-
Notifications
You must be signed in to change notification settings - Fork 1
/
flmatrix.rkt
2225 lines (1968 loc) · 69.6 KB
/
flmatrix.rkt
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
#lang racket
(provide (all-defined-out))
;;; TODO
;;; * Improve matrix-expt! (avoid allocation)
;;; NOTES
;;; * Contracts will be added before release
;;;
;;; * See tests at bottom for examples.
;;; FEEDBACK
;;; * Where is CBLAS and LAPACK on your platform
;;; (Windows and Linux)
;;; * What are the libraries named?
;;; * Do all tests evaluate to #t on your platform?
;;; * Mail: jensaxel@soegaard.net
;;;
;;; PLATFORMS TESTED
;;; * OS X Mountain Lion (Working)
;;;
;;; IDEAS
;;; Potential Improvements
;;; * DONE Unsafe operations
;;; * DONE add lda to the flmatrix structure
;;; * DONE support shared submatrix without allocation
;;; * DONE Improve equal?
;;; * Use dgeequ before dgetrf (in matrix-lu!)
;;; * Use an extra call with lwork=-1 in matrix-inverse!
;;; * support different storage schemes
;;; http://www.netlib.org/lapack/lug/node121.html
;;; Useful routines to consider:
;;; * http://www.math.utah.edu/software/lapack/lapack-d/dlazro.html
;;; * http://www.math.utah.edu/software/lapack/lapack-d/dlaset.html
;;; Constructs diagonal matrices. Use for flmatrix-identity
;;; * http://www.math.utah.edu/software/lapack/lapack-d/dlaswp.html
;;; Row interchanges
;;; * http://www.math.utah.edu/software/lapack/lapack-d/drscl.html
;;; Scale by 1/a with correct rounding
(require ffi/vector
ffi/unsafe
ffi/unsafe/define
racket/flonum
(for-syntax
racket/format
racket/string
ffi/unsafe))
;;;
;;; LIBRARIES
;;;
; CBLAS and LAPACK are used.
; The first two are C-based whereas LAPACK is Fortran based.
;; Find placement of libraries.
(define-values (cblas-lib lapack-lib)
(case (system-type)
; MACOS
[(macosx)
(define veclib-lib
; OS X: Contains CBLAS both CATLAS. CATLAS is not used here.
; https://developer.apple.com/library/mac/#documentation/Accelerate/
; Reference/BLAS_Ref/Reference/reference.html
(ffi-lib "/System/Library/Frameworks/vecLib.framework/Versions/Current/vecLib"))
(define cblas-lib veclib-lib)
(define lapack-lib
(ffi-lib
(string-append
"/System/Library/Frameworks/Accelerate.framework/"
"Versions/A/Frameworks/vecLib.framework/Versions/A/libLAPACK")))
(values cblas-lib lapack-lib)]
; UNIX
[(unix)
(define cblas-lib (ffi-lib "libblas" '("3" #f))) ; works on debian
(define lapack-lib (ffi-lib "liblapack" '("3" #f))) ; works on debian
(values cblas-lib lapack-lib)]
[(windows)
; tester needed
(error 'tester-needed)]))
;;; Load libraries
(define-ffi-definer define-cblas cblas-lib)
(define-ffi-definer define-lapack lapack-lib)
;;;
;;; REFERENCES
;;;
; LAPACK Naming scheme:
; http://www.netlib.org/lapack/lug/node24.html
;;;
;;; CONFIGURATION
;;;
(define epsilon 1e-13)
; If two flmatrices have the same size and
; the differences between two entries are
; smaller than epsilon, they are considered
; equal? . Furthermore if all entries are
; smaller than epislon flmatrix-zero?
; returns true.
(define current-max-flmatrix-print-size (make-parameter 100))
; For matrices with smaller size, all
; entries are printed. For larger matrices
; only the dimension is printed.
;;;
;;; REPRESENTATION
;;;
; BLAS/LAPACK represents matrices as one-dimensional arrays
; of numbers (S=single, D=double, X=complex or Z=double complex).
; This library uses arrays of doubles.
(define _flmatrix (_cpointer 'flmatrix))
; The array is wrapped in a struct, which besides
; a pointer to the array, holds the number of
; rows and columns. Future extension could be to
; allow different types of numbers, or perhaps
; choose specialized operations for triangular matrices.
(define (flmatrix-print A port mode)
(define print (if mode write display))
(print
(if (< (flmatrix-size A) (current-max-flmatrix-print-size))
; constructor style printing:
(list 'flmatrix: ; (flmatrix-m A) (flmatrix-n A)
(flmatrix->lists A))
; omit actual elements
(list 'flmatrix (flmatrix-m A) (flmatrix-n A)
"..."))
port))
(define (flmatrix= A B [eps #f])
(define-param (m n a lda) A)
(define-param (r c b ldb) B)
(and (= m r) (= n c)
(for*/and ([j (in-range n)]
[i (in-range m)])
(define aij (unsafe-ref a lda i j))
(define bij (unsafe-ref b ldb i j))
(if eps
(fl<= (fl- aij bij) eps)
(fl= aij bij)))))
; m = rows, n = cols, a = mxn array of doubles
; lda = leading dimension of a (see below)
(struct flmatrix (m n a lda)
#:methods gen:custom-write
[(define write-proc flmatrix-print)]
#:methods gen:equal+hash
[(define equal-proc
(λ (A B rec)
(and (= (flmatrix-m A) (flmatrix-m B))
(= (flmatrix-n A) (flmatrix-n B))
(or (equal? (flmatrix-a A) (flmatrix-a B))
(flmatrix= A B epsilon)))))
(define hash-proc
; TODO: Avoid allocation in hash-proc.
(λ (A rec)
(define-param (m n) A)
(rec (cons m (cons n (flmatrix->vector A))))))
(define hash2-proc
(λ (A rec)
(define-param (m n) A)
(rec (cons n (cons m (flmatrix->vector A))))))])
; convenient destructuring
(define-syntax (define-param stx)
(syntax-case stx ()
[(_ (m n) A)
#'(begin
(define A1 A)
(define m (flmatrix-m A1))
(define n (flmatrix-n A1)))]
[(_ (m n a) A)
#'(begin
(define A1 A)
(define m (flmatrix-m A1))
(define n (flmatrix-n A1))
(define a (flmatrix-a A1)))]
[(_ (m n a lda) A)
#'(begin
(define A1 A)
(define m (flmatrix-m A1))
(define n (flmatrix-n A1))
(define a (flmatrix-a A1))
(define lda (flmatrix-lda A1)))]
[_
(error)]))
;;;
;;; MEMORY LAYOUT
;;;
; The entries are layed out in column major order.
; This means that the entries in a column are
; contigious. LAPACK needs this order.
; a[0] a[0 +lda] a[0 + 2*lda] ... a[0+(n-1)*lda]
; a[1] a[1 +lda]
; a[2]
; ... ...
; a[m-1] a[m-1 +lda] a[m01 + 2*lda] ... a[m-1+(n-1)*lda]
; For most matrices lda=m.
; For a submatrix it is possible that lda is larger than m.
; See http://stackoverflow.com/q/5009513/23567
; Example:
; If ma=10, na=12, a=<some adress>, lda=10,
; then mb=7, nb=2, b=a+3+4*lda, ldb=10 (=lda)
; represent a 7x2 submatrix whose upper, lefter
; corner in A is (3,4) (indices are 0-based).
; The array index of the (i,j)th entry is:
(define-syntax-rule (index lda i j)
(+ i (* j lda)))
(define (ptr-elm a lda i j)
; address of (i,j)th element
(ptr-add a (index lda i j) _double))
(define (shared-submatrix! A i j r s)
; return rxs matrix with upper left corner (i,j)
; entries are shared with A
; TODO: consider garbage collection
(define-param (m n a lda) A)
(flmatrix r s (ptr-elm a lda i j) lda))
(define (flsubmatrix A m n i j)
; TODO: argument order not consistent with shared-submatrix!
; return a the mxn submatrix of with upper
; left corner in (i,j)
(copy-flmatrix (shared-submatrix! A i j m n)))
(define (ptr-row a i)
; pointer to beginning of row a
(ptr-add a i _double))
(define (ptr-col a lda j)
; address of column j
(ptr-add a (* j lda) _double))
;;;
;;; CHECKS
;;;
(define (check-flmatrix who A)
(unless (flmatrix? A)
(raise-type-error who "expected flmatrix" A)))
(define (check-same-dimensions A B who)
(unless (flmatrix-same-dimensions? A B)
(raise-argument-error who "expected two matrices of the same size" A B)))
(define (check-product-dimensions who A B [C #f])
(unless (if (not C)
(= (flmatrix-n A) (flmatrix-m B))
(and (= (flmatrix-n A) (flmatrix-m B))
(= (flmatrix-m A) (flmatrix-m C))
(= (flmatrix-n B) (flmatrix-n C))))
(raise-argument-error
who
(if C
"expected three matrices with compatible dimensions"
"expected two matrices with compatible dimensions")
A B C)))
(define (check-matrix-vector-product-dimensions who A X Y)
(define-param (ma na) A)
(define-param (mx nx) X)
(define-param (my ny) Y)
(unless (if Y
(and (= na mx) (= mx my) (= ny nx 1))
(= na mx))
(raise-argument-error
who "expected same number of rows" A X Y)))
(define (check-legal-column who j A)
(unless (<= j (flmatrix-n A))
(raise-argument-error
who "column index too large" j))
(unless (<= 0 j)
(raise-argument-error
who "column index must be non-negative")))
(define (check-legal-row who i A)
(unless (<= i (flmatrix-m A))
(raise-argument-error
who "row index too large" i))
(unless (<= 0 i)
(raise-argument-error
who "row index must be non-negative")))
(define (check-square who A)
(define-param (m n) A)
(unless (= m n)
(raise-argument-error
who "square matrix expected" A)))
;;;
;;; SIZE and DIMENSION
;;;
(define (flmatrix-size A)
(check-flmatrix 'flmatrix-size A )
(define-param (m n) A)
(* m n))
(define (flmatrix-dimensions A)
(check-flmatrix 'flmatrix-dimensions A)
(define-param (m n) A)
(values m n))
(define (flmatrix-same-dimensions? A B)
(define-param (ma na) A)
(define-param (mb nb) B)
(and (= ma mb) (= na nb)))
(define (flmatrix-row-vector? A)
(= 1 (flmatrix-m A)))
(define (flmatrix-column-vector? A)
(= 1 (flmatrix-n A)))
;;;
;;; ALLOCATIONS and CONSTRUCTORS
;;;
(define (alloc-flmatrix m n)
(if (or (= m 0) (= n 0))
#f ; ~ NULL
(cast (malloc (* m n) _double 'atomic-interior)
_pointer _flmatrix)))
(define (alloc-same-size-matrix A)
(define-param (m n) A)
(alloc-flmatrix m n))
(define-syntax (define-cblas* stx)
(syntax-case stx ()
[(def xname _x (c ...) body ...)
(let ()
(define ((xname->name ctx xname) c)
(datum->syntax
ctx
(string->symbol
(string-replace (~a xname) "x" (~a c) #:all? #f))))
(define (c->_c c)
(unless (symbol? c)
(error (format "expected symbol, got: ~a" c)))
(case c
[(c) _double] ; TODO missing from ffi?
[(z) _double] ; TODO
[(d) _double]
[(s) _float]
[else (error "expected one of c, z, d, s")]))
(with-syntax ([(name ...)
(map (xname->name stx (syntax->datum #'xname))
(syntax->datum #'(c ...)))]
[(_c ...) (map c->_c (syntax->datum #'(c ...)))])
#'(begin
(define-cblas name
(let ([_x _c]) body ...))
...)))]))
(define-cblas* cblas_xcopy _x (s d c z)
; copy n elements from vector X to vector Y
(_fun (n : _int)
(X : _flmatrix) (incX : _int)
(Y : _flmatrix) (incY : _int)
-> _void))
#;(define-cblas cblas_dcopy
; copy n elements from vector X to vector Y
(_fun (n : _int)
(X : _flmatrix) (incX : _int)
(Y : _flmatrix) (incY : _int)
-> _void))
(define (unsafe-vector-copy! s a lda b)
; copy s elements from A into B
; element 0, lda, 2*lda, ... is copied
(cblas_dcopy s a lda b 1))
(define (unsafe-matrix-copy! m n a lda b ldb)
; copy the mxn matrix A into B
; copy has upper left corner in (i,j)
; Note: use (ptr-elm b ldb i j) to
; copy into a submatrix of b.
(for ([j (in-range n)])
(unsafe-vector-copy!
m (ptr-elm a lda 0 j) 1
(ptr-add b (* j ldb) _double))))
(define (copy-flmatrix A)
(define-param (m n a lda) A)
(define size (* m n))
(define b (cast (malloc size _double 'atomic)
_pointer _flmatrix))
(define ldb m)
(cond
[(= lda m) ; elements in a are contigious
(unsafe-vector-copy! size a 1 b)]
[else ; copy each column separately
(unsafe-matrix-copy! m n a lda b ldb)])
(flmatrix m n b ldb))
(define (make-flmatrix m n [x 0.0])
(define a (alloc-flmatrix m n))
(define x* (real->double-flonum x))
(if (= x 0.0)
(memset a 0 (* m n) _double)
(for ([i (* m n)]) (ptr-set! a _double i x*)))
(flmatrix m n a m))
(define (list->flmatrix xss)
(define m (length xss))
(define n (apply max (map length xss)))
(for*/flmatrix m n
([xs (in-list xss)]
[x (in-list xs)])
x))
(define (vectors->flmatrix xss)
(define m (vector-length xss))
(define n (vector-length (vector-ref xss 0)))
(for*/flmatrix m n
([xs (in-vector xss)]
[x (in-vector xs)])
x))
(define (flmatrix-identity m)
(define A (make-flmatrix m m 0.0))
(for ([i (in-range m)])
(flmatrix-set! A i i 1.0))
A)
(define (flmatrix-column A j)
; copy column j
(check-legal-column 'flmatrix-column j A)
(define-param (m n) A)
(copy-flmatrix (shared-submatrix! A 0 j m 1)))
(define (flmatrix-row A i)
; copy row i
(define-param (m n) A)
(check-legal-row 'flmatrix-row i A)
(copy-flmatrix (shared-submatrix! A i 0 1 n)))
;;;
;;; CONVERSIONS MATRIX <-> VECTOR
;;;
(define (flmatrix->vector A)
; the result vector uses row-major order
(define-param (m n a lda) A)
(for*/vector #:length (* m n)
([i (in-range 0 m)]
[j (in-range 0 n)])
(unsafe-ref a lda i j)))
(define (flmatrix->vectors A)
; the result is a vector of rows
(define-param (m n a lda) A)
(for/vector #:length m
([i (in-range 0 m)])
(for/vector #:length n
([j (in-range 0 n)])
(ptr-ref (ptr-elm a lda i j) _double))))
(define (vector->flmatrix m n v)
(unless (= (* m n) (vector-length v))
(raise-argument-error
'vector->flmatrix
"expected m*n to be the same as the length of the vector"))
(define a (alloc-flmatrix m n))
(define k 0)
(for* ([j (in-range n)]
[i (in-range m)])
(ptr-set! a _double* k ; (index m i j)
(vector-ref v (+ (* i n) j)))
(set! k (+ k 1)))
(flmatrix m n a m))
; (: matrix/dim : Integer Integer Number * -> (Matrix Number))
; construct a mxn flmatrix with elements from the values xs
; the length of xs must be m*n
(define (flmatrix/dim m n . xs)
(vector->flmatrix m n (list->vector xs)))
;;;
;;; COMPREHENSIONS
;;;
; (for/flmatrix m n (clause ...) . defs+exprs)
; Return an m x n flmatrix with elements from the last expr.
; The first n values produced becomes the first row.
; The next n values becomes the second row and so on.
; The bindings in clauses run in parallel.
(define-syntax (for/flmatrix stx)
(syntax-case stx ()
; elements in column 0 are generated first, then column 1, ...
[(_ m-expr n-expr #:column (for:-clause ...) . defs+exprs)
(syntax/loc stx
(let ()
(define m m-expr)
(define n n-expr)
(define m*n (* m n))
(define v (make-vector m*n 0))
(define k 0)
(for ([i (in-range m*n)] for:-clause ...)
(define x (let () . defs+exprs))
(vector-set! v (+ (* n (remainder k m)) (quotient k m)) x)
(set! k (+ k 1)))
(vector->flmatrix m n v)))]
; elements in row 0 are generated first, then row 1, ...
[(_ m-expr n-expr (clause ...) . defs+exprs)
(syntax/loc stx
(let ([m m-expr] [n n-expr])
(define flat-vector
(for/vector #:length (* m n)
(clause ...) . defs+exprs))
; TODO (efficiency): Skip temporary vector
(vector->flmatrix m n flat-vector)))]))
; (for*/flmatrix m n (clause ...) . defs+exprs)
; Return an m x n flmatrix with elements from the last expr.
; The first n values produced becomes the first row.
; The next n values becomes the second row and so on.
; The bindings in clauses run nested.
; (for*/flmatrix m n #:column (clause ...) . defs+exprs)
; Return an m x n flmatrix with elements from the last expr.
; The first m values produced becomes the first column.
; The next m values becomes the second column and so on.
; The bindings in clauses run nested.
(define-syntax (for*/flmatrix stx)
(syntax-case stx ()
[(_ m-expr n-expr #:column (clause ...) . defs+exprs)
(syntax/loc stx
(let* ([m m-expr]
[n n-expr]
[v (make-vector (* m n) 0)]
[w (for*/vector #:length (* m n) (clause ...) . defs+exprs)])
(for* ([i (in-range m)] [j (in-range n)])
(vector-set! v (+ (* i n) j)
(vector-ref w (+ (* j m) i))))
(vector->flmatrix m n v)))]
[(_ m-expr n-expr (clause ...) . defs+exprs)
(syntax/loc stx
(let ([m m-expr] [n n-expr])
(vector->flmatrix
m n (for*/vector #:length (* m n) (clause ...) . defs+exprs))))]))
(define-syntax (for/flmatrix-sum stx)
(syntax-case stx ()
[(_ (for:-clause ...) . defs+exprs)
(syntax/loc stx
(let ()
(define sum #f)
(for (for:-clause ...)
(define a (let () . defs+exprs))
(set! sum (if sum (flmatrix+ sum a) a)))
sum))]))
;;;
;;; BINARY MATRIX OPERATIONS
;;;
;;; MATRIX SUM AND DIFFERENCE
(define-cblas* cblas_xaxpy _x (s d #;c #;z)
; Y := αX+Y ; X and Y are vectors
; If incX=3 then every 3rd element of X is used.
(_fun (n : _int) (alpha : _x)
(X : _flmatrix) (incX : _int)
(Y : _flmatrix) (incY : _int)
-> _void))
#;(define-cblas cblas_daxpy
; Y := αX+Y ; X and Y are vectors
; If incX=3 then every 3rd element of X is used.
(_fun (n : _int) (alpha : _double)
(X : _flmatrix) (incX : _int)
(Y : _flmatrix) (incY : _int)
-> _void))
(define (unsafe-vector-clear n a [lda 1])
(cblas_daxpy n -1.0 a lda a lda))
; TODO: Allow adding row to different matrix!
(define (flmatrix-add-scaled-row! A i1 s i2)
; scale row i2 and add to row i1
(check-legal-row 'matrix-add-scaled-row! i1 A)
(check-legal-row 'matrix-add-scaled-row! i2 A)
(define-param (m n a lda) A)
(define rowi1 (ptr-row a i1))
(define rowi2 (ptr-row a i2))
(define s* (real->double-flonum s))
(cblas_daxpy n s* rowi2 lda rowi1 lda)
A)
(define (flmatrix-add-scaled-row A i1 s i2)
(define B (copy-flmatrix A))
(flmatrix-add-scaled-row! B i1 s i2)
B)
(define (flmatrix-add-scaled-column! A j1 s j2)
(check-legal-row 'flmatrix-add-scaled-column! j1 A)
(check-legal-row 'flmatrix-add-scaled-column! j2 A)
(define-param (m n a lda) A)
(define colj1 (ptr-col a lda j1))
(define colj2 (ptr-col a lda j2))
(define s* (real->double-flonum s))
(cblas_daxpy m s* colj1 1 colj2 1)
A)
(define (flmatrix-add-scaled-column A i1 s i2)
(define B (copy-flmatrix A))
(flmatrix-add-scaled-column! B i1 s i2)
B)
(define (constant*flmatrix+flmatrix! alpha A B)
; B := αA+B
(define-param (m n a lda) A)
(define-param (r s b ldb) B)
(for ([j (in-range n)])
(cblas_daxpy m alpha
(ptr-col a lda j) 1
(ptr-col b ldb j) 1))
B)
(define (constant*flmatrix+flmatrix alpha A B)
; αA+B
(define αA+B (copy-flmatrix B))
(constant*flmatrix+flmatrix! alpha A αA+B)
αA+B)
(define (flmatrix+! A B)
; B := A + B
(check-same-dimensions A B 'flmatrix+!)
(constant*flmatrix+flmatrix! 1.0 A B))
(define (flmatrix+ A B)
; A + B
(check-same-dimensions A B 'flmatrix+)
(constant*flmatrix+flmatrix 1.0 A B))
(define (flmatrix-! A B)
; A := A - B
(check-same-dimensions A B 'flmatrix-!)
(constant*flmatrix+flmatrix! -1.0 B A))
(define (flmatrix- A [B #f])
(cond
[B
(check-same-dimensions A B 'flmatrix-)
(constant*flmatrix+flmatrix -1.0 B A)]
[else
(flmatrix-scale -1.0 A)]))
;;; Matrix x Matrix Multiplication
(define _CBLAS_ORDER _int)
(define CblasRowMajor 101)
(define CblasColMajor 102)
(define _CBLAS_TRANSPOSE _int)
(define CblasNoTrans 111)
(define CblasTrans 112)
(define CblasConjTrans 113)
(define-cblas* cblas_xgemm _x (s d z c)
; C := α(A*B)+βC
; 1. Multiplies A and B.
; 2. Scales result with alpha
; 3. Scales C with beta.
; 4. Stores sum in in C.
(_fun (order : _CBLAS_ORDER)
(transa : _CBLAS_TRANSPOSE) ; transpose A?
(transb : _CBLAS_TRANSPOSE) ; transpose B?
(m : _int) ; rows in A and C
(n : _int) ; cols in B and C
(k : _int) ; cols in A = rows in B
(alpha : _x) ; scaling factor for A and B
(A : _flmatrix)
(lda : _int) ; size of first dim of A
(B : _flmatrix)
(ldb : _int) ; size of first dim of B
(beta : _double) ; scaling for C
(C : _flmatrix)
(ldc : _int) ; size of first dim of C
-> _void))
(define (constant*matrix*matrix+constant*matrix! alpha A B beta C transA transB)
; C := α(A*B)+βC, maybe transpose A and/or B first
(check-product-dimensions 'constant*matrix*matrix+constant*matrix! A B C)
(define-param (m n a lda) A)
(define-param (r s b ldb) B)
(define-param (x y c ldc) C)
(define alpha* (real->double-flonum alpha))
(define beta* (real->double-flonum beta))
(cblas_dgemm CblasColMajor
(if transA CblasTrans CblasNoTrans)
(if transB CblasTrans CblasNoTrans)
m s n alpha*
a lda b ldb beta* c ldc)
C)
(define (flmatrix*! A B C
[alpha 1.0] [beta 1.0]
[transpose-A #f] [transpose-B #f])
; C := α(A*B)+βC, maybe transpose A and/or B first
(constant*matrix*matrix+constant*matrix!
alpha A B beta C transpose-A transpose-B))
(define (flmatrix* A B [C #f]
[alpha 1.0] [beta 1.0]
[transpose-A #f] [transpose-B #f])
; C := α(A*B)+βC, maybe transpose A and/or B first
(define C1 (or C (make-flmatrix (flmatrix-m A) (flmatrix-n B))))
(flmatrix*! A B C1 alpha beta transpose-A transpose-B))
;;; Matrix Power
(define (flmatrix-expt a n)
(check-flmatrix 'flmatrix-expt a)
(check-square 'matrix-expt a)
(cond
[(= n 0) (flmatrix-identity (flmatrix-m a))]
[(= n 1) (copy-flmatrix a)]
[(= n 2) (flmatrix* a a)]
[(even? n) (let ([a^n/2 (flmatrix-expt a (quotient n 2))])
(flmatrix* a^n/2 a^n/2))]
[else (flmatrix* a (flmatrix-expt a (sub1 n)))]))
;;; Matrix x Vector Multiplication
; NOTE: Functions accepting column vectors automatically
; convert (standard) vectors into mx1 matrices.
(define-cblas* cblas_xgemv _x (s d c z) ; Double GEneral Matrix Vector multiplication
; Y := α(AX) +(βY)
(_fun (order : _CBLAS_ORDER)
(transa : _CBLAS_TRANSPOSE) ; transpose A?
(m : _int) ; rows in A
(n : _int) ; cols in A
(alpha : _x) ; scaling factor for A
(A : _flmatrix)
(lda : _int)
(X : _flmatrix) ; vector
(ldx : _int)
(beta : _x) ; scaling for Y
(Y : _flmatrix) ; vector
(ldy : _int)
-> _void))
(define (constant*matrix*vector+constant*vector! alpha A X beta Y transA)
; unsafe: Y := α(AX) +(βY), maybe transpose A first
(define-param (m n a lda) A)
(cblas_dgemv CblasColMajor
(if transA CblasTrans CblasNoTrans)
m n
(real->double-flonum alpha)
a lda
(flmatrix-a X) 1
(real->double-flonum beta)
(flmatrix-a Y) 1)
Y)
(define (flmatrix*vector! A X Y [alpha 1.0] [beta 1.0]
[transpose-A #f])
(define X1 (result-flcolumn X))
(define Y1 (result-flcolumn Y))
(check-matrix-vector-product-dimensions
'constant*matrix*vector+constant*vector! A X1 Y1)
; Y := α(AX) +(βY), maybe transpose A first
(constant*matrix*vector+constant*vector!
alpha A X1 beta Y1 transpose-A))
(define (flmatrix*vector A X [Y #f] [alpha 1.0] [beta 1.0]
[transpose-A #f] )
; Y := α(AX) +(βY), maybe transpose A first
(define Y1 (or Y (make-flmatrix (flmatrix-m A) 1 0.0)))
(flmatrix*vector! A X Y1 alpha 1.0 transpose-A))
;;;
;;; ELEMENT WISE OPERATIONS
;;;
;;; Ref
(define (unsafe-ref a lda i j)
(ptr-ref (ptr-elm a lda i j) _double))
(define (flmatrix-ref A i j)
(define-param (m n a lda) A)
(unless (< -1 i m)
(raise-arguments-error
'matrix-ref (format "expected row index between 0 and ~a, got ~a" m i)))
(unless (< -1 j n)
(error 'matrix-ref
(format "expected column index between 0 and ~a, got ~a" n j)))
(unsafe-ref a lda i j))
;;; Set!
(define (unsafe-set! a lda i j x)
(ptr-set! (ptr-elm a lda i j) _double x))
(define (flmatrix-set! A i j x)
(check-legal-row 'flmatrix-set! i A)
(check-legal-column 'flmatrix-set! j A)
(define-param (m n a lda) A)
(define x* (real->double-flonum x))
(unsafe-set! a lda i j x*)
A)
;;; Scaling
(define-cblas* cblas_xscal _x (s d c z)
; X := αX vector
(_fun (n : _int) (alpha : _x)
(X : _flmatrix) (incX : _int)
-> _void))
(define (constant*matrix! s A)
; A := s*A
(define-param (m n a lda) A)
(define s* (real->double-flonum s))
(cond
[(= lda m)
(cblas_dscal (* m n) s* a 1)]
[else
(for ([j (in-range n)])
(cblas_dscal m s* (ptr-col a lda j) 1))])
A)
(define (flmatrix-scale! s A)
; A := s*A
(constant*matrix! s A))
(define (flmatrix-scale s A)
; s*A
(define sA (copy-flmatrix A))
(flmatrix-scale! s sA))
(define (shared-column-flmatrix A j)
(check-legal-column 'shared-column-flmatrix j A)
(define-param (m n) A)
(shared-submatrix! A 0 j m 1))
(define (shared-row-flmatrix A i)
(check-legal-row 'shared-row-flmatrix i A)
(shared-submatrix! A i 0 1 (flmatrix-n A)))
(define (flmatrix-scale-column! A j s)
; col_j := s * col_j
(constant*matrix! s (shared-column-flmatrix A j))
A)
(define (flmatrix-scale-column A j s)
(define B (copy-flmatrix A))
(flmatrix-scale-column! B j s)
B)
(define (flmatrix-scale-row! A i s)
; row_i := s * rwo_i
(check-legal-row 'flmatrix-scale-row! i A)
(define-values (m n) (flmatrix-dimensions A))
(constant*matrix! s (shared-row-flmatrix A i))
A)
(define (flmatrix-scale-row A i s)
(define B (copy-flmatrix A))
(flmatrix-scale-row! B i s)
B)
;;; Swapping
(define-cblas* cblas_xswap _x (s d c z)
; Swaps elements in the vectors x and y
(_fun (n : _int) ; length of vector
(X : _flmatrix) (incX : _int)
(Y : _flmatrix) (incY : _int)
-> _void))
(define (flmatrix-swap-rows! A i1 i2)
(check-legal-row 'flmatrix-swap-rows! i1 A)
(check-legal-row 'flmatrix-swap-rows! i2 A)
(unless (= i1 i2)
(define-param (m n a lda) A)
(define rowi1 (ptr-row a i1))
(define rowi2 (ptr-row a i2))
(cblas_dswap n rowi1 lda rowi2 lda))
A)
(define (flmatrix-swap-rows A i1 i2)
(define B (copy-flmatrix A))
(flmatrix-swap-rows! B i1 i2)
B)
(define (flmatrix-swap-columns! A j1 j2)
(check-legal-row 'flmatrix-swap-columns! j1 A)
(check-legal-row 'flmatrix-swap-columns! j2 A)
(unless (= j1 j2)
(define-param (m n a lda) A)
(define colj1 (ptr-col a lda j1))
(define colj2 (ptr-col a lda j2))
(cblas_dswap m colj1 1 colj2 1))
A)
(define (flmatrix-swap-columns A j1 j2)
(define B (copy-flmatrix A))
(flmatrix-swap-columns! B j1 j2)
B)
;;; Max Absolute Value
(define-cblas* cblas_ixamax _x (s d c z)
; Returns the index of the element with the largest
; absolute value in a vector.
(_fun (n : _int) (X : _flmatrix) (incX : _int)
-> _int))
(define (flmatrix-max-abs-index A)
(define-param (m n a lda) A)
(cond
[(= m lda)
(define idx (cblas_idamax (* m n) a lda))
(values (remainder idx m) (quotient idx m))]
[(= n 1)
(define idx (cblas_idamax m a 1))
(values (- idx 1) 0)]
[else
(define idx (make-vector n))
(for ([j (in-range n)])
(define i (cblas_idamax m (ptr-col a lda j) 1))
(vector-set! idx j (cons (cons i j) (unsafe-ref a lda i j))))
(define ij (car (vector-argmax cdr idx)))
(values (car ij) (cdr ij))]))
(define (flmatrix-max-abs-value A)
(define-values (i j) (flmatrix-max-abs-index A))
(flmatrix-ref A i j))
(define (flmatrix-zero? A [eps epsilon])
; set eps=#f to use normal equal?
(define val (flmatrix-max-abs-value A))
(if eps (< (abs val) eps) (zero? val)))
;;;
;;; BLOCK LEVEL OPERATIONS
;;;
(define (flmatrix-augment C . Cs)
; 1. Check that all have same number of rows.
(define-param (mc nc c ldc) C)
(define rows (map flmatrix-m (cons C Cs)))
(unless (andmap (λ (r) (= mc r)) rows)
(raise-arguments-error
'flmatrix-augment
"all arguments must have same number of rows"))
; 2. Find size for result matrix and allocate
(define m mc)
(define n (apply + (map flmatrix-n (cons C Cs))))
(define a (alloc-flmatrix m n))
(define lda m)
; 3. Fill in blocks
(define j 0)
(for ([B (in-list (cons C Cs))])
(define-param (mb nb b ldb) B)
(define aj (ptr-col a lda j))
(unsafe-matrix-copy! mb nb b ldb aj lda)
(set! j (+ j nb)))
(flmatrix m n a lda))
(define (flmatrix-stack C . Cs)