view org/worm_learn.clj @ 429:b5d0f0adf19f

improvements by Dylan!
author Robert McIntyre <rlm@mit.edu>
date Fri, 21 Mar 2014 20:56:56 -0400
parents 7f3581dc58ff
children 5205535237fb
line wrap: on
line source
1 (ns org.aurellem.worm-learn
2 "General worm creation framework."
3 {:author "Robert McIntyre"}
4 (:use (cortex world util import body sense
5 hearing touch vision proprioception movement
6 test))
7 (:import (com.jme3.math ColorRGBA Vector3f))
8 (:import java.io.File)
9 (:import com.jme3.audio.AudioNode)
10 (:import com.aurellem.capture.RatchetTimer)
11 (:import (com.aurellem.capture Capture IsoTimer))
12 (:import (com.jme3.math Vector3f ColorRGBA)))
14 (import org.apache.commons.math3.transform.TransformType)
15 (import org.apache.commons.math3.transform.FastFourierTransformer)
16 (import org.apache.commons.math3.transform.DftNormalization)
18 (use 'clojure.pprint)
19 (use 'clojure.set)
20 (dorun (cortex.import/mega-import-jme3))
21 (rlm.rlm-commands/help)
23 (load-bullet)
25 (def hand "Models/test-creature/hand.blend")
27 (defn worm-model []
28 (load-blender-model "Models/worm/worm.blend"))
30 (def output-base (File. "/home/r/proj/cortex/render/worm-learn/curl"))
33 (defn motor-control-program
34 "Create a function which will execute the motor script"
35 [muscle-labels
36 script]
37 (let [current-frame (atom -1)
38 keyed-script (group-by first script)
39 current-forces (atom {}) ]
40 (fn [effectors]
41 (let [indexed-effectors (vec effectors)]
42 (dorun
43 (for [[_ part force] (keyed-script (swap! current-frame inc))]
44 (swap! current-forces (fn [m] (assoc m part force)))))
45 (doall (map (fn [effector power]
46 (effector (int power)))
47 effectors
48 (map #(@current-forces % 0) muscle-labels)))))))
50 (defn worm-direct-control
51 "Create keybindings and a muscle control program that will enable
52 the user to control the worm via the keyboard."
53 [muscle-labels activation-strength]
54 (let [strengths (mapv (fn [_] (atom 0)) muscle-labels)
55 activator
56 (fn [n]
57 (fn [world pressed?]
58 (let [strength (if pressed? activation-strength 0)]
59 (swap! (nth strengths n) (constantly strength)))))
60 activators
61 (map activator (range (count muscle-labels)))
62 worm-keys
63 ["key-f" "key-r"
64 "key-g" "key-t"
65 "key-h" "key-y"
66 "key-j" "key-u"
67 "key-k" "key-i"
68 "key-l" "key-o"]]
69 {:motor-control
70 (fn [effectors]
71 (doall
72 (map (fn [strength effector]
73 (effector (deref strength)))
74 strengths effectors)))
75 :keybindings
76 ;; assume muscles are listed in pairs and map them to keys.
77 (zipmap worm-keys activators)}))
79 ;; These are scripts that direct the worm to move in two radically
80 ;; different patterns -- a sinusoidal wiggling motion, and a curling
81 ;; motions that causes the worm to form a circle.
83 (def curl-script
84 [[150 :d-flex 40]
85 [250 :d-flex 0]])
87 (def period 18)
89 (def worm-muscle-labels
90 [:base-ex :base-flex
91 :a-ex :a-flex
92 :b-ex :b-flex
93 :c-ex :c-flex
94 :d-ex :d-flex])
96 (defn gen-wiggle [[flexor extensor :as muscle-pair] time-base]
97 (let [period period
98 power 45]
99 [[time-base flexor power]
100 [(+ time-base period) flexor 0]
101 [(+ time-base period 1) extensor power]
102 [(+ time-base (+ (* 2 period) 2)) extensor 0]]))
104 (def wiggle-script
105 (mapcat gen-wiggle (repeat 4000 [:a-ex :a-flex])
106 (range 100 1000000 (+ 3 (* period 2)))))
109 (defn shift-script [shift script]
110 (map (fn [[time label power]] [(+ time shift) label power])
111 script))
113 (def do-all-the-things
114 (concat
115 curl-script
116 [[300 :d-ex 40]
117 [320 :d-ex 0]]
118 (shift-script 280 (take 16 wiggle-script))))
120 ;; Normally, we'd use unsupervised/supervised machine learning to pick
121 ;; out the defining features of the different actions available to the
122 ;; worm. For this project, I am going to explicitely define functions
123 ;; that recognize curling and wiggling respectively. These functions
124 ;; are defined using all the information available from an embodied
125 ;; simulation of the action. Note how much easier they are to define
126 ;; than if I only had vision to work with. Things like scale/position
127 ;; invariance are complete non-issues here. This is the advantage of
128 ;; body-centered action recognition and what I hope to show with this
129 ;; thesis.
132 ;; curled? relies on proprioception, resting? relies on touch,
133 ;; wiggling? relies on a fourier analysis of muscle contraction, and
134 ;; grand-circle? relies on touch and reuses curled? as a gaurd.
136 (defn curled?
137 "Is the worm curled up?"
138 [experiences]
139 (every?
140 (fn [[_ _ bend]]
141 (> (Math/sin bend) 0.64))
142 (:proprioception (peek experiences))))
144 (defn touch-average [[coords touch]]
145 (/ (average (map first touch)) (average (map second touch))))
147 (defn rect-region [[x0 y0] [x1 y1]]
148 (vec
149 (for [x (range x0 (inc x1))
150 y (range y0 (inc y1))]
151 [x y])))
153 (def worm-segment-bottom (rect-region [8 15] [14 22]))
155 (defn contact
156 "Determine how much contact a particular worm segment has with
157 other objects. Returns a value between 0 and 1, where 1 is full
158 contact and 0 is no contact."
159 [touch-region [coords contact :as touch]]
160 (-> (zipmap coords contact)
161 (select-keys touch-region)
162 (vals)
163 (#(map first %))
164 (average)
165 (* 10)
166 (- 1)
167 (Math/abs)))
169 (defn resting?
170 "Is the worm straight?"
171 [experiences]
172 (every?
173 (fn [touch-data]
174 (< 0.9 (contact worm-segment-bottom touch-data)))
175 (:touch (peek experiences))))
177 (defn vector:last-n [v n]
178 (let [c (count v)]
179 (if (< c n) v
180 (subvec v (- c n) c))))
182 (defn fft [nums]
183 (map
184 #(.getReal %)
185 (.transform
186 (FastFourierTransformer. DftNormalization/STANDARD)
187 (double-array nums) TransformType/FORWARD)))
189 (def indexed (partial map-indexed vector))
191 (defn max-indexed [s]
192 (first (sort-by (comp - second) (indexed s))))
194 (defn wiggling?
195 "Is the worm wiggling?"
196 [experiences]
197 (let [analysis-interval 0x40]
198 (when (> (count experiences) analysis-interval)
199 (let [a-flex 3
200 a-ex 2
201 muscle-activity
202 (map :muscle (vector:last-n experiences analysis-interval))
203 base-activity
204 (map #(- (% a-flex) (% a-ex)) muscle-activity)]
205 (= 2
206 (first
207 (max-indexed
208 (map #(Math/abs %)
209 (take 20 (fft base-activity))))))))))
211 (def worm-segment-bottom-tip (rect-region [15 15] [22 22]))
213 (def worm-segment-top-tip (rect-region [0 15] [7 22]))
215 (defn grand-circle?
216 "Does the worm form a majestic circle (one end touching the other)?"
217 [experiences]
218 (and (curled? experiences)
219 (let [worm-touch (:touch (peek experiences))
220 tail-touch (worm-touch 0)
221 head-touch (worm-touch 4)]
222 (and (< 0.55 (contact worm-segment-bottom-tip tail-touch))
223 (< 0.55 (contact worm-segment-top-tip head-touch))))))
226 (declare phi-space phi-scan)
228 (defn next-phi-states
229 "Given proprioception data, determine the most likely next sensory
230 pattern from previous experience."
231 [proprio phi-space phi-scan]
232 (if-let [results (phi-scan proprio)]
233 (mapv phi-space
234 (filter (partial > (count phi-space))
235 (map inc results)))))
237 (defn debug-experience
238 [experiences]
239 (cond
240 (grand-circle? experiences) (println "Grand Circle")
241 (curled? experiences) (println "Curled")
242 (wiggling? experiences) (println "Wiggling")
243 (resting? experiences) (println "Resting")))
246 (def standard-world-view
247 [(Vector3f. 4.207176, -3.7366982, 3.0816958)
248 (Quaternion. 0.11118768, 0.87678415, 0.24434438, -0.3989771)])
250 (def worm-side-view
251 [(Vector3f. 4.207176, -3.7366982, 3.0816958)
252 (Quaternion. -0.11555642, 0.88188726, -0.2854942, -0.3569518)])
254 (def degenerate-worm-view
255 [(Vector3f. -0.0708936, -8.570261, 2.6487997)
256 (Quaternion. -2.318909E-4, 0.9985348, 0.053941682, 0.004291452)])
258 (defn worm-world-defaults []
259 (let [direct-control (worm-direct-control worm-muscle-labels 40)]
260 {:view worm-side-view
261 :motor-control (:motor-control direct-control)
262 :keybindings (:keybindings direct-control)
263 :record nil
264 :experiences (atom [])
265 :experience-watch debug-experience
266 :worm-model worm-model
267 :end-frame nil}))
269 (defn dir! [file]
270 (if-not (.exists file)
271 (.mkdir file))
272 file)
274 (defn record-experience! [experiences data]
275 (swap! experiences #(conj % data)))
277 (defn worm-world
278 [& {:keys [record motor-control keybindings view experiences
279 worm-model end-frame experience-watch] :as settings}]
280 (let [{:keys [record motor-control keybindings view experiences
281 worm-model end-frame experience-watch]}
282 (merge (worm-world-defaults) settings)
283 worm (doto (worm-model) (body!))
284 touch (touch! worm)
285 prop (proprioception! worm)
286 muscles (movement! worm)
288 touch-display (view-touch)
289 prop-display (view-proprioception)
290 muscle-display (view-movement)
292 floor (box 10 1 10 :position (Vector3f. 0 -10 0)
293 :color ColorRGBA/Gray :mass 0)
294 timer (IsoTimer. 60)]
296 (world
297 (nodify [worm floor])
298 (merge standard-debug-controls keybindings)
299 (fn [world]
300 (position-camera world view)
301 (.setTimer world timer)
302 (display-dilated-time world timer)
303 (if record
304 (Capture/captureVideo
305 world
306 (dir! (File. record "main-view"))))
307 (speed-up world)
308 (light-up-everything world))
309 (fn [world tpf]
310 (if (and end-frame (> (.getTime timer) end-frame))
311 (.stop world))
312 (let [muscle-data (vec (motor-control muscles))
313 proprioception-data (prop)
314 touch-data (mapv #(% (.getRootNode world)) touch)]
315 (when experiences
316 (record-experience!
317 experiences {:touch touch-data
318 :proprioception proprioception-data
319 :muscle muscle-data}))
320 (when experience-watch
321 (experience-watch @experiences))
322 (muscle-display
323 muscle-data
324 (if record (dir! (File. record "muscle"))))
325 (prop-display
326 proprioception-data
327 (if record (dir! (File. record "proprio"))))
328 (touch-display
329 touch-data
330 (if record (dir! (File. record "touch")))))))))
334 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
335 ;;;;;;;; Phi-Space ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
336 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
338 (defn generate-phi-space []
339 (let [experiences (atom [])]
340 (run-world
341 (apply-map
342 worm-world
343 (merge
344 (worm-world-defaults)
345 {:end-frame 700
346 :motor-control
347 (motor-control-program worm-muscle-labels do-all-the-things)
348 :experiences experiences})))
349 @experiences))
351 (defn bin [digits]
352 (fn [angles]
353 (->> angles
354 (flatten)
355 (map (juxt #(Math/sin %) #(Math/cos %)))
356 (flatten)
357 (mapv #(Math/round (* % (Math/pow 10 (dec digits))))))))
359 ;; k-nearest neighbors with spatial binning. Only returns a result if
360 ;; the propriceptive data is within 10% of a previously recorded
361 ;; result in all dimensions.
362 (defn gen-phi-scan [phi-space]
363 (let [bin-keys (map bin [3 2 1])
364 bin-maps
365 (map (fn [bin-key]
366 (group-by
367 (comp bin-key :proprioception phi-space)
368 (range (count phi-space)))) bin-keys)
369 lookups (map (fn [bin-key bin-map]
370 (fn [proprio] (bin-map (bin-key proprio))))
371 bin-keys bin-maps)]
372 (fn lookup [proprio-data]
373 (set (some #(% proprio-data) lookups)))))
376 (defn longest-thread
377 "Find the longest thread from phi-index-sets. The index sets should
378 be ordered from most recent to least recent."
379 [phi-index-sets]
380 (loop [result '()
381 [thread-bases & remaining :as phi-index-sets] phi-index-sets]
382 (if (empty? phi-index-sets)
383 (vec result)
384 (let [threads
385 (for [thread-base thread-bases]
386 (loop [thread (list thread-base)
387 remaining remaining]
388 (let [next-index (dec (first thread))]
389 (cond (empty? remaining) thread
390 (contains? (first remaining) next-index)
391 (recur
392 (cons next-index thread) (rest remaining))
393 :else thread))))
394 longest-thread
395 (reduce (fn [thread-a thread-b]
396 (if (> (count thread-a) (count thread-b))
397 thread-a thread-b))
398 '(nil)
399 threads)]
400 (recur (concat longest-thread result)
401 (drop (count longest-thread) phi-index-sets))))))
404 (defn init []
405 (def phi-space (generate-phi-space))
406 (def phi-scan (gen-phi-scan phi-space))
407 )
413 (defn infer-nils
414 "Replace nils with the next available non-nil element in the
415 sequence, or barring that, 0."
416 [s]
417 (loop [i (dec (count s)) v (transient s)]
418 (if (= i 0) (persistent! v)
419 (let [cur (v i)]
420 (if cur
421 (if (get v (dec i) 0)
422 (recur (dec i) v)
423 (recur (dec i) (assoc! v (dec i) cur)))
424 (recur i (assoc! v i 0)))))))
426 ;; tests
428 ;;(infer-nils [1 nil 1 1]) [1 1 1 1]
429 ;;(infer-nils [1 1 1 nil]) [1 1 1 0]
430 ;;(infer-nils [nil 2 1 1]) [2 2 1 1]
433 (defn debug-experience-phi []
434 (let [proprio (atom ())]
435 (fn
436 [experiences]
437 (let [phi-indices (phi-scan (:proprioception (peek experiences)))]
438 (swap! proprio (partial cons phi-indices))
439 (let [exp-thread (longest-thread (take 300 @proprio))
440 phi-loop (mapv phi-space (infer-nils exp-thread))]
441 (println-repl (vector:last-n exp-thread 22))
442 (cond
443 (grand-circle? phi-loop) (println "Grand Circle")
444 (curled? phi-loop) (println "Curled")
445 (wiggling? phi-loop) (println "Wiggling")
446 (resting? phi-loop) (println "Resting")
447 :else (println "Unknown")))))))
450 (defn init-interactive []
451 (def phi-space
452 (let [experiences (atom [])]
453 (run-world
454 (apply-map
455 worm-world
456 (merge
457 (worm-world-defaults)
458 {:experiences experiences})))
459 @experiences))
460 (def phi-scan (gen-phi-scan phi-space)))
463 (defn run-experiment-1 []
464 (.start (worm-world :experience-watch (debug-experience-phi))))