utils.cljs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 [dir data] (apply max (map dir data)))
  8. (defn highest-col
  9. "Return the highest column (letter) for which there is a non-empty cell"
  10. [data]
  11. ; choose the "max" (alphabetical order) value among the longest keys
  12. (apply max (val (apply max-key key (group-by #(.-length %) (keys data))))))
  13. (defn highest-row
  14. "Return the highest row (number) for which there is a non-empty cell"
  15. [data]
  16. ; get all the row keys from all the column objects (and flatten), then pick the max
  17. (apply max (flatten (map keys (vals data)))))
  18. (defn increment-letter-code [s]
  19. (let [l (last s)]
  20. (cond
  21. (empty? s) [65]
  22. (= l 90) (conj (increment-letter-code (subvec s 0 (dec (count s)))) 65)
  23. :else (conj (subvec s 0 (dec (count s))) (inc l)))))
  24. (defn next-letter [lc]
  25. (apply str (map char (increment-letter-code (mapv #(.charCodeAt % 0) lc)))))
  26. (def col-letters (iterate next-letter "A"))
  27. (defn get-datum [data c r]
  28. (some #(if (and (= c (:col %)) (= r (:row %))) %) data))
  29. (def parse-variables (memoize (fn [expression]
  30. (as-> (js->clj (.parse mathjs expression)) $
  31. (.filter $ #(true? (.-isSymbolNode %)))
  32. (map #(.-name %) $)
  33. (map #(.toUpperCase %) $)
  34. (filter #(re-matches #"[A-Z]+[0-9]+" %) $)))))
  35. (def str->rc (memoize (fn [s]
  36. (let [c (re-find #"^[A-Z]+" s)
  37. r (.parseInt js/window (re-find #"[0-9]+$" s))]
  38. {:row r :col c}))))
  39. (defn add-parsed-variables [datum]
  40. (if (= (first (:value datum)) "=")
  41. (let [vars (parse-variables (subs (:value datum) 1))
  42. refs (map str->rc vars)]
  43. (-> datum (assoc :vars vars) (assoc :refs refs) (dissoc :error)))
  44. (-> datum (dissoc :vars) (dissoc :refs) (dissoc :display) (dissoc :error))))
  45. ; leave in the :inbound references, since they probably have not have changed
  46. (defn add-references
  47. "Parses the expression in the value of a datum, and adds vars and refs as necessary"
  48. [datum]
  49. (if (= (first (:value datum)) "=")
  50. (let [vars (parse-variables (subs (:value datum) 1))
  51. refs (map str->rc vars)]
  52. (-> datum
  53. (assoc :vars vars)
  54. (assoc :refs refs)
  55. (dissoc :error)))
  56. (-> datum
  57. (dissoc :vars)
  58. (dissoc :refs)
  59. (dissoc :display)
  60. (dissoc :error))))
  61. (defn add-parsed-variables-to-specific-datum
  62. "Parse variables from the value of a datum and add in :vars and :refs (for swap! data-atom).
  63. If the value does not contain a fomula, remove any :vars and :refs that may have been there."
  64. [c r data] (map #(if (and (= (:col %) c) (= (:row %) r))
  65. (add-parsed-variables %)
  66. %) data))
  67. ; the references in the data are a set of disconnected, doubly-linked trees
  68. ;TODO: rather than denotify all, then re-notify all, maybe use a diff? maybe on small scales it's not worth it?
  69. (defn denotify-references
  70. "Remove references in all cells formerly referenced by this cell"
  71. [data origin refs]
  72. (if (empty? refs)
  73. data
  74. (let [target (first refs)
  75. de-notified (update-in data [(:col target) (:row target) :inbound] (partial filter #(not= % origin)))]
  76. (recur de-notified origin (rest refs)))))
  77. (defn notify-references
  78. "Update references in all cells referenced by this cell"
  79. [data origin refs]
  80. (if (empty? refs)
  81. data
  82. (let [target (first refs)
  83. notified (update-in data [(:col target) (:row target) :inbound] conj origin)]
  84. (recur notified origin (rest refs)))))
  85. (defn create-all-references
  86. "Starting from a clean slate, add in all references. This wipes any references that may have been present."
  87. [data]
  88. (reduce-kv
  89. (fn [columns c curr-column]
  90. (assoc columns c (reduce-kv
  91. (fn [rows r datum]
  92. (assoc rows r (add-references (dissoc (dissoc datum :refs) :inbound))))
  93. {}
  94. curr-column)))
  95. {}
  96. data))
  97. ;TODO: re-write create-all-references to use walk-modify-data instead
  98. (defn walk-modify-data
  99. "Walks through the data map and updates each datum by applying f (a function accepting col, row, datum)."
  100. [data f]
  101. (reduce-kv
  102. (fn [columns c curr-column]
  103. (assoc columns c (reduce-kv
  104. (fn [rows r datum]
  105. (assoc rows r (f c r datum)))
  106. {}
  107. curr-column)))
  108. {}
  109. data))
  110. (defn walk-get-refs
  111. "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)."
  112. [data pred]
  113. (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))
  114. (defn create-all-back-references
  115. "Assuming all references have been added, insert all back references."
  116. [data]
  117. (loop [data data
  118. formulas (walk-get-refs data #(= (first (:value %3)) "="))]
  119. (if (empty? formulas)
  120. data
  121. (let [origin (first formulas)
  122. refs (get-in data [(:col origin) (:row origin) :refs])
  123. updated-one (notify-references data origin refs)]
  124. (recur updated-one (rest formulas))))))
  125. (defn set-dirty-flags
  126. "Sets the target cell to \"dirty\" and recursively repeat with its back-references all the way up. Returns the new data set."
  127. ([data c r]
  128. (set-dirty-flags data (list {:col c :row r})))
  129. ([data queue]
  130. (if (empty? queue)
  131. data
  132. (let [cur (first queue)
  133. c (:col cur)
  134. r (:row cur)
  135. datum (get-in data [c r])]
  136. (if (true? (:dirty datum))
  137. (recur data (rest queue))
  138. (let [new-data (assoc-in data [c r :dirty] true)
  139. new-queue (concat (rest queue) (:inbound datum))]
  140. (recur new-data new-queue)))))))
  141. (defn change-datum-value
  142. "Modify the value of a datum in the table, and update all applicable references"
  143. [data c r value]
  144. (let [datum (get-in data [c r])
  145. updated (assoc datum :value value)]
  146. (-> data
  147. (assoc-in [c r :value] value)
  148. (set-dirty-flags c r))))
  149. (defn reset-references
  150. "If there has been a change to which cells are referenced by this cell, then change the necessary back-references to this cell."
  151. [data c r]
  152. (let [datum (get-in data [c r])
  153. parsed (add-references datum)]
  154. (if (= (:refs datum) (:refs parsed))
  155. data
  156. (-> data
  157. (assoc-in [c r] parsed)
  158. (denotify-references {:col c :row r} (:refs datum))
  159. (notify-references {:col c :row r} (:refs parsed))))))
  160. (def evaluate-expression
  161. "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."
  162. (memoize (fn [expression variables]
  163. (try
  164. (.evaluate mathjs expression (clj->js variables))
  165. (catch js/Error e
  166. (println "mathjs evaluation error" (.-message e) e)
  167. :calc-error)))))
  168. ;TODO: deal with lowercase cell references
  169. (defn find-cell [data c r]
  170. (some #(if (and (= (:col %) c) (= (:row %) r)) %) data))
  171. (defn find-ref [data cell-ref]
  172. (some (fn [{:keys [row col] :as datum}] (if (and (= row (:row cell-ref)) (= col (:col cell-ref))) datum)) data))
  173. (defn copy-display-values [data display-values]
  174. (let [original (map #(dissoc % :dirty) data)
  175. removed (map #(-> % (dissoc :found) (dissoc :inputs) (dissoc :dirty)) display-values)]
  176. (into original removed)))
  177. ;TODO: memoize dynamically? probably not worth memoizing directly, and could take up too much memory over time
  178. ; https://stackoverflow.com/a/13123571/8172807
  179. (defn find-cycle
  180. ([data datum] (find-cycle data datum #{}))
  181. ([data datum ances]
  182. (let [cur {:row (:row datum) :col (:col datum)}
  183. this-and-above (conj ances cur)
  184. refs (:refs datum)
  185. found (not (empty? (clojure.set/intersection this-and-above (set refs))))]
  186. (if found
  187. :cycle-error
  188. (some (fn [cell]
  189. (find-cycle data (find-ref data cell) this-and-above)) refs)))))
  190. (defn alt-find-cycle
  191. "Accepts the data and a datum, and peforms a depth-first search to find reference cycles, following back-references."
  192. ([data c r] (alt-find-cycle data c r #{}))
  193. ([data c r ancest]
  194. (let [datum (get-in data [c r])
  195. current {:col c :row r}
  196. this-and-above (conj ancest current)
  197. inbound (:inbound datum)
  198. found-repeat (not (empty? (clojure.set/intersection this-and-above (set inbound))))]
  199. (if found-repeat
  200. :cycle-error
  201. (some #(alt-find-cycle data (:col %) (:row %) this-and-above) inbound)))))
  202. (defn gather-variables-and-evaluate-cell
  203. "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."
  204. [data c r]
  205. (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)
  206. refs (:refs datum)
  207. value (:value datum)
  208. formula? (= (first value) "=")
  209. resolved-refs (map #(merge % (get-in data [(:col %) (:row %)])) refs)
  210. evaluated-refs (map #(if (= (first (:value %)) "=") (:display %) (:value % "0")) resolved-refs)
  211. invalid-refs (some nil? resolved-refs)
  212. dirty-refs (some :dirty resolved-refs)
  213. error-refs (some #(= (:display %) :error) resolved-refs)
  214. unevaluated-refs (some nil? evaluated-refs)
  215. cycle-refs (some #(= (:display %) :cycle-error) resolved-refs)
  216. disqualified? (or invalid-refs dirty-refs error-refs)]
  217. (cond
  218. (false? formula?) (assoc-in data [c r] datum) ; if it's not a formula, then return as is (with the dirty flag removed)
  219. cycle-refs (-> data ; if one of its references has a reference cycle, then this one is "poisoned" as well
  220. (assoc-in [c r] datum)
  221. (assoc-in [c r :display] :cycle-error))
  222. unevaluated-refs (assoc-in data [c r :display] :insufficient-data) ; do not un-mark as "dirty", since it has not been evaluated yet
  223. disqualified? (-> data ; some other error is present
  224. (assoc-in [c r] datum)
  225. (assoc-in [c r :display] :error))
  226. (empty? refs) (-> data
  227. (assoc-in [c r] datum)
  228. (assoc-in [c r :display] (evaluate-expression (subs value 1) {})))
  229. :else (let [variables (zipmap (map #(str (:col %) (:row %)) refs) evaluated-refs)
  230. evaluated-value (evaluate-expression (subs value 1) variables)
  231. new-datum (assoc datum :display evaluated-value)]
  232. (assoc-in data [c r] new-datum)))))
  233. ; THE NEW EVALUATE FUNCTION
  234. ; - 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)
  235. ; - 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)
  236. ; - evaluate (using forward references if necessary)
  237. ; - add all back-references to the queue
  238. ; - recurse
  239. ; - TODO: consider initialization case
  240. ; - TODO: consider multiple cells modified simultaneously
  241. (defn evaluate-from-cell
  242. "Evaluate the final value of a cell, and recursively re-evaluate all the cells that reference it."
  243. [data c r]
  244. (let [cycles? (alt-find-cycle data c r)
  245. new-data (if cycles?
  246. (-> 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
  247. (update-in [c r] dissoc :dirty)
  248. (assoc-in [c r :display] :cycle-error))
  249. (gather-variables-and-evaluate-cell data c r))] ; if there are no cycles, evaluate the cell
  250. (loop [data new-data
  251. queue (get-in new-data [c r :inbound])]
  252. (if (empty? queue)
  253. data ; if the queue is empty, we're done
  254. (let [current (first queue)
  255. cc (:col current)
  256. cr (:row current)
  257. dirty? (get-in data [cc cr :dirty])
  258. re-evaluated-data (if dirty?
  259. (gather-variables-and-evaluate-cell data cc cr)
  260. data)
  261. sufficient? (not= (get-in re-evaluated-data [cc cr :display]) :insufficient-data)
  262. new-queue (if dirty?
  263. (if sufficient?
  264. (concat (rest queue) (get-in re-evaluated-data [cc cr :inbound])) ; if all is well, then add the back-references onto the queue
  265. (concat (rest queue) (list current))) ; if the current cell's dependencies are not satisfied, re-add to the end of the queue
  266. (rest queue))] ; if the current cell is not marked as dirty, then it has already been processed
  267. (recur re-evaluated-data new-queue))))))
  268. ;TODO: does this need a cycle check?
  269. (defn evaluate-all
  270. "Evaluates all cells marked as \"dirty\". Generally reserved for the initialization."
  271. ([data]
  272. (evaluate-all data (walk-get-refs data #(:dirty %3))))
  273. ([data queue]
  274. (if (empty? queue)
  275. data
  276. (let [cur (first queue)
  277. cc (:col cur)
  278. cr (:row cur)
  279. dirty? (get-in data [cc cr :dirty])]
  280. (if dirty?
  281. (let [evaluated (evaluate-from-cell data (:col cur) (:row cur))
  282. result (get-in evaluated [cc cr :display])]
  283. (if (= result :insufficient-data)
  284. (recur data (concat (rest queue) (list cur)))
  285. (recur evaluated (rest queue))))
  286. (recur data (rest queue)))))))
  287. (evaluate-all (walk-modify-data (:alt-table-data microtables-frontend.db/default-db) (fn [c r datum] (if (= (first (:value datum)) "=") (assoc datum :dirty true) datum))))
  288. #_(defn alt-re-evaluate
  289. "Evaluate the values of cells that contain formulae, following reference chains if applicable."
  290. [data]
  291. (let [non-empty-cells (flatten (map (fn [[c v]] (map (fn [[r _]] {:col c :row r}) v)) data))
  292. {has-formula true original-values false} (group-by #(= (first (get-in data [(:col %) (:row %) :value])) "=") non-empty-cells)
  293. found-cycles (map #(let [found (alt-find-cycle data (:col %) (:row %))]
  294. (if found (assoc % :error found) %)) has-formula)]
  295. non-empty-cells))
  296. (defn find-val [data c r]
  297. (let [l (find-cell data c r)
  298. v (get l :display (get l :value))
  299. formula? (and (string? v) (= (first v) "="))]
  300. (cond
  301. (nil? v) 0
  302. ;(contains? l :error) :ref-error
  303. formula? :not-yet
  304. :else v)))
  305. (defn re-evaluate [data]
  306. (println "re-evaluating" data)
  307. (let [{has-formula true original-values false} (group-by #(= (first (:value %)) "=") data)
  308. found-cycles (map #(let [found (find-cycle data %)] (if found (assoc % :error found) %)) has-formula)
  309. {eligible true ineligible false} (group-by #(not (contains? % :error)) found-cycles)]
  310. ;
  311. (loop [values (into original-values ineligible)
  312. mapped-cell-keys eligible]
  313. (let [search-values (map (fn [datum]
  314. (assoc datum :found (map #(find-val
  315. (concat values mapped-cell-keys)
  316. (:col %)
  317. (:row %))
  318. (:refs datum))))
  319. mapped-cell-keys)
  320. {not-ready true ready nil} (group-by (fn [datum]
  321. (some #(= :not-yet %) (:found datum)))
  322. search-values)
  323. prepped-for-eval (map (fn [datum]
  324. (let [hash-map-of-vars-to-vals (apply hash-map (interleave (:vars datum) (:found datum)))]
  325. (assoc datum :inputs hash-map-of-vars-to-vals)))
  326. ready)
  327. evaluated (map (fn [datum]
  328. (assoc datum :display (evaluate-expression
  329. (subs (:value datum) 1)
  330. (:inputs datum))))
  331. prepped-for-eval)
  332. updated-values (copy-display-values values evaluated)]
  333. (println "EVALUATED" evaluated)
  334. (if (nil? not-ready)
  335. updated-values
  336. (recur updated-values not-ready))))))