-
Notifications
You must be signed in to change notification settings - Fork 4
/
flomat.rkt
3667 lines (3186 loc) · 117 KB
/
flomat.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
;;; * Implement block. Handle mix between numbers and matrices.
;;; * Improve matrix-expt! (avoid allocation)
;;; * schur decomposition
;;; * sqrtm See Higham paper.
;;; * logm
;;; 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 Catalina (Working)
;;;
;;; IDEAS
;;; Potential Improvements
;;; * DONE Unsafe operations
;;; * DONE add lda to the flomat 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 flomat-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
racket/syntax))
;;;
;;; LIBRARIES
;;;
; CBLAS and LAPACK are used.
; The first two are C-based whereas LAPACK is Fortran based.
; Note: Use trailing _ in names exported by LAPACK (in order to work both on macOS and Linux).
;; 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)
; Note: The library names are different on Debian, Ubuntu and Arch.
(define uname (string-downcase (system-type 'machine)))
(define dist (cond [(regexp-match "arch" uname) 'arch]
[(regexp-match "debian" uname) 'debian]
[(regexp-match "ubuntu" uname) 'ubuntu]
[(regexp-match #px"fc\\d\\d" uname) 'fedora]
[(regexp-match #px"raspberrypi" uname) 'rp400] ; raspberry pi
[(regexp-match #px"rp400" uname) 'rp400] ; raspberry pi
[else 'other]))
; The lib order is important here.
; Since cblas depends on gfortran, gfortran needs to come first.
(define gfortran-lib (ffi-lib "libgfortran" '("5" "3" #f)))
(define quadmath-lib (case dist
[(rp400) #f]
[else (ffi-lib "libquadmath" '("0" #f))]))
(define cblas-lib (case dist
[(debian) (ffi-lib "libblas" '("3" #f))]
[(arch) (ffi-lib "libcblas" '("3" #f))]
[(ubuntu) (ffi-lib "libblas" '("3" #f))]
[(fedora) (ffi-lib "libcblas" '("3" #f))]
[(rp400) (ffi-lib "libblas" '("3" #f))]
[(other) (ffi-lib "libblas" '("3" #f))]))
(define lapack-lib (ffi-lib "liblapack" '("3" #f)))
(values cblas-lib lapack-lib)]
[(windows) ; Windows 10
(define (use-openblas)
(define cblas-lib (ffi-lib "libopenblas.dll"))
(define lapack-lib #f)
(values cblas-lib lapack-lib))
; If RACKET_SCI_USE_OPENBLAS is set, we don't look for the standard names.
(case (getenv "RACKET_SCI_USE_OPENBLAS")
[(#f) (with-handlers ([exn:fail:filesystem?
; the standard names weren't found, try openblas
(λ (x) (use-openblas))])
(define cblas-lib (ffi-lib "libblas.dll")) ; place them in PATH
(define lapack-lib (ffi-lib "liblapack.dll"))
(values cblas-lib lapack-lib))]
[else (use-openblas)])]))
;;; 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
; On macOS the header files are here:
; /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/
; Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/
; Versions/A/Headers/clapack.h
;;;
;;; CONFIGURATION
;;;
(define epsilon 1e-13)
; If two flomats 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 epsilon flomat-zero?
; returns true.
(define current-max-flomat-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 _flomat (_cpointer 'flomat))
; 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 (flomat-print A port mode)
(define print (if mode write display))
(print
(if (< (flomat-size A) (current-max-flomat-print-size))
; constructor style printing:
(list 'flomat: ; (flomat-m A) (flomat-n A)
(flomat->lists A))
; omit actual elements
(list 'flomat (flomat-m A) (flomat-n A)
"..."))
port))
(define (flomat= A B [eps #f])
; TODO: Use (< (norm1 (.- A B)) eps)
(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<= (flabs (fl- aij bij)) eps)
(fl= aij bij)))))
; m = rows, n = cols, a = mxn array of doubles
; lda = leading dimension of a (see below)
(struct flomat (m n a lda)
#:methods gen:custom-write
[(define write-proc flomat-print)]
#:methods gen:equal+hash
[(define equal-proc
(λ (A B rec)
(and (= (flomat-m A) (flomat-m B))
(= (flomat-n A) (flomat-n B))
(or (equal? (flomat-a A) (flomat-a B))
(flomat= A B epsilon)))))
(define hash-proc
; TODO: Avoid allocation in hash-proc.
(λ (A rec)
(define-param (m n) A)
(rec (cons m (cons n (flomat->vector A))))))
(define hash2-proc
(λ (A rec)
(define-param (m n) A)
(rec (cons n (cons m (flomat->vector A))))))])
; convenient destructuring
(define-syntax (define-param stx)
(syntax-case stx ()
[(_ (m n) A)
#'(begin
(define A1 A)
(define m (flomat-m A1))
(define n (flomat-n A1)))]
[(_ (m n a) A)
#'(begin
(define A1 A)
(define m (flomat-m A1))
(define n (flomat-n A1))
(define a (flomat-a A1)))]
[(_ (m n a lda) A)
#'(begin
(define A1 A)
(define m (flomat-m A1))
(define n (flomat-n A1))
(define a (flomat-a A1))
(define lda (flomat-lda A1)))]
[_
(syntax/loc stx (error "Wrong number of arguments"))]))
;;;
;;; 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)
(flomat 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-flomat (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-flomat who A)
(unless (flomat? A)
(raise-type-error who "expected flomat" A)))
(define (check-same-dimensions A B who)
(unless (flomat-same-dimensions? A B)
(raise-argument-error who "expected two matrices of the same size" A B)))
(define (check-all-matrices-same-size who AS)
(set! AS (filter flomat? AS))
(when (not( empty? AS))
(unless (and (apply = (map flomat-m AS))
(apply = (map flomat-n AS)))
(raise-argument-error
who
"All input matrices are expected to have the same dimensions."
AS))))
(define (check-product-dimensions who A B [C #f] [transA #f] [transB #f])
(define-values (ma na) (flomat-dimensions A))
(define-values (mb nb) (flomat-dimensions B))
(when transA (set!-values (ma na) (values na ma)))
(when transB (set!-values (mb nb) (values nb mb)))
(unless (if (not C)
(= na mb)
(and (= na mb)
(= ma (flomat-m C))
(= nb (flomat-n C))))
(raise-argument-error
who
(if C
"expected three matrices with compatible dimensions"
"expected two matrices with compatible dimensions")
(list (map (λ (A) (flomat-dimensions A #t)) (list A B C)) (list A B C)))))
(define (check-matrix-vector-product-dimensions who A X Y transpose-A)
; ma x na * mx x nx = ma x nx
(define-param (ma na) A)
(define-param (mx nx) X)
(define-param (my ny) Y)
(when transpose-A (set!-values (ma na) (values na ma)))
(unless (= ny nx 1)
(raise-argument-error
who "expected two column vectors, got: "
(list (list mx nx) (list my ny))))
(unless (= na mx)
(raise-argument-error
who "expected same number of columns in matrix as there are columns in X"
(list (list ma na) (list mx nx) (list 'transpose-A transpose-A)))))
(define (check-legal-column who j A)
(unless (< j (flomat-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 (flomat-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)))
(define (check-vector who v)
(unless (vector? v) (raise-argument-error who "vector expected" v)))
(define (check-integer who x)
(unless (integer? x) (raise-argument-error who "integer expected" x)))
(define (check-positive-integer who x)
(unless (and (integer? x) (>= x 0))
(raise-argument-error who "positive integer epected" x)))
;;;
;;; SIZE and DIMENSION
;;;
(define (flomat-size A)
(check-flomat 'flomat-size A )
(define-param (m n) A)
(* m n))
(define (flomat-dimensions A [as-list? #f])
(check-flomat 'flomat-dimensions A)
(define-param (m n) A)
(if as-list?
(list m n)
(values m n)))
(define (flomat-same-dimensions? A B)
(define-param (ma na) A)
(define-param (mb nb) B)
(and (= ma mb) (= na nb)))
(define (flomat-row-vector? A)
(= 1 (flomat-m A)))
(define (flomat-column-vector? A)
(= 1 (flomat-n A)))
;;;
;;; ALLOCATIONS and CONSTRUCTORS
;;;
(define (alloc-flomat m n)
(if (or (= m 0) (= n 0))
#f ; ~ NULL
(cast (malloc (* m n) _double 'atomic)
_pointer _flomat)))
; Note: Even though we use ptr-add we do not need to use 'atomic-interior
; since the result of ptr-add contains both the base pointer and an offset.
(define (alloc-same-size-matrix A)
(define-param (m n) A)
(alloc-flomat 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 ...))
...)))]))
;; Note: BLAS expects complex numbers to be passed as two doubles,
; so _complex aren't per se missing from the FFI.
; https://stackoverflow.com/questions/34103818/swift-blas-cblas-cgemv-complex-numbers
; For now this library sticks with doubles.
(define-cblas* cblas_xcopy _x (s d c z) ; dcopy
; copy n elements from vector X to vector Y
(_fun (n : _int)
(X : _flomat) (incX : _int)
(Y : _flomat) (incY : _int)
-> _void))
#;(define-cblas cblas_dcopy
; copy n elements from vector X to vector Y
(_fun (n : _int)
(X : _flomat) (incX : _int)
(Y : _flomat) (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)
; Todo: The for loop currently copies each column.
; If the rows are longer than columns then it would be
; faster to copy each row.
; 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-flomat A)
(define-param (m n a lda) A)
(define size (* m n))
(define b (cast (malloc size _double 'atomic)
_pointer _flomat))
(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)])
(flomat m n b ldb))
;; (define (make-flomat m n [x 0.0])
;; (define a (alloc-flomat 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*)))
;; (flomat m n a m))
(define (make-flomat m n [x 0.0])
(define a (alloc-flomat m n))
(define x* (cast (malloc 1 _double 'atomic) _pointer _flomat))
(ptr-set! x* _double (real->double-flonum x))
(if (= x 0.0)
(memset a 0 (* m n) _double)
(cblas_dcopy (* m n) x* 0 a 1))
(flomat m n a m))
(define (flomat-zeros m n)
(make-flomat m n 0.0))
(define (flomat-ones m n)
(make-flomat m n 1.0))
(define (list->flomat xss)
(define m (length xss))
(define n (apply max (map length xss)))
(for*/flomat m n
([xs (in-list xss)]
[x (in-list xs)])
x))
(define (vectors->flomat xss)
(define m (vector-length xss))
(define n (vector-length (vector-ref xss 0)))
(for*/flomat m n
([xs (in-vector xss)]
[x (in-vector xs)])
x))
(define (flomat-identity m)
(define A (make-flomat m m 0.0))
(for ([i (in-range m)])
(flomat-set! A i i 1.0))
A)
(define (flomat-column A j)
; copy column j
(check-legal-column 'flomat-column j A)
(define-param (m n) A)
(copy-flomat (shared-submatrix! A 0 j m 1)))
(define (flomat-row A i)
; copy row i
(define-param (m n) A)
(check-legal-row 'flomat-row i A)
(copy-flomat (shared-submatrix! A i 0 1 n)))
;;;
;;; CONVERSIONS MATRIX <-> VECTOR
;;;
(define (flomat->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 (flomat->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 a _double (+ i (* j lda)))
#;(ptr-ref (ptr-elm a lda i j) _double))))
(define (vector->flomat m n v)
(unless (= (* m n) (vector-length v))
(raise-argument-error
'vector->flomat
"expected m*n to be the same as the length of the vector"))
(define a (alloc-flomat 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)))
(flomat m n a m))
; (: matrix/dim : Integer Integer Number * -> (Matrix Number))
; construct a mxn flomat with elements from the values xs
; the length of xs must be m*n
(define (flomat/dim m n . xs)
(vector->flomat m n (list->vector xs)))
;;;
;;; COMPREHENSIONS
;;;
; (for/flomat m n (clause ...) . defs+exprs)
; (for/matrix (i in m) (j in n) (clauses ...) . body)
; Return an m x n flomat 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/flomat stx)
(syntax-case stx (in)
[(_for/matrix (i in m-expr) (j in n-expr) #:column (clause ...) . defs+exprs)
(syntax/loc stx
(let ([m m-expr] [n n-expr])
(define a (alloc-flomat m n))
(define idx 0)
(for* ([j (in-range n)]
[i (in-range m)]
clause ...)
(define x (let () . defs+exprs))
(ptr-set! a _double* idx x)
(set! idx (+ idx 1)))
(flomat m n a m)))]
; elements in column 0 are generated first, then column 1, ...
[(_ m-expr n-expr #:column (clause ...) . defs+exprs)
(syntax/loc stx
(let ([m m-expr] [n n-expr])
(define a (alloc-flomat m n))
(define size (* m n))
(for ([idx (in-range size)] clause ...)
(define x (let () . defs+exprs))
(ptr-set! a _double* idx x))
(flomat m n a m)))]
[(_for/matrix (i in m-expr) (j in n-expr) (clause ...) . defs+exprs)
(syntax/loc stx
(let ([m m-expr] [n n-expr])
(define size (* m n))
(define a (alloc-flomat m n))
(define idx 0)
(for* ([i (in-range m)]
[j (in-range n)]
clause ...)
(define x (let () . defs+exprs))
(ptr-set! a _double* idx x)
(set! idx (+ idx m))
(when (>= idx size)
(set! idx (+ idx 1 (- size)))))
(flomat m n a m)))]
; 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 a (alloc-flomat m n))
(define idx 0)
(define size (* m n))
(for ([k (in-range size)] clause ...)
(define x (let () . defs+exprs))
(ptr-set! a _double* idx x)
(set! idx (+ idx m))
(when (>= idx size)
(set! idx (+ idx 1 (- size)))))
(flomat m n a m)))]))
; (for*/flomat m n (clause ...) . defs+exprs)
; Return an m x n flomat 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*/flomat m n #:column (clause ...) . defs+exprs)
; Return an m x n flomat 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*/flomat stx)
(syntax-case stx ()
[(_ m-expr n-expr #:column (clause ...) . defs+exprs)
(syntax/loc stx
(let* ([m m-expr] [n n-expr])
(define a (alloc-flomat m n))
(define idx 0)
(define size (* m n))
(for* (clause ... #:break (= idx size))
(define x (let () . defs+exprs))
(ptr-set! a _double* idx x)
(set! idx (+ idx 1)))
(flomat m n a m)))]
[(_ m-expr n-expr (clause ...) . defs+exprs)
(syntax/loc stx
(let ([m m-expr] [n n-expr])
(define a (alloc-flomat m n))
(define idx 0)
(define size (* m n))
(for* (clause ... #:final (= idx (- size 1)))
(define x (let () . defs+exprs))
(ptr-set! a _double* idx x)
(set! idx (+ idx m))
(when (>= idx size)
(set! idx (+ idx 1 (- size)))))
(flomat m n a m)))]))
(define-syntax (for/flomat-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 (flomat+ 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 : _flomat) (incX : _int)
(Y : _flomat) (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 : _flomat) (incX : _int)
(Y : _flomat) (incY : _int)
-> _void))
;; This does not work if there are NaN entries.
;; Use memset with 0 instead. See block-diagonal as an example.
;; (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 (flomat-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 (flomat-add-scaled-row A i1 s i2)
(define B (copy-flomat A))
(flomat-add-scaled-row! B i1 s i2)
B)
(define (flomat-add-scaled-column! A j1 s j2)
(check-legal-row 'flomat-add-scaled-column! j1 A)
(check-legal-row 'flomat-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 (flomat-add-scaled-column A i1 s i2)
(define B (copy-flomat A))
(flomat-add-scaled-column! B i1 s i2)
B)
(define (constant*flomat+flomat! 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*flomat+flomat alpha A B)
; αA+B
(define αA+B (copy-flomat B))
(constant*flomat+flomat! alpha A αA+B)
αA+B)
(define (flomat+! A B)
; B := A + B
(check-same-dimensions A B 'flomat+!)
(constant*flomat+flomat! 1.0 A B))
(define (flomat+ A B)
; A + B
(check-same-dimensions A B 'flomat+)
(constant*flomat+flomat 1.0 A B))
(define (flomat-! A B)
; A := A - B
(check-same-dimensions A B 'flomat-!)
(constant*flomat+flomat! -1.0 B A))
(define (flomat- A [B #f])
(cond
[B
(check-same-dimensions A B 'flomat-)
(constant*flomat+flomat -1.0 B A)]
[else
(flomat-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 : _flomat)
(lda : _int) ; size of first dim of A
(B : _flomat)
(ldb : _int) ; size of first dim of B
(beta : _double) ; scaling for C
(C : _flomat)
(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
; Note: the check fails when the matrices are transposed.
; todo: pass transA and transB to the checker.
(check-product-dimensions 'constant*matrix*matrix+constant*matrix!
A B C transA transB)
(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)
(if transA n m) ; rows in A
(if transB r s) ; cols in B
(if transA m n) ; cols in A
alpha*
a lda b ldb beta* c ldc)
C)
(define (flomat*! 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 (flomat* 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-values (ma na) (flomat-dimensions A))
(define-values (mb nb) (flomat-dimensions B))
(when transpose-A (set!-values (ma na) (values na ma)))
(when transpose-B (set!-values (mb nb) (values nb mb)))
(define C1 (or C (make-flomat ma nb)))
(flomat*! A B C1 alpha beta transpose-A transpose-B))
;;; Matrix Power
(define (flomat-expt a n)
(check-flomat 'flomat-expt a)
(check-square 'matrix-expt a)
(cond
[(= n 0) (flomat-identity (flomat-m a))]
[(= n 1) (copy-flomat a)]
[(= n 2) (flomat* a a)]
[(even? n) (let ([a^n/2 (flomat-expt a (quotient n 2))])
(flomat* a^n/2 a^n/2))]
[else (flomat* a (flomat-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 : _flomat)
(lda : _int)
(X : _flomat) ; vector
(ldx : _int)
(beta : _x) ; scaling for Y
(Y : _flomat) ; 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
(flomat-a X) 1
(real->double-flonum beta)
(flomat-a Y) 1)
Y)
(define (flomat*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 transpose-A)
; Y := α(AX) +(βY), maybe transpose A first
(constant*matrix*vector+constant*vector!
alpha A X1 beta Y1 transpose-A))
(define (flomat*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-flomat (if transpose-A (flomat-n A) (flomat-m A)) 1 0.0)))
(flomat*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 (flomat-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!