1 (ns neural-net.som-gui.clj
4 (:import (java.awt Color Graphics Dimension)
5 (java.awt.image BufferedImage)
6 (javax.swing JPanel JFrame)))
8 ;; evolved from example gui code in Rich Hickey's Ants demo
9 ;; (see http://clojure.googlegroups.com/web/ants.clj)
14 (defn render-net [#^Graphics o #^neural-net.core.Graph g]
15 (let [pos (comp (partial + (* scale (/ dim 2))) (partial * scale))
16 x (comp pos first) y (comp pos second)]
18 (for [w (map :weights (vals (get g :vertices)))]
19 (doto o (.setColor (. Color black))
20 (.drawOval (x w) (y w) 5 5)
21 (.fillOval (x w) (y w) 5 5))))
23 (for [[a b] (get g :edges)]
24 (let [a ((get (get g :vertices) a) :weights)
25 b ((get (get g :vertices) b) :weights )]
26 (doto o (.setColor (. Color black))
27 (.drawLine (x a) (y a) (x b) (y b))))))))
30 (let [img (new BufferedImage (* scale dim) (* scale dim)
31 (. BufferedImage TYPE_INT_ARGB))
32 bg (. img (getGraphics))]
34 (.setColor (. Color white))
35 (.fillRect 0 0 (. img (getWidth)) (. img (getHeight))))
36 (render-net bg (@net :map))
37 (. g (drawImage img 0 0 nil))
40 (def panel (doto (proxy [JPanel] []
41 (paint [g] (render g)))
42 (.setPreferredSize (new Dimension
46 (def frame (doto (new JFrame) (.add panel) .pack .show))
48 (comment ) ; interactively re-paint the frame
51 (def animator (agent nil))
53 (def animation-sleep-ms 500)
58 (when running (send-off *agent* #'animation))
60 (. Thread (sleep animation-sleep-ms))
64 (let [som {:phi self-organizing-map:run
65 :learn self-organizing-map:learn
66 :train self-organizing-map:train
68 :update (fn [this dist n x]
69 (map (fn [x] (* (/ x (inc dist)) (this :eta)))
71 x (((get (this :map) :vertices) n) :weights))))
72 :map (neural-net.core.Graph.
76 :d {:weights [ 0 -2]}}
77 [[:a :b] [:b :c] [:c :d]])}
84 (dosync (ref-set net som))
86 (. Thread (sleep 1000))
87 (when (not (empty? xs))
88 (recur (second (train som (first xs) nil nil)) (rest xs)))))