1 #+TITLE: Concurrent Propagator System
2 #+OPTIONS: num:nil ^:nil
7 :tangle: src/propagator.clj
11 #^{:author "Eric Schulte",
13 :doc "Simple concurrent propagator system."}
15 (:use clojure.contrib.repl-utils clojure.contrib.math))
17 (defmacro cell "Define a new cell."
19 `(def ~name (agent ~state)))
21 (defmacro propagator "Define a new propagator."
22 [name in-cells out-cells & body]
24 (defn ~(with-meta name
26 :in-cells in-cells :out-cells out-cells))
28 (doseq [cell# ~in-cells] (add-neighbor cell# ~name))
31 (defn set-cell "Set the value of a cell" [cell value]
32 (send cell (fn [_] value)))
34 (defmacro run-propagator
35 "Run a propagator, first collect the most recent values from all
36 cells associated with the propagator, then evaluate."
38 `(let [results# (apply ~propagator (map deref (:in-cells ^#'~propagator)))]
39 (doseq [cell# (:out-cells ^#'~propagator)]
40 (when (not (= @cell# results#))
41 (send cell# (fn [_#] results#))))
44 (defmacro add-neighbor "Add a neighbor to the given cell."
48 (agent nil :validator (fn [_#] (do (future (run-propagator ~neighbor)) true)))
52 ** graphs of the propagator network
55 (import '(javax.swing JFrame JPanel)
56 '(java.awt Color Graphics)
57 '(java.awt.image BufferedImage))
63 (defn view "Display a graph generated by vijual" [img]
65 width (* (.getWidth img) mult)
66 height (* (.getHeight img) mult)
68 panel (doto (proxy [JPanel] []
70 (.drawImage g img offset offset nil))))]
71 (doto frame (.add panel) .pack (.setSize (+ offset width) (+ offset height)).show)))
75 ** doubling a number -- simplest
79 (propagator doubler [in] [out] (* 2 in))
80 ;; then any updates to in
82 ;; will propagate to out
86 ** square roots -- heron
95 (propagator enough [x guess] [done]
96 (if (< (abs (- (* guess guess) x)) @margin) true false))
98 (propagator heron [x guess] [guess]
101 (/ (+ guess (/ x guess)) 2.0)))
105 ** look at mutable data stores
106 - http://clojure.org/agents
107 - http://clojure.org/atoms
108 - http://clojure.org/refs
110 most definitely will use agents, functions to set their values are
111 applied to them with send (or send-off if potentially I/O bound), they
112 support validators, and they can be set to run actions (i.e. alert
113 propagators) as part of their update cycle (with add-watcher).
115 ** design to permit distribution across multiple machines
116 it should be possible to wrap these mutable items including
117 - network connections from other machines
118 - hardware (timers, I/O devices, etc...)
120 in cells, so that the propagator system remains "pure"