Skip to content

Instantly share code, notes, and snippets.

@siscia
Created January 13, 2013 18:54
Show Gist options
  • Save siscia/4525672 to your computer and use it in GitHub Desktop.
Save siscia/4525672 to your computer and use it in GitHub Desktop.
(ns parallel-colt-matrix.core
(:require [core.matrix.protocols :as mp])
(:import [cern.colt.matrix.tobject.impl DenseObjectMatrix1D DenseObjectMatrix2D DenseObjectMatrix3D]))
(defn find-right-dimension [[vector]] ;;Need a better way to do this
(cond
(vector? (first (first vector))) (throw (Exception. "To be Done")) ;[(Class/forName "[[[Ljava.lang.Object;")]
(vector? (first vector)) [(Class/forName "[[Ljava.lang.Object;")]
:else [clojure.lang.PersistentVector]))
(defn get-class [& more] ;;I don't like it all
(let [classes (vec (map class more))]
(cond
(= classes [clojure.lang.PersistentVector]) (find-right-dimension more)
:else classes)))
(defmulti p-array get-class)
(defmethod p-array [Number]
[dimension] (DenseObjectMatrix1D. dimension))
(defmethod p-array [clojure.lang.PersistentVector]
[values] (DenseObjectMatrix1D. (object-array values)))
(defmethod p-array [Number Number]
[rows columns] (DenseObjectMatrix2D. rows columns))
(defmethod p-array [(Class/forName "[[Ljava.lang.Object;")]
[values] (DenseObjectMatrix2D. (to-array-2d values)))
(defmethod p-array [Number Number Number]
[slice rows columns] (DenseObjectMatrix3D. slice rows columns))
(defmethod p-array [(Class/forName "[[[Ljava.lang.Object;")] ;;Need
;;some way to get the [[[Ljava.lang.Object; object
[values] (DenseObjectMatrix3D. values))
(deftype P-Array
[array]
mp/PImplementation
(implementation-key [array] :parallel-colt)
mp/PDimensionInfo
(dimensionality [array]
(case (class array)
cern.colt.matrix.tobject.impl.DenseObjectMatrix1D 1
cern.colt.matrix.tobject.impl.DenseObjectMatrix2D 2
cern.colt.matrix.tobject.impl.DenseObjectMatrix3D 3))
(is-scalar? [array]
"Tests whether an object is a scalar value"
false)
(is-vector? [array]
"Tests whether an object is a vector (1D matrix)"
(case (class array)
cern.colt.matrix.tobject.impl.DenseObjectMatrix1D true
:else false)))
@mikera
Copy link

mikera commented Jan 14, 2013

Look good!

As noted on the issue discussion, the alternative would be to extend the protocols directly to the colt matrix types.

If you continue on this path, it might be an idea to programatically construct multiple versions of P-Array, e.g. use macros to build them for each combination of 1D, 2D, 3D and even perhaps different array types.

This has a few advantages:

  • You won't have to write conditional code that branched on (class array)
  • You can put a type hint on the "array" field in P-Array versions, which will help performance considerably (avoiding Java reflection)

OTOH, the macro could get quite complex.....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment