Skip to content

Instantly share code, notes, and snippets.

@timgluz
Created September 22, 2012 18:49
Show Gist options
  • Save timgluz/3767383 to your computer and use it in GitHub Desktop.
Save timgluz/3767383 to your computer and use it in GitHub Desktop.
Sparsematrix wrappers for Clojure.
;;sparsematrix module
;;clojure wrappers around colt0.94, which also powers clojure/Incanter computations
;;
;;Look javadocs:
;;http://acs.lbl.gov/software/colt/api/index.html
(ns elamyslahjat.utils.sparsematrix
(:use [incanter core])
(:import [cern.colt.matrix.tdouble DoubleFactory1D DoubleFactory2D]
[cern.colt.matrix.tdouble.impl SparseDoubleMatrix1D
SparseDoubleMatrix2D]
[cern.colt.matrix.tdouble.algo DenseDoubleAlgebra SmpDoubleBlas]
))
(def BLAS (SmpDoubleBlas.))
;;Helper functions
(defn- max-pos [val-map]
"returns max position form val-map, useful for to specify max-size of sparse vector"
(apply max (keys val-map)))
;;GetSetters and public wrapper around Java interface
(defn setq
"Does quickSetting to Matrix, aka doesnt control limits of matrix"
([^SparseDoubleMatrix1D spmatrix ^Integer col val]
(.setQuick spmatrix col (double val)))
;;set value for 2D
([^SparseDoubleMatrix2D spmatrix ^Integer row ^Integer col ^Double val]
(.setQuick spmatrix row col val))
)
(defn getq
"Does quickGetting from given matrix."
([^SparseDoubleMatrix1D spmatrix ^Integer col]
(.getQuick spmatrix col))
;;get value for sparse 2d matrix
([^SparseDoubleMatrix2D spmatrix ^Integer row ^Integer col]
(.getQuick spmatrix row col))
)
(defn sparse-vector [val-map]
"Creates new sparse map with given value map,
which has given structure {pos val, pos2 val2}"
(let [vector-size (+ 1 (max-pos val-map))
spmatrix (SparseDoubleMatrix1D. vector-size)]
;initialize row-vector
(doseq [[pos val] val-map]
(setq spmatrix pos val))
spmatrix
))
(defn dot [m1 m2]
(.ddot BLAS m1 m2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment