Skip to content

Instantly share code, notes, and snippets.

@duncanmak
Created September 22, 2010 21:10
Show Gist options
  • Select an option

  • Save duncanmak/592575 to your computer and use it in GitHub Desktop.

Select an option

Save duncanmak/592575 to your computer and use it in GitHub Desktop.
(ns ScriptIJ.distance-matrix
(:import [java.awt.geom Point2D$Double]))
(defn ->point [m]
(Point2D$Double. (Double/parseDouble (get m "XM"))
(Double/parseDouble (get m "YM"))))
(defn compute-matrix [table]
(partition (count table)
(for [a table, b table]
(.distance (->point a) (->point b)))))
(defn verify-matrix [matrix]
(loop [i 0, matrix matrix]
(when-not (empty? matrix)
(assert (zero? (nth (first matrix) i)))
(recur (inc i) (rest matrix)))))
(defn allocate-bins [distance tolerance]
(partition 2
(interleave (range 0 (+ distance tolerance) tolerance)
(range tolerance (+ distance tolerance) tolerance))))
(defn within-range
"Return the number of items in row that is between lower (inclusive) and upper (exclusive)"
[row [lower upper]]
(count (filter #(and (<= lower %) (< % upper)) row)))
(def range-comparator
(comparator (fn [[a _] [b _]] (< a b))))
(defn count-occurrances [row bins]
(apply assoc
(sorted-map-by range-comparator)
(interleave bins (map #(within-range row %) bins))))
(defn matrix->histogram
"Given an n-matrix return a list of length 'distance/tolerance', counting the number of entries per bin"
[matrix distance tolerance]
(let [bins (allocate-bins distance tolerance)]
;; it's better when it's parallel!
(reduce #(merge-with + %1 %2)
(doall (pmap #(count-occurrances % bins) matrix)))
;; (loop [histogram (sorted-map-by range-comparator), matrix matrix]
;; (if (empty? matrix)
;; (do (println "Done!")
;; histogram)
;; (let [row (first matrix)
;; occurances (count-occurrances row bins)]
;; (recur (merge-with + histogram occurances)
;; (rest matrix)))))
))
;; (matrix->histogram (partition 10 (take 1000 (repeatedly #(rand-int 100)))) 100 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment