utils.cljs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. (ns microtables-frontend.utils
  2. (:require
  3. ["mathjs" :as mathjs]))
  4. ; to add an npm package to shadow-cljs:
  5. ; https://clojureverse.org/t/guide-on-how-to-use-import-npm-modules-packages-in-clojurescript/2298
  6. ; https://shadow-cljs.github.io/docs/UsersGuide.html#npm
  7. (defn highest-col
  8. "Return the highest column (letter) for which there is a non-empty cell"
  9. [data]
  10. ; choose the "max" (alphabetical order) value among the longest keys
  11. (apply max (val (apply max-key key (group-by #(.-length %) (keys data))))))
  12. (defn highest-row
  13. "Return the highest row (number) for which there is a non-empty cell"
  14. [data]
  15. ; get all the row keys from all the column objects (and flatten), then pick the max
  16. (apply max (flatten (map keys (vals data)))))
  17. (defn increment-letter-code [s]
  18. (let [l (last s)]
  19. (cond
  20. (empty? s) [65]
  21. (= l 90) (conj (increment-letter-code (subvec s 0 (dec (count s)))) 65)
  22. :else (conj (subvec s 0 (dec (count s))) (inc l)))))
  23. (defn next-letter [lc]
  24. (apply str (map char (increment-letter-code (mapv #(.charCodeAt % 0) lc)))))
  25. (def col-letters (iterate next-letter "A"))
  26. (defn get-datum [data c r]
  27. (some #(if (and (= c (:col %)) (= r (:row %))) %) data))
  28. (def parse-variables (memoize (fn [expression]
  29. (as-> (js->clj (.parse mathjs expression)) $
  30. (.filter $ #(true? (.-isSymbolNode %)))
  31. (map #(.-name %) $)
  32. (map #(.toUpperCase %) $)
  33. (filter #(re-matches #"[A-Z]+[0-9]+" %) $)))))
  34. (def str->rc (memoize (fn [s]
  35. (let [c (re-find #"^[A-Z]+" s)
  36. r (.parseInt js/window (re-find #"[0-9]+$" s))]
  37. {:row r :col c}))))
  38. (defn add-parsed-variables [datum]
  39. (if (= (first (:value datum)) "=")
  40. (let [vars (parse-variables (subs (:value datum) 1))
  41. refs (map str->rc vars)]
  42. (-> datum (assoc :vars vars) (assoc :refs refs) (dissoc :error)))
  43. (-> datum (dissoc :vars) (dissoc :refs) (dissoc :display) (dissoc :error))))
  44. ; leave in the :inbound references, since they probably have not have changed
  45. (defn add-references
  46. "Parses the expression in the value of a datum, and adds vars and refs as necessary"
  47. [datum]
  48. (if (= (first (:value datum)) "=")
  49. (let [vars (parse-variables (subs (:value datum) 1))
  50. refs (map str->rc vars)]
  51. (-> datum
  52. (assoc :vars vars)
  53. (assoc :refs refs)
  54. (dissoc :error)))
  55. (-> datum
  56. (dissoc :vars)
  57. (dissoc :refs)
  58. (dissoc :display)
  59. (dissoc :error))))
  60. ; the references in the data are a set of disconnected, doubly-linked trees
  61. ;TODO: rather than denotify all, then re-notify all, maybe use a diff? maybe on small scales it's not worth it?
  62. (defn denotify-references
  63. "Remove references in all cells formerly referenced by this cell"
  64. [data origin refs]
  65. (if (empty? refs)
  66. data
  67. (let [target (first refs)
  68. de-notified (update-in data [(:col target) (:row target) :inbound] (partial filter #(not= % origin)))]
  69. (recur de-notified origin (rest refs)))))
  70. (defn notify-references
  71. "Update references in all cells referenced by this cell"
  72. [data origin refs]
  73. (if (empty? refs)
  74. data
  75. (let [target (first refs)
  76. notified (update-in data [(:col target) (:row target) :inbound] conj origin)]
  77. (recur notified origin (rest refs)))))
  78. (defn create-all-references
  79. "Starting from a clean slate, add in all references. This wipes any references that may have been present."
  80. [data]
  81. (reduce-kv
  82. (fn [columns c curr-column]
  83. (assoc columns c (reduce-kv
  84. (fn [rows r datum]
  85. (assoc rows r (add-references (dissoc (dissoc datum :refs) :inbound))))
  86. {}
  87. curr-column)))
  88. {}
  89. data))
  90. ;TODO: re-write create-all-references to use walk-modify-data instead
  91. (defn walk-modify-data
  92. "Walks through the data map and updates each datum by applying f (a function accepting col, row, datum)."
  93. [data f]
  94. (reduce-kv
  95. (fn [columns c curr-column]
  96. (assoc columns c (reduce-kv
  97. (fn [rows r datum]
  98. (assoc rows r (f c r datum)))
  99. {}
  100. curr-column)))
  101. {}
  102. data))
  103. (defn walk-get-refs
  104. "Walks through the data map and returns a list of :col/:row maps for each cell which satisfies the predicate (a function accepting col, row, datum)."
  105. [data pred]
  106. (reduce-kv (fn [l c column] (concat l (map (fn [[r _]] {:col c :row r}) (filter (fn [[r datum]] (pred c r datum)) column)))) '() data))
  107. (defn create-all-back-references
  108. "Assuming all references have been added, insert all back references."
  109. [data]
  110. (loop [data data
  111. formulas (walk-get-refs data #(= (first (:value %3)) "="))]
  112. (if (empty? formulas)
  113. data
  114. (let [origin (first formulas)
  115. refs (get-in data [(:col origin) (:row origin) :refs])
  116. updated-one (notify-references data origin refs)]
  117. (recur updated-one (rest formulas))))))
  118. (defn set-dirty-flags
  119. "Sets the target cell to \"dirty\" and recursively repeat with its back-references all the way up. Returns the new data set."
  120. ([data c r]
  121. (set-dirty-flags data (list {:col c :row r})))
  122. ([data queue]
  123. (if (empty? queue)
  124. data
  125. (let [cur (first queue)
  126. c (:col cur)
  127. r (:row cur)
  128. datum (get-in data [c r])]
  129. (if (true? (:dirty datum))
  130. (recur data (rest queue))
  131. (let [new-data (assoc-in data [c r :dirty] true)
  132. new-queue (concat (rest queue) (:inbound datum))]
  133. (recur new-data new-queue)))))))
  134. (defn change-datum-value
  135. "Modify the value of a datum in the table, and update all applicable references"
  136. [data c r value]
  137. (let [datum (get-in data [c r])
  138. updated (assoc datum :value value)]
  139. (-> data
  140. (assoc-in [c r :value] value)
  141. (set-dirty-flags c r))))
  142. (defn reset-references
  143. "If there has been a change to which cells are referenced by this cell, then change the necessary back-references to this cell."
  144. [data c r]
  145. (let [datum (get-in data [c r])
  146. parsed (add-references datum)]
  147. (if (= (:refs datum) (:refs parsed))
  148. data
  149. (-> data
  150. (assoc-in [c r] parsed)
  151. (denotify-references {:col c :row r} (:refs datum))
  152. (notify-references {:col c :row r} (:refs parsed))))))
  153. (def evaluate-expression
  154. "Convert (via mathjs) an expression string to a final answer (also a string). A map of variables must also be provided. If there is an error, it will return :calc-error."
  155. (memoize (fn [expression variables]
  156. (try
  157. (.evaluate mathjs expression (clj->js variables))
  158. (catch js/Error e
  159. (println "mathjs evaluation error" (.-message e) e)
  160. :calc-error)))))
  161. ;TODO: deal with lowercase cell references
  162. ;TODO: memoize dynamically? probably not worth memoizing directly, and could take up too much memory over time
  163. ; https://stackoverflow.com/a/13123571/8172807
  164. (defn find-cycle
  165. "Accepts the data and a datum, and peforms a depth-first search to find reference cycles, following back-references."
  166. ([data c r] (find-cycle data c r #{}))
  167. ([data c r ancest]
  168. (let [datum (get-in data [c r])
  169. current {:col c :row r}
  170. this-and-above (conj ancest current)
  171. inbound (:inbound datum)
  172. found-repeat (not (empty? (clojure.set/intersection this-and-above (set inbound))))]
  173. (if found-repeat
  174. :cycle-error
  175. (some #(find-cycle data (:col %) (:row %) this-and-above) inbound)))))
  176. (defn gather-variables-and-evaluate-cell
  177. "Assumes that all the cell's immediate references have been resolved. Collects the final values from them, then evaluates the current cell's expression. Returns the new data map."
  178. [data c r]
  179. (let [datum (dissoc (dissoc (get-in data [c r]) :dirty) :display) ; get rid of the dirty flag right away (it must be included with the returned data to have effect)
  180. refs (:refs datum)
  181. value (:value datum)
  182. formula? (= (first value) "=")
  183. resolved-refs (map #(merge % (get-in data [(:col %) (:row %)])) refs)
  184. evaluated-refs (map #(if (= (first (:value %)) "=") (:display %) (:value % "0")) resolved-refs)
  185. invalid-refs (some nil? resolved-refs)
  186. dirty-refs (some :dirty resolved-refs)
  187. error-refs (some #(= (:display %) :error) resolved-refs)
  188. unevaluated-refs (some nil? evaluated-refs)
  189. cycle-refs (some #(= (:display %) :cycle-error) resolved-refs)
  190. disqualified? (or invalid-refs dirty-refs error-refs)]
  191. (cond
  192. (false? formula?) (assoc-in data [c r] datum) ; if it's not a formula, then return as is (with the dirty flag removed)
  193. cycle-refs (-> data ; if one of its references has a reference cycle, then this one is "poisoned" as well
  194. (assoc-in [c r] datum)
  195. (assoc-in [c r :display] :cycle-error))
  196. unevaluated-refs (assoc-in data [c r :display] :insufficient-data) ; do not un-mark as "dirty", since it has not been evaluated yet
  197. disqualified? (-> data ; some other error is present
  198. (assoc-in [c r] datum)
  199. (assoc-in [c r :display] :error))
  200. (empty? refs) (-> data
  201. (assoc-in [c r] datum)
  202. (assoc-in [c r :display] (evaluate-expression (subs value 1) {})))
  203. :else (let [variables (zipmap (map #(str (:col %) (:row %)) refs) evaluated-refs)
  204. evaluated-value (evaluate-expression (subs value 1) variables)
  205. new-datum (assoc datum :display evaluated-value)]
  206. (assoc-in data [c r] new-datum)))))
  207. ; THE NEW EVALUATE FUNCTION
  208. ; - check for cycles in the back references, starting from the target cell (if any, use another function to mark it and its back references with :cycle-error and remove :dirty)
  209. ; - if any of the forward references are dirty, mark the cell (and recurse up) with an error (and set a TODO to think about this further)
  210. ; - evaluate (using forward references if necessary)
  211. ; - add all back-references to the queue
  212. ; - recurse
  213. ; - TODO: consider initialization case
  214. ; - TODO: consider multiple cells modified simultaneously
  215. (defn evaluate-from-cell
  216. "Evaluate the final value of a cell, and recursively re-evaluate all the cells that reference it."
  217. [data c r]
  218. (let [cycles? (find-cycle data c r)
  219. new-data (if cycles?
  220. (-> data ; if there are cycles, mark :cycle-error and remove :dirty (rathan than evaluate) - still need to recurse up the tree to mark dependents with :cycle-error
  221. (update-in [c r] dissoc :dirty)
  222. (assoc-in [c r :display] :cycle-error))
  223. (gather-variables-and-evaluate-cell data c r))] ; if there are no cycles, evaluate the cell
  224. (loop [data new-data
  225. queue (get-in new-data [c r :inbound])]
  226. (if (empty? queue)
  227. data ; if the queue is empty, we're done
  228. (let [current (first queue)
  229. cc (:col current)
  230. cr (:row current)
  231. dirty? (get-in data [cc cr :dirty])
  232. re-evaluated-data (if dirty?
  233. (gather-variables-and-evaluate-cell data cc cr)
  234. data)
  235. sufficient? (not= (get-in re-evaluated-data [cc cr :display]) :insufficient-data)
  236. new-queue (if dirty?
  237. (if sufficient?
  238. (concat (rest queue) (get-in re-evaluated-data [cc cr :inbound])) ; if all is well, then add the back-references onto the queue
  239. (concat (rest queue) (list current))) ; if the current cell's dependencies are not satisfied, re-add to the end of the queue
  240. (rest queue))] ; if the current cell is not marked as dirty, then it has already been processed
  241. (recur re-evaluated-data new-queue))))))
  242. ;TODO: does this need a cycle check?
  243. (defn evaluate-all
  244. "Evaluates all cells marked as \"dirty\". Generally reserved for the initialization."
  245. ([data]
  246. (evaluate-all data (walk-get-refs data #(:dirty %3))))
  247. ([data queue]
  248. (if (empty? queue)
  249. data
  250. (let [cur (first queue)
  251. cc (:col cur)
  252. cr (:row cur)
  253. dirty? (get-in data [cc cr :dirty])]
  254. (if dirty?
  255. (let [evaluated (evaluate-from-cell data (:col cur) (:row cur))
  256. result (get-in evaluated [cc cr :display])]
  257. (if (= result :insufficient-data)
  258. (recur data (concat (rest queue) (list cur)))
  259. (recur evaluated (rest queue))))
  260. (recur data (rest queue)))))))