├── doc └── intro.md ├── .gitignore ├── project.clj ├── test └── nd4clj │ └── core_test.clj ├── README.md ├── LICENSE └── src └── nd4clj └── matrix.clj /doc/intro.md: -------------------------------------------------------------------------------- 1 | # Introduction to nd4clj 2 | 3 | TODO: write [great documentation](http://jacobian.org/writing/what-to-write/) 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | .hgignore 11 | .hg/ 12 | /bin/ 13 | /.classpath 14 | /.project 15 | /.settings/ 16 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject org.clojars.ds923y/nd4clj "0.1.1-SNAPSHOT" 2 | :plugins [[lein-cljfmt "0.5.3"]] 3 | :description "An implementation of core.matrix protocols with nd4j." 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[org.clojure/clojure "1.8.0"] 7 | 8 | [net.mikera/core.matrix "0.53.0"] 9 | [org.nd4j/nd4j-native "0.5.0"]] 10 | 11 | :profiles {:dev {:dependencies [[net.mikera/core.matrix "0.53.0" :classifier "tests"]] 12 | }} 13 | ) 14 | -------------------------------------------------------------------------------- /test/nd4clj/core_test.clj: -------------------------------------------------------------------------------- 1 | (ns nd4clj.core-test 2 | (:require [clojure.pprint :refer [pprint]] 3 | [clojure.core.matrix :refer :all :as m] 4 | [clojure.test :refer :all] 5 | [clojure.core.matrix.compliance-tester :as compliance] 6 | [nd4clj.matrix]) 7 | (:import [org.nd4j.linalg.factory Nd4j])) 8 | 9 | 10 | ;(def canonical-object (Nd4j/create 4 2)) 11 | ;(imp/register-implementation canonical-object) 12 | 13 | (clojure.core.matrix/set-current-implementation :nd4j) 14 | 15 | #_(deftest slice-tests 16 | (is (equals [3 4] (slice (matrix :nd4j [[1 2] [3 4]]) 1))) ;; second slice 17 | (is (equals [1 3] (slice (matrix :nd4j [[1 2] [3 4]]) 1 0))) ;; first slice of second dimension 18 | ) 19 | 20 | #_(deftest shape-tests 21 | (is (= [2] (shape (first (slices (matrix :nd4j [[2 0] [0 2]])))))) ;; first of slice sequence 22 | (is (nil? (shape (first (eseq (matrix :nd4j [[2 0] [0 2]])))))) ;; first element 23 | ) 24 | 25 | (deftest compliance-test 26 | (clojure.core.matrix.compliance-tester/instance-test (matrix :nd4j [[2 0] [0 2]])) 27 | (clojure.core.matrix.compliance-tester/compliance-test (matrix :nd4j [[2 0] [0 2]]))) 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nd4clj 2 | ### Rationale 3 | If you want to use clojure with the deeplearning4j library a clojure 4 | wrapper for nd4j functions is needed. This wrapper implements the 5 | idiomatic and familiar clojure matrix interface `core.matrix`. 6 | Existing clojure code using the `core.matrix` can change its 7 | implementation to nd4clj and take advatage of the performance 8 | of nd4j and interoperability with deeplearning4j libraries. 9 | b 10 | The NDArray fundemental to deeplearning4j code is now wrapped 11 | with this release. It can be unwraped by dereferencing the 12 | public property "a" as in `(.a (indarray/matrix :nd4clj [[1 2] [3 4]]))`. 13 | ### Tutorial 14 | Add `[org.clojars.ds923y/nd4clj "0.1.1-SNAPSHOT"]` to your project.clj 15 | file. Here is an example of usage. 16 | ```clojure 17 | (ns useit.core 18 | (:require [nd4clj.matrix :as imp] 19 | [clojure.core.matrix :as indarray]) 20 | (:gen-class)) 21 | 22 | (indarray/set-current-implementation :nd4j) 23 | 24 | (def A (indarray/array [[0 1] [2 3]])) 25 | (def I (indarray/array [[1 0] [0 1]])) 26 | 27 | (defn -main 28 | [& args] 29 | (println (indarray/mmul A I))) 30 | ``` 31 | 32 | ### Limitations 33 | This is a largely compliant implementation. The bare minimum of 34 | protocols are supported though. Most people should not have problems. 35 | 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of New York and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /src/nd4clj/matrix.clj: -------------------------------------------------------------------------------- 1 | (ns nd4clj.matrix 2 | (:require [clojure.core.matrix.protocols :as mp] 3 | [clojure.core.matrix :as m] 4 | [clojure.reflect :as r] 5 | [clojure.core.matrix.utils :as util] 6 | [clojure.core.matrix.implementations :as imp]) 7 | (:use [clojure.pprint :only [print-table]]) 8 | (:import [org.nd4j.linalg.factory Nd4j] 9 | [java.util Arrays] 10 | [org.nd4j.linalg.api.ndarray INDArray] 11 | [clojure.lang Numbers] 12 | [org.nd4j.linalg.api.shape Shape] 13 | [org.nd4j.linalg.cpu.nativecpu NDArray] 14 | [org.nd4j.linalg.api.ops.impl.transforms Pow] 15 | [org.nd4j.linalg.api.ops.impl.broadcast BroadcastCopyOp] 16 | [org.nd4j.linalg.indexing IntervalIndex INDArrayIndex])) 17 | 18 | ;; TODO: eliminate reflection warnings 19 | (set! *warn-on-reflection* true) 20 | ;; (set! *unchecked-math* true) 21 | 22 | (declare convert-to-nested-vectors) 23 | (declare convert-mn) 24 | (declare wrap-matrix) 25 | (declare empty-matrix) 26 | 27 | (defn- broadcast [m target-shape] 28 | (let [dim-prj (->> target-shape count range (drop 1) int-array) 29 | crt (Nd4j/create (int-array target-shape)) 30 | vbn (BroadcastCopyOp. crt (.a m) crt (int-array [])) 31 | to-ret (.exec (Nd4j/getExecutioner) vbn (int-array dim-prj))] (wrap-matrix m to-ret))) 32 | 33 | (defn- sub-matrix [^INDArray matrix a b c d] 34 | (let [idx1 (IntervalIndex. true 1) 35 | idx2 (IntervalIndex. true 1) 36 | idxs (into-array INDArrayIndex [idx1 idx2])] 37 | (.init idx1 (int a) (int b)) 38 | (.init idx2 (int c) (int d)) 39 | (.get matrix idxs))) 40 | 41 | (defn- triangleUpper [^INDArray matrix n offset1 offset2] 42 | (let [nh (long (/ n 2)) 43 | nr (long (mod n 2)) 44 | a0 (+ nh offset1) 45 | b0 (+ (- n 1) offset1) 46 | c0 (+ 0 offset2) 47 | d0 (+ (- nh 1) offset2) 48 | sub (sub-matrix matrix a0 b0 c0 d0)] 49 | 50 | (and (if (> nh 1) 51 | (and (triangleUpper matrix nh offset1 offset2) 52 | (triangleUpper matrix (+ nh nr) (+ nh offset1) (+ nh offset2))) 53 | true) 54 | (= 0.0 (.minNumber ^INDArray sub) (.maxNumber ^INDArray sub))))) 55 | 56 | (defn- triangleLower [^INDArray matrix n offset1 offset2] 57 | (let [nh (long (/ n 2)) 58 | nr (long (mod n 2)) 59 | a0 (+ 0 offset1) 60 | b0 (+ (- nh 1) offset1) 61 | c0 (+ nh offset2) 62 | d0 (+ (- n 1) offset2) 63 | sub (sub-matrix matrix a0 b0 c0 d0)] 64 | (and (if (> nh 1) 65 | (and (triangleLower matrix nh offset1 offset2) 66 | (triangleLower matrix (+ nh nr) (+ nh offset1) (+ nh offset2))) 67 | true) 68 | (= 0.0 (.minNumber ^INDArray sub) (.maxNumber ^INDArray sub))))) 69 | 70 | (defn- get-index-iterate-fn 71 | ([shape cur carry] 72 | (if-let [s (seq shape)] 73 | (if carry 74 | (let [rlt (mod (inc (first cur)) (first s))] 75 | (cons rlt (get-index-iterate-fn (rest s) (rest cur) (zero? rlt)))) 76 | cur) 77 | [])) 78 | ([shape] 79 | (fn [cur] 80 | (if-let [s (seq shape)] 81 | (let [rlt (mod (inc (first cur)) (first s))] 82 | (cons rlt (get-index-iterate-fn (rest s) (rest cur) (zero? rlt)))) 83 | [])))) 84 | 85 | (defn- iterate-indexes [shape] 86 | (let [begin (repeat (count shape) 0) 87 | iterate-fn (get-index-iterate-fn shape)] 88 | (iterate iterate-fn begin))) 89 | 90 | (defn- concat-along [is-vec old matrix dim] 91 | (if (= (alength (.shape old)) 2) ;nd4j concat does not work for indexes hi 92 | (Nd4j/concat #^int (int dim) #^"[Lorg.nd4j.linalg.api.ndarray.INDArray;" (into-array org.nd4j.linalg.api.ndarray.INDArray matrix)) 93 | (let [iterater (iterate-indexes (.shape old)) 94 | to-return (Nd4j/create (.shape old))] 95 | (doseq [idx (range (.length old))] 96 | (let [i1 (nth iterater idx) 97 | i2 (keep-indexed #(if (not= %1 dim) %2) i1) 98 | sliced-matrix (matrix (nth i1 dim))] 99 | (.putScalar ^INDArray to-return #^ints (int-array i1) (.getDouble ^INDArray sliced-matrix (int-array i2))))) 100 | to-return))) 101 | 102 | (defn- rotate4 [old dim pos] 103 | (let [^INDArray matrix (.a old) 104 | dim-sz (-> matrix (.size dim)) 105 | components (if (not (.vector old)) 106 | (map #(.slice ^INDArray matrix % (int dim)) (range dim-sz)) 107 | (map #(sub-matrix matrix % % 0 0) (range (.length matrix)))) 108 | n-pos (mod pos (if (.vector old) (.length matrix) dim-sz)) 109 | to-ret (Nd4j/create #^ints (.shape ^INDArray matrix)) 110 | swapped (vec (concat (take-last (- (count components) n-pos) components) (take n-pos components)))] 111 | (concat-along (.vector old) matrix swapped dim))) 112 | 113 | (defn- square? [^INDArray matrix] (apply = (vec (.shape matrix)))) 114 | 115 | (defn- m-new-scalar-array 116 | ([m] (mp/construct-matrix m (Nd4j/scalar #^double (double 0)))) 117 | ([m value] (mp/construct-matrix m (Nd4j/scalar #^double (double value))))) 118 | 119 | (deftype clj-INDArray [^INDArray a ^Boolean vector ^Boolean scalar ^Boolean empty] 120 | mp/PImplementation 121 | (mp/implementation-key [m] :nd4j) 122 | (mp/meta-info [m] {:doc "nd4j implementation of the core.matrix 123 | protocols. Allows different backends, e.g. jblas or jcublas for 124 | graphic cards."}) 125 | (mp/construct-matrix [m data] 126 | (let [res (convert-mn m data)] 127 | (if (nil? data) (empty-matrix (.a ^clj-INDArray res)) res))) 128 | (mp/new-vector [m length] 129 | (let [res (Nd4j/create #^int (int length)) 130 | e (zero? length) 131 | s (= length 1) 132 | v (> length 1)] (wrap-matrix m res v s e))) 133 | (mp/new-matrix [m rows columns] 134 | (let [res (Nd4j/create #^int (int rows) #^int (int columns)) 135 | e (zero? (min rows columns)) 136 | s (= rows columns 1) 137 | v (and (= (min rows columns) 1) (> (max rows columns) 1))] (wrap-matrix m res v s e))) 138 | (mp/new-matrix-nd [m shape] 139 | (let [res (Nd4j/create #^ints (int-array shape)) 140 | e (zero? (apply min shape)) 141 | s (apply = 1 shape) 142 | v (and (= (apply min shape) 1) (> (apply max shape) 1))] (wrap-matrix m res v s e))) 143 | (mp/supports-dimensionality? [m dimensions] 144 | (>= dimensions 0)) 145 | mp/PDimensionInfo 146 | (mp/dimensionality [m] (let [w (alength (.shape ^INDArray a))] 147 | (cond scalar 0 vector 1 :else w))) 148 | (mp/get-shape [m] (let [sp (vec (.shape ^INDArray a))] 149 | (cond vector [(apply max sp)] 150 | scalar 0 151 | :else sp))) 152 | (mp/is-scalar? [m] 153 | scalar) 154 | (mp/is-vector? [m] 155 | vector) 156 | (mp/dimension-count [m dimension-number] 157 | (cond 158 | (and scalar (not= dimension-number 0)) (throw (IllegalArgumentException. "bad args")) 159 | (and vector (not= dimension-number 0) (throw (IllegalArgumentException. "bad args"))) 160 | (or (neg? dimension-number) (>= dimension-number (mp/dimensionality m)) (throw (IllegalArgumentException. "bad args")))) 161 | (cond 162 | scalar 1 163 | vector (->> a (.shape) vec (apply max)) 164 | :else (aget (.shape ^INDArray a) dimension-number))) 165 | mp/PIndexedAccess 166 | (mp/get-1d [m row] 167 | (let [ixs (int-array [row])] 168 | (.getDouble ^INDArray a #^int row))) 169 | (mp/get-2d [m row column] 170 | (let [ixs (int-array [row column])] 171 | (.getDouble ^INDArray a #^ints ixs))) 172 | (mp/get-nd [m indexes] 173 | (let [ixs (int-array indexes)] 174 | (.getDouble ^INDArray a #^ints ixs))) 175 | mp/PIndexedSetting 176 | (mp/set-1d [m row v] 177 | (let [d (.dup ^INDArray a) 178 | ixs (int-array row)] 179 | (.putScalar ^INDArray d #^ints ixs #^double (double v)))) 180 | (mp/set-2d [m row column v] 181 | (let [d (.dup ^INDArray a) 182 | ixs (int-array [row column])] 183 | (.putScalar ^INDArray d #^ints ixs #^double (double v)))) 184 | (mp/set-nd [m indexes v] 185 | (let [d (.dup ^INDArray a) 186 | indexes (int-array indexes)] 187 | (.putScalar ^INDArray d #^ints indexes #^double (double v)))) 188 | (mp/is-mutable? [m] false) 189 | mp/PMatrixAdd 190 | (mp/matrix-add [m w] (wrap-matrix m (.add ^INDArray a ^INDArray (.a ^clj-INDArray (mp/construct-matrix m w))))) 191 | (mp/matrix-sub [m w] (wrap-matrix m (.sub ^INDArray a ^INDArray (.a ^clj-INDArray (mp/construct-matrix m w))))) 192 | mp/PZeroDimensionConstruction 193 | (mp/new-scalar-array [m] (mp/construct-matrix m 0)) 194 | (mp/new-scalar-array [m value] (mp/construct-matrix m value)) 195 | mp/PMatrixEquality 196 | (mp/matrix-equals [m m2] (if (= (type m) (type m2)) (.equals ^INDArray a ^INDArray (.a ^clj-INDArray m2)) (.equals ^INDArray a ^INDArray (.a ^clj-INDArray (mp/construct-matrix m m2))))) 197 | mp/PMatrixScaling 198 | (mp/scale [m b] (wrap-matrix m (.mul ^INDArray a ^Number (double b)))) 199 | (mp/pre-scale [m b] (wrap-matrix m (.mul ^INDArray a ^Number (double b)))) 200 | mp/PMatrixPredicates 201 | (mp/identity-matrix? [m] 202 | (let [h (.a m)] (and (square? a) (mp/diagonal? m) (let [diag (.a ^clj-INDArray (mp/main-diagonal m))] (= 1.0 (.minNumber ^INDArray diag) (.maxNumber ^INDArray diag)))))) 203 | (mp/zero-matrix? [m] (let [h (.a m)] (and (zero? (.minNumber ^INDArray h)) (zero? (.maxNumber ^INDArray h))))) 204 | (mp/symmetric? [m] false) 205 | mp/PSpecialisedConstructors 206 | (mp/identity-matrix 207 | [m dims] (wrap-matrix m (Nd4j/eye dims) false false)) 208 | (mp/diagonal-matrix 209 | [m diagonal-values] 210 | (let [to-ret (Nd4j/eye #^int (int (count diagonal-values)))] 211 | (doseq [i (range (count diagonal-values))] 212 | (.put ^INDArray to-ret #^int i #^int i ^Number (get diagonal-values i))) 213 | (wrap-matrix m to-ret false false))) 214 | mp/PMatrixTypes 215 | (mp/diagonal? [m] (and (triangleUpper a (aget (.shape ^INDArray a) 0) 0 0) (triangleLower ^INDArray a (aget (.shape ^INDArray a) 0) 0 0))) 216 | (mp/upper-triangular? [m] (triangleUpper ^INDArray a (aget (.shape ^INDArray a) 0) 0 0)) 217 | (mp/lower-triangular? [m] (triangleLower ^INDArray a (aget (.shape ^INDArray a) 0) 0 0)) 218 | (mp/positive-definite? [m] (throw (UnsupportedOperationException. "not implemented"))) 219 | (mp/positive-semidefinite? [m] (throw (UnsupportedOperationException. "not implemented"))) 220 | (mp/orthogonal? [m eps] 221 | (mp/matrix-equals-epsilon 222 | (wrap-matrix m (.mmul (.transpose a) a)) 223 | (wrap-matrix m (Nd4j/eye (aget (.shape a) 0))) eps)) 224 | mp/PMatrixSubComponents 225 | (mp/main-diagonal [m] (wrap-matrix m (Nd4j/diag ^INDArray a))) 226 | ;mp/PMatrixEqualityEpsilon 227 | ;(mp/matrix-equals-epsilon [s b eps] 228 | ; (let [b-new (if (instance? org.nd4j.linalg.api.ndarray.INDArray (.a ^clj-INDArray b)) (.a ^clj-INDArray b) (convert-mn a (m/to-nested-vectors (.a ^clj-INDArray b)))) 229 | ; a-add (.add ^INDArray a ^Number eps) 230 | ; a-sub (.sub ^INDArray a ^Number eps) 231 | ; gt (.gt ^INDArray a-add ^INDArray b-new) 232 | ; lt (.lt ^INDArray a-sub ^INDArray b-new) 233 | ; gt-min (.minNumber ^INDArray gt) 234 | ; gt-max (.maxNumber ^INDArray gt) 235 | ; lt-min (.minNumber ^INDArray lt) 236 | ; lt-max (.maxNumber ^INDArray lt)] 237 | ; (= gt-min gt-max lt-min lt-max))) 238 | mp/PBroadcast 239 | (mp/broadcast [m target-shape] (broadcast m target-shape)) 240 | mp/PBroadcastLike 241 | (mp/broadcast-like [m z] 242 | (let [to-broadcast (mp/construct-matrix m z)] 243 | (if (.scalar ^clj-INDArray to-broadcast) 244 | (wrap-matrix m (.assign ^INDArray (Nd4j/create (.shape a)) ^java.lang.Number z)) 245 | (mp/broadcast to-broadcast (mp/get-shape m))))) 246 | mp/PBroadcastCoerce 247 | (mp/broadcast-coerce [m z] 248 | (mp/broadcast-like m z)) 249 | mp/PValueEquality 250 | (mp/value-equals [m r] (mp/matrix-equals m r)) 251 | mp/PRotate 252 | (mp/rotate [m dim places] (wrap-matrix m (rotate4 m dim places))) 253 | mp/PVectorView 254 | (mp/as-vector [m] (if (and (= (alength (.shape a)) 2) (or (.isColumnVector a) (.isRowVector a) vector)) (if (.isRowVector a) (wrap-matrix m a true false) (wrap-matrix m (.reshape a (int-array [1 (max (vec (.shape a)))])) true false)) (convert-mn a (vec (.asDouble (.data (.ravel a))))))) 255 | mp/PReshaping 256 | (mp/reshape [m shape] (let [v (if (= (count (vec shape)) 1) true false) 257 | shape (if v (conj shape 1) shape)] 258 | (wrap-matrix m (.reshape a (int-array shape)) v false))) 259 | mp/PElementCount 260 | (mp/element-count [m] (if empty 0 (.length a))) 261 | mp/PSameShape 262 | (mp/same-shape? [w r] (let [b (convert-mn w r)] (and (= (mp/get-shape w) (mp/get-shape b)) (= empty (.empty ^clj-INDArray b)) (= scalar (.scalar ^clj-INDArray b)) (= vector (.vector ^clj-INDArray b))))) 263 | mp/PImmutableAssignment 264 | (mp/assign [m source] 265 | (let [r (mp/broadcast-coerce m source)] 266 | (if (identical? r source) (mp/clone r) r))) 267 | mp/PMatrixCloning 268 | (mp/clone [m] 269 | (wrap-matrix m (.dup a))) 270 | mp/PExponent 271 | (mp/element-pow [m exponent] (let [result (Nd4j/create (.shape a))] (.exec (Nd4j/getExecutioner) (Pow. (.dup a) result exponent)) (wrap-matrix m result))) 272 | mp/PSquare 273 | (mp/square [m] (mp/element-pow m 2)) 274 | mp/PMatrixDivide 275 | (mp/element-divide 276 | [m] (wrap-matrix m (.rdiv a 1))) 277 | (mp/element-divide 278 | [m w] (wrap-matrix m (.div a (.a (convert-mn m w))))) 279 | Object 280 | (toString [m] (str a)) 281 | ;clojure.lang.Seqable 282 | ;(seq [m] ) 283 | ;; The semantics should be to return a seq / iterator of row-major slices 284 | ;; 285 | ;; This enables matrices to be used with regular Clojure sequence operations e.g. 286 | ;;;;;;;;;;;;;;;;;;;;;; 287 | ; PTypeInfo 288 | ) 289 | 290 | (defn- wrap-matrix ([^clj-INDArray m ^INDArray mx] (->clj-INDArray mx (.vector m) (.scalar m) (.empty m))) 291 | ([^clj-INDArray _ ^INDArray mx ^Boolean vector ^Boolean scalar] (->clj-INDArray mx vector scalar false)) 292 | ([^clj-INDArray _ ^INDArray mx ^Boolean vector ^Boolean scalar ^Boolean empty] (->clj-INDArray mx vector scalar empty))) 293 | 294 | (defn- empty-matrix ([^INDArray mx] (->clj-INDArray mx false false true))) 295 | 296 | (defn- convert-to-nested-vectors [^INDArray m] 297 | (let [sp (reverse (vec (.shape m))) 298 | flattened (vec (.asDouble (.data m)))] 299 | (first (reduce #(partition %2 %1) flattened sp)))) 300 | 301 | (defn- convert-mn [m data] 302 | (if (instance? nd4clj.matrix.clj-INDArray data) 303 | data 304 | (let [data-p (cond ;(instance? org.nd4j.linalg.api.ndarray.INDArray data) 305 | ;(convert-to-nested-vectors data) 306 | (instance? clojure.lang.PersistentVector data) 307 | (if (instance? java.lang.Number (first data)) [data] (clojure.walk/prewalk #(if (instance? org.nd4j.linalg.api.ndarray.INDArray %) (first (convert-to-nested-vectors %)) %) data)) 308 | (instance? java.lang.Number data) 309 | [[data]] 310 | ;(or (instance? (Class/forName "[D") data) (instance? (Class/forName "[[D") data)) 311 | ;(let [pvec (m/to-nested-vectors data)] (if (instance? java.lang.Number (first pvec)) [pvec] pvec)) 312 | :else 313 | (let [pre (m/to-nested-vectors data)] (cond (mp/is-scalar? pre) [[pre]] (mp/is-vector? pre) [pre] :else pre))) 314 | crr (Nd4j/create 315 | (double-array (vec (flatten data-p))) 316 | (int-array 317 | (loop [cur data-p lst []] 318 | (if (not (sequential? cur)) 319 | lst 320 | (recur (first cur) (conj lst (count cur)))))))] 321 | (->clj-INDArray crr (mp/is-vector? data) (mp/is-scalar? data) false)))) 322 | 323 | (def canonical-object (->clj-INDArray (Nd4j/create 2 2) false false false)) 324 | 325 | (imp/register-implementation :nd4j canonical-object) 326 | ;(clojure.core.matrix/set-current-implementation :nd4j) 327 | 328 | ;(mp/get-slice-seq (m/matrix :ndarray [1 2]) 0) 329 | 330 | ;(mp/is-vector? (m/matrix :ndarray (m/matrix :nd4j [[1 2]]))) 331 | 332 | 333 | (vec (.shape (.a (m/matrix :nd4j [[1 2] [3 2]])))) 334 | (let [array (.a (m/matrix :nd4j [[1 2] [3 2] [4 5]])) 335 | sp (vec (.shape array)) 336 | repeat-num (reduce #(conj %1 (* (sp %2) (last %1))) [1] (range (dec (count sp))))] 337 | (map #(->> %1 range (map (fn [x] (repeat %2 x)))) sp repeat-num)) 338 | --------------------------------------------------------------------------------