forked from incanter/incanter
/
core.clj
1564 lines (1148 loc) · 45 KB
/
core.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; core.clj -- Core functions built on the CERN Colt Library
;; by David Edgar Liebke http://incanter.org
;; March 11, 2009
;; Copyright (c) David Edgar Liebke, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.htincanter.at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
;; CHANGE LOG
;; March 11, 2009: First version
(ns #^{:doc "This is the core numerics library for Incanter.
It provides functions for vector- and matrix-based
mathematical operations and the core data manipulation
functions for Incanter.
This library is built on Parallel Colt
(http://sites.google.com/site/piotrwendykier/software/parallelcolt)
an extension of the Colt numerics library
(http://acs.lbl.gov/~hoschek/colt/).
"
:author "David Edgar Liebke"}
incanter.core
;(:gen-class)
(:use (incanter internal))
(:import (incanter Matrix)
(cern.colt.matrix.tdouble DoubleMatrix2D
DoubleFactory2D
DoubleFactory1D)
(cern.colt.matrix.tdouble.algo DoubleAlgebra
DoubleFormatter)
(cern.colt.matrix.tdouble.algo.decomposition DoubleCholeskyDecomposition
DoubleSingularValueDecompositionDC
DoubleEigenvalueDecomposition
DoubleLUDecomposition
DoubleQRDecomposition)
(cern.jet.math.tdouble DoubleFunctions DoubleArithmetic)
(cern.colt.function.tdouble DoubleDoubleFunction DoubleFunction)
(cern.colt.list.tdouble DoubleArrayList)
(cern.jet.stat.tdouble DoubleDescriptive Gamma)
(javax.swing JTable JScrollPane JFrame)
(java.util Vector)))
(defn matrix
"
Returns an instance of an incanter.Matrix, which is an extension of
cern.colt.matrix.tdouble.impl.DenseColDoubleMatrix2D that implements the Clojure
interface clojure.lang.ISeq. Therefore Clojure sequence operations can
be applied to matrices. A matrix consists of a sequence of rows, where
each row is a one-dimensional row matrix. One-dimensional matrices are
in turn, sequences of numbers. Equivalent to R's matrix function.
Examples:
(def A (matrix [[1 2 3] [4 5 6] [7 8 9]])) ; produces a 3x3 matrix
(def A2 (matrix [1 2 3 4 5 6 7 8 9] 3)) ; produces the same 3x3 matrix
(def B (matrix [1 2 3 4 5 6 7 8 9])) ; produces a 9x1 column vector
(first A) ; produces a row matrix [1 2 3]
(rest A) ; produces a sub matrix [[4 5 6] [7 8 9]]
(first (first A)) ; produces 1.0
(rest (first A)) ; produces a row matrix [2 3]
; since (plus row1 row2) adds the two rows element-by-element
(reduce plus A) ; produces the sums of the columns
; and since (sum row1) sums the elements of the row
(map sum A) ; produces the sums of the rows
; you can filter the rows using Clojure's filter function
(filter #(> (nth % 1) 4) A) ; returns the rows where the second column is greater than 4.
References:
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/tdouble/DoubleMatrix2D.html
"
([data]
(make-matrix data))
([data ncol]
(make-matrix data ncol))
([init-val rows cols]
(make-matrix init-val rows cols)))
(defn matrix?
" Test if obj is 'derived' incanter.Matrix."
([obj] (is-matrix obj)))
(defn nrow
" Returns the number of rows in the given matrix. Equivalent to R's nrow function."
([mat]
(cond
(matrix? mat) (.rows #^Matrix mat)
(coll? mat) (count mat))))
(defn ncol
" Returns the number of columns in the given matrix. Equivalent to R's ncol function."
([mat]
(cond
(matrix? mat) (.columns #^Matrix mat)
(coll? mat) 1 )))
(defn dim
" Returns a vector with the number of rows and columns of the given matrix. "
([mat]
[(nrow mat) (ncol mat)]))
(defn identity-matrix
" Returns an n-by-n identity matrix.
Examples:
(identity-matrix 4)
"
([n] (Matrix. (.identity DoubleFactory2D/dense n))))
(defn diag
" If given a matrix, diag returns a sequence of its diagonal elements.
If given a sequence, it returns a matrix with the sequence's elements
on its diagonal. Equivalent to R's diag function.
Examples:
(diag [1 2 3 4])
(def A (matrix [[1 2 3]
[4 5 6]
[7 8 9]]))
(diag A)
"
([m]
(cond
(matrix? m)
(seq (.toArray (.diagonal DoubleFactory2D/dense m)))
(coll? m)
(Matrix. (.diagonal DoubleFactory2D/dense (.make DoubleFactory1D/dense (double-array m))))
(number? m)
m)))
(defn #^Matrix trans
" Returns the transpose of the given matrix. Equivalent to R's t function
Examples:
(def A (matrix [[1 2 3]
[4 5 6]
[7 8 9]]))
(trans A)
"
([mat]
(cond
(matrix? mat)
(.viewDice #^Matrix mat)
(coll? mat)
(.viewDice #^Matrix (matrix #^double-array mat)))))
(defn- except-for
" Returns a lazy list of numbers ranging from 0 to n, except for the given exceptions.
Examples:
(except-for 10 3)
(except-for 10 [5 7])
"
([n exceptions]
(let [except (if (coll? exceptions) exceptions [exceptions])]
(for [i (range n) :when (reduce #(and %1 %2) (map #(not= i %) except))] i))))
(defmulti sel
"
Returns an element or subset of the given matrix, or dataset.
Argument:
a matrix object or dataset.
Options:
:rows (default true)
returns all rows by default, can pass a row index or sequence of row indices
:cols (default true)
returns all columns by default, can pass a column index or sequence of column indices
:except-rows (default nil) can pass a row index or sequence of row indices to exclude
:except-cols (default nil) can pass a column index or sequence of column indices to exclude
:filter (default nil)
a function can be provided to filter the rows of the matrix
Examples:
(use 'incanter.datasets)
(def iris (to-matrix (get-dataset :iris)))
(sel iris 0 0) ; first element
(sel iris :rows 0 :cols 0) ; also first element
(sel iris :cols 0) ; first column of all rows
(sel iris :cols [0 2]) ; first and third column of all rows
(sel iris :rows (range 10) :cols (range 2)) ; first two columns of the first 10 rows
(sel iris :rows (range 10)) ; all columns of the first 10 rows
;; exclude rows or columns
(sel iris :except-rows (range 10)) ; all columns of all but the first 10 rows
(sel iris :except-cols 1) ; all columns except the second
;; return only the first 10 even rows
(sel iris :rows (range 10) :filter #(even? (int (nth % 0))))
;; select rows where distance (third column) is greater than 50
(sel iris :filter #(> (nth % 2) 4))
;; examples with datasets
(use 'incanter.datasets)
(def us-arrests (get-dataset :us-arrests))
(sel us-arrests :cols \"State\")
(sel us-arrests :cols :State)
(sel us-arrests :cols [\"State\" \"Murder\"])
(sel us-arrests :cols [:State :Murder])
"
(fn [mat & options] [(type mat) (keyword? (first options))]))
(defmethod sel [incanter.Matrix false]
([#^Matrix mat rows columns]
(let [rws (if (number? rows) [rows] rows)
cols (if (number? columns) [columns] columns)]
(cond
(and (number? rows) (number? columns))
(.getQuick mat rows columns)
(and (true? rws) (coll? cols))
(.viewSelection mat (int-array (range (.rows mat))) (int-array cols))
(and (coll? rws) (true? cols))
(.viewSelection mat (int-array rws) (int-array (range (.columns mat))))
(and (coll? rws) (coll? cols))
(.viewSelection mat (int-array rws) (int-array cols))
(and (true? rws) (true? cols))
mat))))
(defmethod sel [incanter.Matrix true]
([#^Matrix mat & options]
(let [opts (when options (apply assoc {} options))
except-rows (:except-rows opts)
except-columns (:except-cols opts)
rows (cond
(:rows opts)
(:rows opts)
except-rows
(except-for (.rows mat) except-rows)
:else
true)
cols (cond
(:cols opts)
(:cols opts)
except-columns
(except-for (.columns mat) except-columns)
:else
true)
row-filter (:filter opts)
mat (if (nil? row-filter) mat (matrix (filter row-filter mat)))]
(cond
(and (number? rows) (number? cols))
(.getQuick mat rows cols)
(and (true? rows) (coll? cols))
(.viewSelection mat (int-array (range (.rows mat))) (int-array cols))
(and (true? rows) (number? cols))
(.viewSelection mat (int-array (range (.rows mat))) (int-array [cols]))
(and (coll? rows) (number? cols))
(.viewSelection mat (int-array rows) (int-array [cols]))
(and (coll? rows) (true? cols))
(.viewSelection mat (int-array rows) (int-array (range (.columns mat))))
(and (number? rows) (true? cols))
(.viewSelection mat (int-array [rows]) (int-array (range (.columns mat))))
(and (number? rows) (coll? cols))
(.viewSelection mat (int-array [rows]) (int-array cols))
(and (coll? rows) (coll? cols))
(.viewSelection mat (int-array rows) (int-array cols))
(and (true? rows) (true? cols))
mat))))
(defn bind-rows
" Returns the matrix resulting from concatenating the given matrices
and/or sequences by their rows. Equivalent to R's rbind.
Examples:
(def A (matrix [[1 2 3]
[4 5 6]
[7 8 9]]))
(def B (matrix [[10 11 12]
[13 14 15]]))
(bind-rows A B)
(bind-rows [1 2 3 4] [5 6 7 8])
"
([& args]
(reduce
(fn [A B]
(cond
(nil? (seq A))
B
(nil? (seq B))
A
(and (matrix? A) (matrix? B))
(conj A B)
(and (matrix? A) (coll? B))
(conj A B)
(and (coll? A) (matrix? B))
(conj (matrix A (count A)) B)
(and (coll? A) (coll? B))
(conj (matrix A (count A)) (matrix B (count B)))
:else
(throw (Exception. "Incompatible types"))))
args)))
(defn bind-columns
" Returns the matrix resulting from concatenating the given matrices
and/or sequences by their columns. Equivalent to R's cbind.
Examples:
(def A (matrix [[1 2 3]
[4 5 6]
[7 8 9]]))
(def B (matrix [10 11 12]))
(bind-columns A B)
(bind-columns [1 2 3 4] [5 6 7 8])
"
([& args]
(reduce
(fn [A B] (.viewDice (bind-rows (trans A) (trans B))))
args)))
;(defn inner-product [& args] (apply + (apply map * args)))
;(inner-product [1 2 3] [4 5 6]) ; = 32
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; MATH FUNCTIONS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn plus
" Performs element-by-element addition on multiple matrices, sequences
and/or numbers. Equivalent to R's + operator.
Examples:
(def A (matrix [[1 2 3]
[4 5 6]
[7 8 9]]))
(plus A A A)
(plus A 2)
(plus 2 A)
(plus [1 2 3] [1 2 3])
(plus [1 2 3] 2)
(plus 2 [1 2 3])
"
([& args] (reduce (fn [A B] (combine-with A B clojure.core/+ plus)) args)))
(defn minus
" Performs element-by-element subtraction on multiple matrices, sequences
and/or numbers. If only a single argument is provided, returns the
negative of the given matrix, sequence, or number. Equivalent to R's - operator.
Examples:
(def A (matrix [[1 2 3]
[4 5 6]
[7 8 9]]))
(minus A)
(minus A A A)
(minus A 2)
(minus 2 A)
(minus [1 2 3] [1 2 3])
(minus [1 2 3] 2)
(minus 2 [1 2 3])
(minus [1 2 3])
"
;([& args] (reduce (fn [A B] (combine-with A B clojure.core/- minus)) args)))
([& args] (if (= (count args) 1)
(combine-with 0 (first args) clojure.core/- minus)
(reduce (fn [A B] (combine-with A B clojure.core/- minus)) args))))
(defn mult
" Performs element-by-element multiplication on multiple matrices, sequences
and/or numbers. Equivalent to R's * operator.
Examples:
(def A (matrix [[1 2 3]
[4 5 6]
[7 8 9]]))
(mult A A A)
(mult A 2)
(mult 2 A)
(mult [1 2 3] [1 2 3])
(mult [1 2 3] 2)
(mult 2 [1 2 3])
"
([& args] (reduce (fn [A B] (combine-with A B clojure.core/* mult)) args)))
(defn div
" Performs element-by-element division on multiple matrices, sequences
and/or numbers. Equivalent to R's / operator.
Examples:
(def A (matrix [[1 2 3]
[4 5 6]
[7 8 9]]))
(div A A A)
(div A 2)
(div 2 A)
(div [1 2 3] [1 2 3])
(div [1 2 3] 2)
(div 2 [1 2 3])
(div [1 2 3]) ; returns [1 1/2 13]
"
([& args] (if (= (count args) 1)
(combine-with 1 (first args) clojure.core// div)
(reduce (fn [A B] (combine-with A B clojure.core// div)) args))))
(defn pow
" This is an element-by-element exponent function, raising the first argument
by the exponents in the remaining arguments. Equivalent to R's ^ operator."
([& args] (reduce (fn [A B] (combine-with A B #(Math/pow %1 %2) pow)) args)))
(defn atan2
"Returns the atan2 of the elements in the given matrices, sequences or numbers.
Equivalent to R's atan2 function."
([& args] (reduce (fn [A B] (combine-with A B #(Math/atan2 %1 %2)
cern.jet.math.tdouble.DoubleFunctions/atan2)) args)))
(defn sqrt
"Returns the square-root of the elements in the given matrix, sequence or number.
Equivalent to R's sqrt function."
([A] (pow A 1/2)))
(defn sq
"Returns the square of the elements in the given matrix, sequence or number.
Equivalent to R's sq function."
([A] (mult A A)))
(defn log
"Returns the natural log of the elements in the given matrix, sequence or number.
Equvalent to R's log function."
([A] (transform-with A #(Math/log %) log)))
(defn log2
"Returns the log base 2 of the elements in the given matrix, sequence or number.
Equivalent to R's log2 function."
([A] (transform-with A #(/ (Math/log %) (Math/log 2)) log2)))
(defn log10
"Returns the log base 10 of the elements in the given matrix, sequence or number.
Equivalent to R's log10 function."
([A] (transform-with A #(Math/log10 %) (lg 10.0))))
(defn exp
"Returns the exponential of the elements in the given matrix, sequence or number.
Equivalent to R's exp function."
([A] (transform-with A #(Math/exp %) exp)))
(defn abs
"Returns the absolute value of the elements in the given matrix, sequence or number.
Equivalent to R's abs function."
([A] (transform-with A #(Math/abs (float %)) abs)))
(defn sin
"Returns the sine of the elements in the given matrix, sequence or number.
Equivalent to R's sin function."
([A] (transform-with A #(Math/sin %) sin)))
(defn asin
"Returns the arc sine of the elements in the given matrix, sequence or number.
Equivalent to R's asin function."
([A] (transform-with A #(Math/asin %) asin)))
(defn cos
"Returns the cosine of the elements in the given matrix, sequence or number.
Equivalent to R's cos function."
([A] (transform-with A #(Math/cos %) cos)))
(defn acos
"Returns the arc cosine of the elements in the given matrix, sequence or number.
Equivalent to R's acos function."
([A] (transform-with A #(Math/acos %) acos)))
(defn tan
"Returns the tangent of the elements in the given matrix, sequence or number.
Equivalent to R's tan function."
([A] (transform-with A #(Math/tan %) tan)))
(defn atan
"Returns the arc tangent of the elements in the given matrix, sequence or number.
Equivalent to R's atan function."
([A] (transform-with A #(Math/atan %) atan)))
(defn factorial
"
Returns the factorial of k (k must be a positive integer). Equivalent to R's
factorial function.
Examples:
(factorial 6)
References:
http://incanter.org/docs/parallelcolt/api/cern/jet/math/tdouble/DoubleArithmetic.html
http://en.wikipedia.org/wiki/Factorial
"
([k] (DoubleArithmetic/factorial k)))
(defn choose
"
Returns number of k-combinations (each of size k) from a set S with
n elements (size n), which is the binomial coefficient (also known
as the 'choose function') [wikipedia]
choose = n!/(k!(n - k)!)
Equivalent to R's choose function.
Examples:
(choose 25 6) ; => 2,598,960
References:
http://incanter.org/docs/parallelcolt/api/cern/jet/math/tdouble/DoubleArithmetic.html
http://en.wikipedia.org/wiki/Combination
"
([n k] (DoubleArithmetic/binomial (double n) (long k))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; MATRIX FUNCTIONS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn to-list
" Returns a list-of-lists if the given matrix is two-dimensional
and a flat list if the matrix is one-dimensional."
([#^Matrix mat]
(cond
(and (coll? mat) (not (matrix? mat)))
mat
(= (.columns mat) 1)
(first (map #(seq %) (seq (.toArray (.viewDice mat)))))
(= (.rows mat) 1)
(first (map #(seq %) (seq (.toArray mat))))
:else
(map #(seq %) (seq (.toArray mat))))))
(defn #^Matrix copy
"Returns a copy of the given matrix."
([#^Matrix mat] (.copy mat)))
(defn mmult
" Returns the matrix resulting from the matrix multiplication of the
the given arguments. Equivalent to R's %*% operator.
Examples:
(def A (matrix [[1 2 3]
[4 5 6]
[7 8 9]]))
(mmult A (trans A))
(mmult A (trans A) A)
References:
http://en.wikipedia.org/wiki/Matrix_multiplication
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/tdouble/DoubleMatrix2D.html
"
([& args]
(reduce (fn [A B]
(let [a (if (matrix? A) A (matrix A))
b (if (matrix? B) B (matrix B))
result (Matrix. (.zMult #^Matrix a #^Matrix b nil))]
(if (and (= (.rows result) 1) (= (.columns result) 1))
(.getQuick result 0 0)
result)))
args)))
(defn kronecker
" Returns the Kronecker product of the given arguments.
Examples:
(def x (matrix (range 6) 2))
(def y (matrix (range 4) 2))
(kronecker 4 x)
(kronecker x 4)
(kronecker x y)
"
([& args]
(reduce (fn [A B]
(let [a (cond
(matrix? A) A
(number? A) (matrix [A])
:else (matrix A))
b (cond
(matrix? B) B
(number? B) (matrix [B])
:else (matrix B))
rows (* (nrow a) (nrow b))
cols (* (ncol a) (ncol b))]
(apply bind-rows (for [i (range (nrow a))]
(apply bind-columns (for [j (range (ncol a))]
(mult (sel a i j) b)))))))
args)))
(defn solve
" Returns a matrix solution if A is square, least squares solution otherwise.
Equivalent to R's solve function.
Examples:
(solve (matrix [[2 0 0] [0 2 0] [0 0 2]]))
References:
http://en.wikipedia.org/wiki/Matrix_inverse
"
([#^Matrix A & B]
(if B
(Matrix. (.solve (DoubleAlgebra.) A (first B)))
(Matrix. (.inverse (DoubleAlgebra.) A)))))
(defn det
" Returns the determinant of the given matrix using LU decomposition. Equivalent
to R's det function.
References:
http://en.wikipedia.org/wiki/LU_decomposition
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/tdouble/algo/decomposition/DoubleLUDecomposition.html
"
;([mat] (.det (cern.colt.matrix.linalg.LUDecomposition. mat))))
([mat] (.det DoubleAlgebra/DEFAULT mat)))
(defn trace
" Returns the trace of the given matrix.
References:
http://en.wikipedia.org/wiki/Matrix_trace
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/tdouble/algo/DoubleAlgebra.html
"
([mat] (.trace DoubleAlgebra/DEFAULT mat)))
(defn vectorize
" Returns the vectorization (i.e. vec) of the given matrix.
The vectorization of an m-by-n matrix A, denoted by vec(A)
is the m*n-by-1 column vector obtain by stacking the columns
of the matrix A on top of one another.
For instance:
(= (vectorize (matrix [[a b] [c d]])) (matrix [a c b d]))
Examples:
(def A (matrix [[1 2] [3 4]]))
(vectorize A)
References:
http://en.wikipedia.org/wiki/Vectorization_(mathematics)
"
([mat]
(mapcat identity (trans mat))))
;(reduce #(concat %1 (to-list %2)) '() (trans mat))))
(defn half-vectorize
" Returns the half-vectorization (i.e. vech) of the given matrix.
The half-vectorization, vech(A), of a symmetric nxn matrix A
is the n(n+1)/2 x 1 column vector obtained by vectorizing only
the upper triangular part of A.
For instance:
(= (half-vectorize (matrix [[a b] [b d]])) (matrix [a b d]))
Examples:
(def A (matrix [[1 2] [2 4]]))
(half-vectorize A)
References:
http://en.wikipedia.org/wiki/Vectorization_(mathematics)
"
([mat]
(for [j (range (nrow mat)) i (range j (nrow mat))] (sel mat i j))))
(defn sum-of-squares
"Returns the sum-of-squares of the given sequence."
([x]
(let [xx (if (or (nil? x) (empty? x)) [0] (to-list x))]
(DoubleDescriptive/sumOfSquares (DoubleArrayList. (double-array xx))))))
(defn sum
"Returns the sum of the given sequence."
([x]
(let [xx (if (or (nil? x) (empty? x)) [0] (to-list x))]
(DoubleDescriptive/sum (DoubleArrayList. (double-array xx))))))
(defn prod
"Returns the product of the given sequence."
([x]
(let [xx (if (or (nil? x) (empty? x)) [0] (to-list x))]
(DoubleDescriptive/product (DoubleArrayList. (double-array xx))))))
(defn cumulative-sum
" Returns a sequence of cumulative sum for the given collection. For instance
The first value equals the first value of the argument, the second value is
the sum of the first two arguments, the third is the sum of the first three
arguments, etc.
Examples:
(use 'incanter.core)
(cumulative-sum (range 100))
"
([coll]
(loop [in-coll (rest coll)
cumu-sum [(first coll)]
cumu-val (first coll)]
(if (empty? in-coll)
cumu-sum
(let [cv (+ cumu-val (first in-coll))]
(recur (rest in-coll) (conj cumu-sum cv) cv))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; MATRIX DECOMPOSITION FUNCTIONS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn #^Matrix decomp-cholesky
" Returns the Cholesky decomposition of the given matrix. Equivalent to R's
chol function.
Returns:
a matrix of the triangular factor (note: the result from
cern.colt.matrix.linalg.CholeskyDecomposition is transposed so
that it matches the result return from R's chol function.
Examples:
(use '(incanter core stats charts datasets))
;; load the iris dataset
(def iris (to-matrix (get-dataset :iris)))
;; take the Cholesky decompostion of the correlation matrix of the iris data.
(decomp-cholesky (correlation iris))
References:
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/tdouble/algo/decomposition/DoubleCholeskyDecomposition.html
http://en.wikipedia.org/wiki/Cholesky_decomposition
"
([#^Matrix mat]
(.viewDice (.getL (DoubleCholeskyDecomposition. mat)))))
;(Matrix. (.viewDice (.getL (CholeskyDecomposition. mat)))))
(defn decomp-svd
" Returns the Singular Value Decomposition (SVD) of the given matrix. Equivalent to
R's svd function.
Returns:
a map containing:
:S -- the diagonal matrix of singular values
:U -- the left singular vectors U
:V -- the right singular vectors V
Examples:
(use 'incanter.core)
(def foo (matrix (range 9) 3))
(decomp-foo foo)
References:
http://en.wikipedia.org/wiki/Singular_value_decomposition
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/tdouble/algo/decomposition/DoubleSingularValueDecompositionDC.html
"
([mat]
(let [result (DoubleSingularValueDecompositionDC. mat, true, true)]
{:S (diag (Matrix. (.getS result)))
:U (Matrix. (.getU result))
:V (Matrix. (.getV result))})))
(defn decomp-eigenvalue
" Returns the Eigenvalue Decomposition of the given matrix. Equivalent to R's eig function.
Returns:
a map containing:
:values -- vector of eigenvalues
:vectors -- the matrix of eigenvectors
Examples:
(use 'incanter.core)
(def foo (matrix (range 9) 3))
(decomp-eigenvalue foo)
References:
http://en.wikipedia.org/wiki/Eigenvalue_decomposition
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/tdouble/algo/decomposition/DoubleEigenvalueDecomposition.html
"
([mat]
(let [result (DoubleEigenvalueDecomposition. mat)]
{:values (diag (Matrix. (.getD result)))
:vectors (Matrix. (.getV result))})))
(defn decomp-lu
" Returns the LU decomposition of the given matrix.
Examples:
(use 'incanter.core)
(def foo (matrix (range 9) 3))
(decomp-lu foo)
Returns:
a map containing:
:L -- the lower triangular factor
:U -- the upper triangular factor
References:
http://en.wikipedia.org/wiki/LU_decomposition
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/tdouble/algo/decomposition/DoubleLUDecomposition.html
"
([mat]
(let [result (DoubleLUDecomposition. mat)]
{:L (Matrix. (.getL result))
:U (Matrix. (.getU result))})))
(defn decomp-qr
" Returns the QR decomposition of the given matrix. Equivalent to R's qr function.
Examples:
(use 'incanter.core)
(def foo (matrix (range 9) 3))
(decomp-qr foo)
Returns:
a map containing:
:Q -- orthogonal factor
:R -- the upper triangular factor
References:
http://en.wikipedia.org/wiki/QR_decomposition
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/tdouble/algo/decomposition/DoubleQRDecomposition.html
"
([mat]
(let [result (DoubleQRDecomposition. mat)]
{:Q (Matrix. (.getQ result))
:R (Matrix. (.getR result))})))
(defn condition
" Returns the two norm condition number, which is max(S) / min(S), where S is the diagonal matrix of singular values from an SVD decomposition.
Examples:
(use 'incanter.core)
(def foo (matrix (range 9) 3))
(condition foo)
References:
http://en.wikipedia.org/wiki/Condition_number
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/tdouble/algo/decomposition/DoubleSingularValueDecompositionDC.html
"
([mat]
(.cond (DoubleSingularValueDecompositionDC. mat, true, true))))
(defn rank
" Returns the effective numerical matrix rank, which is the number of nonnegligible singular values.
Examples:
(use 'incanter.core)
(def foo (matrix (range 9) 3))
(rank foo)
References:
http://en.wikipedia.org/wiki/Matrix_rank
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/tdouble/algo/decomposition/DoubleSingularValueDecompositionDC.html
"
([mat]
(.rank (DoubleSingularValueDecompositionDC. mat, true, true))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;