view org/worm_learn.clj @ 414:634795361af8

working on wiggling? stream predicate.
author Robert McIntyre <rlm@mit.edu>
date Wed, 19 Mar 2014 15:59:46 -0400
parents 54ef2e06c3ef
children af7945c27474
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 [[370 :d-flex 40]
85 [600 :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 ;; Normally, we'd use unsupervised/supervised machine learning to pick
110 ;; out the defining features of the different actions available to the
111 ;; worm. For this project, I am going to explicitely define functions
112 ;; that recognize curling and wiggling respectively. These functions
113 ;; are defined using all the information available from an embodied
114 ;; simulation of the action. Note how much easier they are to define
115 ;; than if I only had vision to work with. Things like scale/position
116 ;; invariance are complete non-issues here. This is the advantage of
117 ;; body-centered action recognition and what I hope to show with this
118 ;; thesis.
121 (defn straight?
122 "Is the worm straight?"
123 [experiences]
124 (every?
125 (fn [[_ _ bend]]
126 (< (Math/sin bend) 0.05))
127 (:proprioception (peek experiences))))
129 (defn curled?
130 "Is the worm curled up?"
131 [experiences]
132 (every?
133 (fn [[_ _ bend]]
134 (> (Math/sin bend) 0.64))
135 (:proprioception (peek experiences))))
137 (defn grand-circle?
138 "Does the worm form a majestic circle (one end touching the other)?"
139 [experiences]
140 (and (curled? experiences)
141 true)) ;; TODO: add code here.
143 (defn vector:last-n [v n]
144 (let [c (count v)]
145 (if (< c n) v
146 (subvec v (- c n) c))))
148 (defn touch-average [[coords touch]]
149 (/ (average (map first touch)) (average (map second touch))))
151 (defn rect-region [[x0 y0] [x1 y1]]
152 (vec
153 (for [x (range x0 (inc x1))
154 y (range y0 (inc y1))]
155 [x y])))
157 (def worm-segment-touch-bottom (rect-region [8 15] [14 22]))
159 (defn contact
160 "Determine how much contact a particular worm segment has with
161 other objects. Returns a value between 0 and 1, where 1 is full
162 contact and 0 is no contact."
163 [[coords contact :as touch]]
164 (-> (zipmap coords contact)
165 (select-keys worm-segment-touch-bottom)
166 (vals)
167 (#(map first %))
168 (average)
169 (* 10)
170 (- 1)
171 (Math/abs)))
173 (defn fft [nums]
174 (map
175 #(.getReal %)
176 (.transform
177 (FastFourierTransformer. DftNormalization/STANDARD)
178 (double-array nums) TransformType/FORWARD)))
180 (def indexed (partial map-indexed vector))
182 (defn max-indexed [s]
183 (first (sort-by (comp - second) (indexed s))))
186 (defn wiggling?
187 "Is the worm wiggling?"
188 [experiences]
189 (let [analysis-interval 0x40]
190 (when (> (count experiences) analysis-interval)
191 (let [a-flex 3
192 a-ex 2
193 muscle-activity
194 (map :muscle (vector:last-n experiences analysis-interval))
195 base-activity
196 (map #(- (% a-flex) (% a-ex)) muscle-activity)]
197 (= 2
198 (first
199 (max-indexed (map #(Math/abs %) (take 20 (fft base-activity))))))))))
201 ;; (println-repl
202 ;; (apply format "%d %.2f"
203 ;; (first (sort-by
204 ;; (comp - second)
205 ;; (indexed (take 20 ))))))))))
207 ;; (println-repl
208 ;; (apply
209 ;; format
210 ;; (apply str (repeat analysis-interval "%5.1f"))
211 ;; (fft base-activity)))
213 ;; ;;(println-repl (last base-activity))
214 ;; )))
218 (def standard-world-view
219 [(Vector3f. 4.207176, -3.7366982, 3.0816958)
220 (Quaternion. 0.11118768, 0.87678415, 0.24434438, -0.3989771)])
222 (def worm-side-view
223 [(Vector3f. 4.207176, -3.7366982, 3.0816958)
224 (Quaternion. -0.11555642, 0.88188726, -0.2854942, -0.3569518)])
226 (def degenerate-worm-view
227 [(Vector3f. -0.0708936, -8.570261, 2.6487997)
228 (Quaternion. -2.318909E-4, 0.9985348, 0.053941682, 0.004291452)])
230 (defn worm-world-defaults []
231 (let [direct-control (worm-direct-control worm-muscle-labels 40)]
232 {:view worm-side-view
233 :motor-control (:motor-control direct-control)
234 :keybindings (:keybindings direct-control)
235 :record nil
236 :experiences nil
237 :worm-model worm-model
238 :end-frame nil}))
240 (defn dir! [file]
241 (if-not (.exists file)
242 (.mkdir file))
243 file)
245 (defn record-experience! [experiences data]
246 (swap! experiences #(conj % data)))
248 (defn worm-world
249 [& {:keys [record motor-control keybindings view experiences
250 worm-model end-frame] :as settings}]
251 (let [{:keys [record motor-control keybindings view experiences
252 worm-model end-frame]}
253 (merge (worm-world-defaults) settings)
254 worm (doto (worm-model) (body!))
255 touch (touch! worm)
256 prop (proprioception! worm)
257 muscles (movement! worm)
259 touch-display (view-touch)
260 prop-display (view-proprioception)
261 muscle-display (view-movement)
263 floor (box 10 1 10 :position (Vector3f. 0 -10 0)
264 :color ColorRGBA/Gray :mass 0)
265 timer (IsoTimer. 60)]
267 (world
268 (nodify [worm floor])
269 (merge standard-debug-controls keybindings)
270 (fn [world]
271 (position-camera world view)
272 (.setTimer world timer)
273 (display-dilated-time world timer)
274 (if record
275 (Capture/captureVideo
276 world
277 (dir! (File. record "main-view"))))
278 (speed-up world)
279 (light-up-everything world))
280 (fn [world tpf]
281 (if (and end-frame (> (.getTime timer) end-frame))
282 (.stop world))
283 (let [muscle-data (vec (motor-control muscles))
284 proprioception-data (prop)
285 touch-data (map #(% (.getRootNode world)) touch)]
286 (when experiences
287 (record-experience!
288 experiences {:touch touch-data
289 :proprioception proprioception-data
290 :muscle muscle-data})
291 ;;(if (curled? @experiences) (println "Curled"))
292 ;;(if (straight? @experiences) (println "Straight"))
293 ;; (println-repl
294 ;; (apply format "%.2f %.2f %.2f %.2f %.2f\n"
295 ;; (map contact touch-data)))
296 (wiggling? @experiences)
297 )
298 (muscle-display
299 muscle-data
300 (if record (dir! (File. record "muscle"))))
301 (prop-display
302 proprioception-data
303 (if record (dir! (File. record "proprio"))))
304 (touch-display
305 touch-data
306 (if record (dir! (File. record "touch")))))))))