utils.cljs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 order-two-cols
  27. "Accepts two column names (letters) and returns them in order."
  28. [col1 col2]
  29. (cond
  30. (> (.-length col1) (.-length col2)) [col2 col1]
  31. (> (.-length col2) (.-length col1)) [col1 col2]
  32. (= (max col1 col2) col1) [col2 col1]
  33. :else [col1 col2]))
  34. ; the order goes top to bottom, then left to right - that makes the most sense to me
  35. ; I don't know why a different order would be important, or even in what situation order is important at all
  36. (def parse-range
  37. "Converts a range in \"A1:B2\" notation to a comma-separated list of cells: \"A1,A2,B1,B2\"."
  38. (memoize (fn [range-string]
  39. (let [col1 (second (re-find #"\(\s*([A-Z]+)" range-string))
  40. col2 (second (re-find #":\s*([A-Z]+)" range-string))
  41. row1 (.parseInt js/window (second (re-find #"([0-9]+)\s*:" range-string)))
  42. row2 (.parseInt js/window (second (re-find #"([0-9]+)\s*\)" range-string)))
  43. [start-col end-col] (order-two-cols col1 col2)
  44. start-row (min row1 row2)
  45. end-row (max row1 row2)]
  46. (str "(" (clojure.string/join "," (for [col (take-while #(not= (next-letter end-col) %) (iterate next-letter start-col))
  47. row (range start-row (inc end-row))]
  48. (str col row))) ")")))))
  49. (def replace-ranges-in-expression
  50. "Receives an expression string, and replaces all ranges in colon notation (\"A1:B2\") into a comma-separated list of cells (\"A1,A2,B1,B2\")."
  51. (memoize (fn [expression]
  52. (clojure.string/replace expression #"\(\s*[A-Z]+[0-9]+\s*:\s*[A-Z]+[0-9]+\s*\)" parse-range))))
  53. (def parse-variables (memoize (fn [expression]
  54. (as-> (js->clj (.parse mathjs (replace-ranges-in-expression expression))) $
  55. (.filter $ #(true? (.-isSymbolNode %)))
  56. (map #(.-name %) $)
  57. (map #(.toUpperCase %) $)
  58. (filter #(re-matches #"[A-Z]+[0-9]+" %) $)))))
  59. (def str->rc (memoize (fn [s]
  60. (let [c (re-find #"^[A-Z]+" s)
  61. r (.parseInt js/window (re-find #"[0-9]+$" s))]
  62. {:row r :col c}))))
  63. ; leave in the :inbound references, since they probably have not have changed
  64. (defn add-references
  65. "Parses the expression in the value of a datum, and adds refs as necessary"
  66. [datum]
  67. (if (= (first (:value datum)) "=")
  68. (let [vars (parse-variables (subs (:value datum) 1))
  69. refs (map str->rc vars)]
  70. (-> datum
  71. (assoc :refs refs)
  72. (dissoc :error)))
  73. (-> datum
  74. (dissoc :refs)
  75. (dissoc :display)
  76. (dissoc :error))))
  77. ; the references in the data are a set of disconnected, doubly-linked trees
  78. ;TODO: rather than denotify all, then re-notify all, maybe use a diff? maybe on small scales it's not worth it?
  79. (defn denotify-references
  80. "Remove references in all cells formerly referenced by this cell"
  81. [data origin refs]
  82. (if (empty? refs)
  83. data
  84. (let [target (first refs)
  85. de-notified (update-in data [(:col target) (:row target) :inbound] (partial filter #(not= % origin)))]
  86. (recur de-notified origin (rest refs)))))
  87. (defn notify-references
  88. "Update references in all cells referenced by this cell"
  89. [data origin refs]
  90. (if (empty? refs)
  91. data
  92. (let [target (first refs)
  93. notified (update-in data [(:col target) (:row target) :inbound] conj origin)]
  94. (recur notified origin (rest refs)))))
  95. (defn create-all-references
  96. "Starting from a clean slate, add in all references. This wipes any references that may have been present."
  97. [data]
  98. (reduce-kv
  99. (fn [columns c curr-column]
  100. (assoc columns c (reduce-kv
  101. (fn [rows r datum]
  102. (assoc rows r (add-references (dissoc (dissoc datum :refs) :inbound))))
  103. {}
  104. curr-column)))
  105. {}
  106. data))
  107. ;TODO: re-write create-all-references to use walk-modify-data instead
  108. (defn walk-modify-data
  109. "Walks through the data map and updates each datum by applying f (a function accepting col, row, datum)."
  110. [data f]
  111. (reduce-kv
  112. (fn [columns c curr-column]
  113. (assoc columns c (reduce-kv
  114. (fn [rows r datum]
  115. (assoc rows r (f c r datum)))
  116. {}
  117. curr-column)))
  118. {}
  119. data))
  120. (defn walk-get-refs
  121. "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)."
  122. [data pred]
  123. (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))
  124. (defn create-all-back-references
  125. "Assuming all references have been added, insert all back references."
  126. [data]
  127. (loop [data data
  128. formulas (walk-get-refs data #(= (first (:value %3)) "="))]
  129. (if (empty? formulas)
  130. data
  131. (let [origin (first formulas)
  132. refs (get-in data [(:col origin) (:row origin) :refs])
  133. updated-one (notify-references data origin refs)]
  134. (recur updated-one (rest formulas))))))
  135. (defn set-dirty-flags
  136. "Sets the target cell to \"dirty\" and recursively repeat with its back-references all the way up. Returns the new data set."
  137. ([data c r]
  138. (set-dirty-flags data (list {:col c :row r})))
  139. ([data queue]
  140. (if (empty? queue)
  141. data
  142. (let [cur (first queue)
  143. c (:col cur)
  144. r (:row cur)
  145. datum (get-in data [c r])]
  146. (if (true? (:dirty datum))
  147. (recur data (rest queue))
  148. (let [new-data (assoc-in data [c r :dirty] true)
  149. new-queue (concat (rest queue) (:inbound datum))]
  150. (recur new-data new-queue)))))))
  151. (defn change-datum-value
  152. "Modify the value of a datum in the table, and update all applicable references"
  153. [data c r value]
  154. (let [datum (get-in data [c r])
  155. updated (assoc datum :value value)]
  156. (-> data
  157. (assoc-in [c r :value] value)
  158. (set-dirty-flags c r))))
  159. (defn reset-references
  160. "If there has been a change to which cells are referenced by this cell, then change the necessary back-references to this cell."
  161. [data c r]
  162. (let [datum (get-in data [c r])
  163. parsed (add-references datum)]
  164. (if (= (:refs datum) (:refs parsed))
  165. data
  166. (-> data
  167. (assoc-in [c r] parsed)
  168. (denotify-references {:col c :row r} (:refs datum))
  169. (notify-references {:col c :row r} (:refs parsed))))))
  170. (defn remove-valueless-range-elements
  171. "Remove nil values specifically from ranges (to solve issues with some functions like average)."
  172. [variables var-list]
  173. (println "remove-valueless-range-elements" variables var-list (first var-list))
  174. (let [l (clojure.string/split (clojure.string/replace (first var-list) #"[()]" "") #",")
  175. has-values (filter #(not (nil? (variables %))) l)]
  176. (str "(" (clojure.string/join "," has-values) ")")))
  177. (defn preprocess-expression
  178. "Handle range cases, rename certain functions (to work with math.js), prepare expression and variables for processing."
  179. [expression variables]
  180. (let [renamed-expression (clojure.string/replace expression #"\baverage\(" "mean(")
  181. new-expression (clojure.string/replace renamed-expression #"\(([A-Z]+[0-9]+,)*[A-Z]+[0-9]+\)" (partial remove-valueless-range-elements variables))
  182. new-variables (reduce-kv #(assoc %1 %2 (if (nil? %3) "0" %3)) {} variables)]
  183. (println "PREPROCESS" {:expression new-expression :variables new-variables})
  184. {:expression new-expression
  185. :variables new-variables}))
  186. (def evaluate-expression
  187. "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."
  188. (memoize (fn [expression variables]
  189. (let [range-replaced (replace-ranges-in-expression expression)
  190. {ready-expression :expression ready-variables :variables} (preprocess-expression range-replaced variables)]
  191. (try
  192. (.evaluate mathjs ready-expression (clj->js ready-variables))
  193. (catch js/Error e
  194. (println "mathjs evaluation error" (.-message e) e)
  195. :calc-error))))))
  196. ;TODO: deal with lowercase cell references
  197. ;TODO: memoize dynamically? probably not worth memoizing directly, and could take up too much memory over time
  198. ; https://stackoverflow.com/a/13123571/8172807
  199. (defn find-cycle
  200. "Accepts the data and a datum, and peforms a depth-first search to find reference cycles, following back-references."
  201. ([data c r] (find-cycle data c r #{}))
  202. ([data c r ancest]
  203. (let [datum (get-in data [c r])
  204. current {:col c :row r}
  205. this-and-above (conj ancest current)
  206. inbound (:inbound datum)
  207. found-repeat (not (empty? (clojure.set/intersection this-and-above (set inbound))))]
  208. (if found-repeat
  209. :cycle-error
  210. (some #(find-cycle data (:col %) (:row %) this-and-above) inbound)))))
  211. (defn gather-variables-and-evaluate-cell
  212. "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."
  213. [data c r]
  214. (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)
  215. refs (:refs datum)
  216. value (:value datum)
  217. formula? (= (first value) "=")
  218. resolved-refs (map #(merge % (get-in data [(:col %) (:row %)])) refs)
  219. evaluated-refs (map #(if (= (first (:value %)) "=") (:display %) (:value %)) resolved-refs)
  220. invalid-refs (some nil? resolved-refs)
  221. dirty-refs (some :dirty resolved-refs)
  222. error-refs (some #(= (:display %) :error) resolved-refs)
  223. ;unevaluated-refs (some nil? evaluated-refs)
  224. cycle-refs (some #(= (:display %) :cycle-error) resolved-refs)
  225. disqualified? (or invalid-refs dirty-refs error-refs)]
  226. (cond
  227. (false? formula?) (assoc-in data [c r] datum) ; if it's not a formula, then return as is (with the dirty flag removed)
  228. cycle-refs (-> data ; if one of its references has a reference cycle, then this one is "poisoned" as well
  229. (assoc-in [c r] datum)
  230. (assoc-in [c r :display] :cycle-error))
  231. ;unevaluated-refs (assoc-in data [c r :display] :insufficient-data) ; do not un-mark as "dirty", since it has not been evaluated yet
  232. disqualified? (-> data ; some other error is present
  233. (assoc-in [c r] datum)
  234. (assoc-in [c r :display] :error))
  235. (empty? refs) (-> data
  236. (assoc-in [c r] datum)
  237. (assoc-in [c r :display] (evaluate-expression (subs value 1) {})))
  238. :else (let [variables (zipmap (map #(str (:col %) (:row %)) refs) evaluated-refs)
  239. evaluated-value (evaluate-expression (subs value 1) variables)
  240. new-datum (assoc datum :display evaluated-value)]
  241. (assoc-in data [c r] new-datum)))))
  242. ; THE NEW EVALUATE FUNCTION
  243. ; - 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)
  244. ; - 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)
  245. ; - evaluate (using forward references if necessary)
  246. ; - add all back-references to the queue
  247. ; - recurse
  248. ; - TODO: consider initialization case
  249. ; - TODO: consider multiple cells modified simultaneously
  250. (defn evaluate-from-cell
  251. "Evaluate the final value of a cell, and recursively re-evaluate all the cells that reference it."
  252. [data c r]
  253. (let [cycles? (find-cycle data c r)
  254. new-data (if cycles?
  255. (-> 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
  256. (update-in [c r] dissoc :dirty)
  257. (assoc-in [c r :display] :cycle-error))
  258. (gather-variables-and-evaluate-cell data c r))] ; if there are no cycles, evaluate the cell
  259. (loop [data new-data
  260. queue (get-in new-data [c r :inbound])]
  261. (if (empty? queue)
  262. data ; if the queue is empty, we're done
  263. (let [current (first queue)
  264. cc (:col current)
  265. cr (:row current)
  266. dirty? (get-in data [cc cr :dirty])
  267. re-evaluated-data (if dirty?
  268. (gather-variables-and-evaluate-cell data cc cr)
  269. data)
  270. sufficient? (not= (get-in re-evaluated-data [cc cr :display]) :insufficient-data)
  271. new-queue (if dirty?
  272. (if sufficient?
  273. (concat (rest queue) (get-in re-evaluated-data [cc cr :inbound])) ; if all is well, then add the back-references onto the queue
  274. (concat (rest queue) (list current))) ; if the current cell's dependencies are not satisfied, re-add to the end of the queue
  275. (rest queue))] ; if the current cell is not marked as dirty, then it has already been processed
  276. (recur re-evaluated-data new-queue))))))
  277. ;TODO: does this need a cycle check?
  278. (defn evaluate-all
  279. "Evaluates all cells marked as \"dirty\". Generally reserved for the initialization."
  280. ([data]
  281. (evaluate-all data (walk-get-refs data #(:dirty %3))))
  282. ([data queue]
  283. (if (empty? queue)
  284. data
  285. (let [cur (first queue)
  286. cc (:col cur)
  287. cr (:row cur)
  288. dirty? (get-in data [cc cr :dirty])]
  289. (if dirty?
  290. (let [evaluated (evaluate-from-cell data (:col cur) (:row cur))
  291. result (get-in evaluated [cc cr :display])]
  292. (if (= result :insufficient-data)
  293. (recur data (concat (rest queue) (list cur)))
  294. (recur evaluated (rest queue))))
  295. (recur data (rest queue)))))))