utils.cljs 16 KB

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