forked from AprilRobotics/apriltag
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matd.c
2026 lines (1612 loc) · 54.2 KB
/
matd.c
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
/* Copyright (C) 2013-2016, The Regents of The University of Michigan.
All rights reserved.
This software was developed in the APRIL Robotics Lab under the
direction of Edwin Olson, [email protected]. This software may be
available under alternative licensing terms; contact the address above.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the Regents of The University of Michigan.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <assert.h>
#include <math.h>
#include <float.h>
#include "common/math_util.h"
#include "common/svd22.h"
#include "common/matd.h"
#include "common/debug_print.h"
// a matd_t with rows=0 cols=0 is a SCALAR.
// to ease creating mati, matf, etc. in the future.
#define TYPE double
matd_t *matd_create(int rows, int cols)
{
assert(rows >= 0);
assert(cols >= 0);
if (rows == 0 || cols == 0)
return matd_create_scalar(0);
matd_t *m = calloc(1, sizeof(matd_t) + (rows*cols*sizeof(double)));
m->nrows = rows;
m->ncols = cols;
return m;
}
matd_t *matd_create_scalar(TYPE v)
{
matd_t *m = calloc(1, sizeof(matd_t) + sizeof(double));
m->nrows = 0;
m->ncols = 0;
m->data[0] = v;
return m;
}
matd_t *matd_create_data(int rows, int cols, const TYPE *data)
{
if (rows == 0 || cols == 0)
return matd_create_scalar(data[0]);
matd_t *m = matd_create(rows, cols);
for (int i = 0; i < rows * cols; i++)
m->data[i] = data[i];
return m;
}
matd_t *matd_create_dataf(int rows, int cols, const float *data)
{
if (rows == 0 || cols == 0)
return matd_create_scalar(data[0]);
matd_t *m = matd_create(rows, cols);
for (int i = 0; i < rows * cols; i++)
m->data[i] = (double)data[i];
return m;
}
matd_t *matd_identity(int dim)
{
if (dim == 0)
return matd_create_scalar(1);
matd_t *m = matd_create(dim, dim);
for (int i = 0; i < dim; i++)
MATD_EL(m, i, i) = 1;
return m;
}
// row and col are zero-based
TYPE matd_get(const matd_t *m, unsigned int row, unsigned int col)
{
assert(m != NULL);
assert(!matd_is_scalar(m));
assert(row < m->nrows);
assert(col < m->ncols);
return MATD_EL(m, row, col);
}
// row and col are zero-based
void matd_put(matd_t *m, unsigned int row, unsigned int col, TYPE value)
{
assert(m != NULL);
if (matd_is_scalar(m)) {
matd_put_scalar(m, value);
return;
}
assert(row < m->nrows);
assert(col < m->ncols);
MATD_EL(m, row, col) = value;
}
TYPE matd_get_scalar(const matd_t *m)
{
assert(m != NULL);
assert(matd_is_scalar(m));
return (m->data[0]);
}
void matd_put_scalar(matd_t *m, TYPE value)
{
assert(m != NULL);
assert(matd_is_scalar(m));
m->data[0] = value;
}
matd_t *matd_copy(const matd_t *m)
{
assert(m != NULL);
matd_t *x = matd_create(m->nrows, m->ncols);
if (matd_is_scalar(m))
x->data[0] = m->data[0];
else
memcpy(x->data, m->data, sizeof(TYPE)*m->ncols*m->nrows);
return x;
}
matd_t *matd_select(const matd_t * a, unsigned int r0, int r1, unsigned int c0, int c1)
{
assert(a != NULL);
assert(r0 < a->nrows);
assert(c0 < a->ncols);
int nrows = r1 - r0 + 1;
int ncols = c1 - c0 + 1;
matd_t * r = matd_create(nrows, ncols);
for (int row = r0; row <= r1; row++)
for (int col = c0; col <= c1; col++)
MATD_EL(r,row-r0,col-c0) = MATD_EL(a,row,col);
return r;
}
void matd_print(const matd_t *m, const char *fmt)
{
assert(m != NULL);
assert(fmt != NULL);
if (matd_is_scalar(m)) {
printf(fmt, MATD_EL(m, 0, 0));
printf("\n");
} else {
for (unsigned int i = 0; i < m->nrows; i++) {
for (unsigned int j = 0; j < m->ncols; j++) {
printf(fmt, MATD_EL(m, i, j));
}
printf("\n");
}
}
}
void matd_print_transpose(const matd_t *m, const char *fmt)
{
assert(m != NULL);
assert(fmt != NULL);
if (matd_is_scalar(m)) {
printf(fmt, MATD_EL(m, 0, 0));
printf("\n");
} else {
for (unsigned int j = 0; j < m->ncols; j++) {
for (unsigned int i = 0; i < m->nrows; i++) {
printf(fmt, MATD_EL(m, i, j));
}
printf("\n");
}
}
}
void matd_destroy(matd_t *m)
{
if (!m)
return;
assert(m != NULL);
free(m);
}
matd_t *matd_multiply(const matd_t *a, const matd_t *b)
{
assert(a != NULL);
assert(b != NULL);
if (matd_is_scalar(a))
return matd_scale(b, a->data[0]);
if (matd_is_scalar(b))
return matd_scale(a, b->data[0]);
assert(a->ncols == b->nrows);
matd_t *m = matd_create(a->nrows, b->ncols);
for (unsigned int i = 0; i < m->nrows; i++) {
for (unsigned int j = 0; j < m->ncols; j++) {
TYPE acc = 0;
for (unsigned int k = 0; k < a->ncols; k++) {
acc += MATD_EL(a, i, k) * MATD_EL(b, k, j);
}
MATD_EL(m, i, j) = acc;
}
}
return m;
}
matd_t *matd_scale(const matd_t *a, double s)
{
assert(a != NULL);
if (matd_is_scalar(a))
return matd_create_scalar(a->data[0] * s);
matd_t *m = matd_create(a->nrows, a->ncols);
for (unsigned int i = 0; i < m->nrows; i++) {
for (unsigned int j = 0; j < m->ncols; j++) {
MATD_EL(m, i, j) = s * MATD_EL(a, i, j);
}
}
return m;
}
void matd_scale_inplace(matd_t *a, double s)
{
assert(a != NULL);
if (matd_is_scalar(a)) {
a->data[0] *= s;
return;
}
for (unsigned int i = 0; i < a->nrows; i++) {
for (unsigned int j = 0; j < a->ncols; j++) {
MATD_EL(a, i, j) *= s;
}
}
}
matd_t *matd_add(const matd_t *a, const matd_t *b)
{
assert(a != NULL);
assert(b != NULL);
assert(a->nrows == b->nrows);
assert(a->ncols == b->ncols);
if (matd_is_scalar(a))
return matd_create_scalar(a->data[0] + b->data[0]);
matd_t *m = matd_create(a->nrows, a->ncols);
for (unsigned int i = 0; i < m->nrows; i++) {
for (unsigned int j = 0; j < m->ncols; j++) {
MATD_EL(m, i, j) = MATD_EL(a, i, j) + MATD_EL(b, i, j);
}
}
return m;
}
void matd_add_inplace(matd_t *a, const matd_t *b)
{
assert(a != NULL);
assert(b != NULL);
assert(a->nrows == b->nrows);
assert(a->ncols == b->ncols);
if (matd_is_scalar(a)) {
a->data[0] += b->data[0];
return;
}
for (unsigned int i = 0; i < a->nrows; i++) {
for (unsigned int j = 0; j < a->ncols; j++) {
MATD_EL(a, i, j) += MATD_EL(b, i, j);
}
}
}
matd_t *matd_subtract(const matd_t *a, const matd_t *b)
{
assert(a != NULL);
assert(b != NULL);
assert(a->nrows == b->nrows);
assert(a->ncols == b->ncols);
if (matd_is_scalar(a))
return matd_create_scalar(a->data[0] - b->data[0]);
matd_t *m = matd_create(a->nrows, a->ncols);
for (unsigned int i = 0; i < m->nrows; i++) {
for (unsigned int j = 0; j < m->ncols; j++) {
MATD_EL(m, i, j) = MATD_EL(a, i, j) - MATD_EL(b, i, j);
}
}
return m;
}
void matd_subtract_inplace(matd_t *a, const matd_t *b)
{
assert(a != NULL);
assert(b != NULL);
assert(a->nrows == b->nrows);
assert(a->ncols == b->ncols);
if (matd_is_scalar(a)) {
a->data[0] -= b->data[0];
return;
}
for (unsigned int i = 0; i < a->nrows; i++) {
for (unsigned int j = 0; j < a->ncols; j++) {
MATD_EL(a, i, j) -= MATD_EL(b, i, j);
}
}
}
matd_t *matd_transpose(const matd_t *a)
{
assert(a != NULL);
if (matd_is_scalar(a))
return matd_create_scalar(a->data[0]);
matd_t *m = matd_create(a->ncols, a->nrows);
for (unsigned int i = 0; i < a->nrows; i++) {
for (unsigned int j = 0; j < a->ncols; j++) {
MATD_EL(m, j, i) = MATD_EL(a, i, j);
}
}
return m;
}
static
double matd_det_general(const matd_t *a)
{
// Use LU decompositon to calculate the determinant
matd_plu_t *mlu = matd_plu(a);
matd_t *L = matd_plu_l(mlu);
matd_t *U = matd_plu_u(mlu);
// The determinants of the L and U matrices are the products of
// their respective diagonal elements
double detL = 1; double detU = 1;
for (unsigned int i = 0; i < a->nrows; i++) {
detL *= matd_get(L, i, i);
detU *= matd_get(U, i, i);
}
// The determinant of a can be calculated as
// epsilon*det(L)*det(U),
// where epsilon is just the sign of the corresponding permutation
// (which is +1 for an even number of permutations and is −1
// for an uneven number of permutations).
double det = mlu->pivsign * detL * detU;
// Cleanup
matd_plu_destroy(mlu);
matd_destroy(L);
matd_destroy(U);
return det;
}
double matd_det(const matd_t *a)
{
assert(a != NULL);
assert(a->nrows == a->ncols);
switch(a->nrows) {
case 0:
// scalar: invalid
assert(a->nrows > 0);
break;
case 1:
// 1x1 matrix
return a->data[0];
case 2:
// 2x2 matrix
return a->data[0] * a->data[3] - a->data[1] * a->data[2];
case 3:
// 3x3 matrix
return a->data[0]*a->data[4]*a->data[8]
- a->data[0]*a->data[5]*a->data[7]
+ a->data[1]*a->data[5]*a->data[6]
- a->data[1]*a->data[3]*a->data[8]
+ a->data[2]*a->data[3]*a->data[7]
- a->data[2]*a->data[4]*a->data[6];
case 4: {
// 4x4 matrix
double m00 = MATD_EL(a,0,0), m01 = MATD_EL(a,0,1), m02 = MATD_EL(a,0,2), m03 = MATD_EL(a,0,3);
double m10 = MATD_EL(a,1,0), m11 = MATD_EL(a,1,1), m12 = MATD_EL(a,1,2), m13 = MATD_EL(a,1,3);
double m20 = MATD_EL(a,2,0), m21 = MATD_EL(a,2,1), m22 = MATD_EL(a,2,2), m23 = MATD_EL(a,2,3);
double m30 = MATD_EL(a,3,0), m31 = MATD_EL(a,3,1), m32 = MATD_EL(a,3,2), m33 = MATD_EL(a,3,3);
return m00 * m11 * m22 * m33 - m00 * m11 * m23 * m32 -
m00 * m21 * m12 * m33 + m00 * m21 * m13 * m32 + m00 * m31 * m12 * m23 -
m00 * m31 * m13 * m22 - m10 * m01 * m22 * m33 +
m10 * m01 * m23 * m32 + m10 * m21 * m02 * m33 -
m10 * m21 * m03 * m32 - m10 * m31 * m02 * m23 +
m10 * m31 * m03 * m22 + m20 * m01 * m12 * m33 -
m20 * m01 * m13 * m32 - m20 * m11 * m02 * m33 +
m20 * m11 * m03 * m32 + m20 * m31 * m02 * m13 -
m20 * m31 * m03 * m12 - m30 * m01 * m12 * m23 +
m30 * m01 * m13 * m22 + m30 * m11 * m02 * m23 -
m30 * m11 * m03 * m22 - m30 * m21 * m02 * m13 +
m30 * m21 * m03 * m12;
}
default:
return matd_det_general(a);
}
assert(0);
return 0;
}
// returns NULL if the matrix is (exactly) singular. Caller is
// otherwise responsible for knowing how to cope with badly
// conditioned matrices.
matd_t *matd_inverse(const matd_t *x)
{
matd_t *m = NULL;
assert(x != NULL);
assert(x->nrows == x->ncols);
if (matd_is_scalar(x)) {
if (x->data[0] == 0)
return NULL;
return matd_create_scalar(1.0 / x->data[0]);
}
switch(x->nrows) {
case 1: {
double det = x->data[0];
if (det == 0)
return NULL;
double invdet = 1.0 / det;
m = matd_create(x->nrows, x->nrows);
MATD_EL(m, 0, 0) = 1.0 * invdet;
return m;
}
case 2: {
double det = x->data[0] * x->data[3] - x->data[1] * x->data[2];
if (det == 0)
return NULL;
double invdet = 1.0 / det;
m = matd_create(x->nrows, x->nrows);
MATD_EL(m, 0, 0) = MATD_EL(x, 1, 1) * invdet;
MATD_EL(m, 0, 1) = - MATD_EL(x, 0, 1) * invdet;
MATD_EL(m, 1, 0) = - MATD_EL(x, 1, 0) * invdet;
MATD_EL(m, 1, 1) = MATD_EL(x, 0, 0) * invdet;
return m;
}
default: {
matd_plu_t *plu = matd_plu(x);
matd_t *inv = NULL;
if (!plu->singular) {
matd_t *ident = matd_identity(x->nrows);
inv = matd_plu_solve(plu, ident);
matd_destroy(ident);
}
matd_plu_destroy(plu);
return inv;
}
}
return NULL; // unreachable
}
// TODO Optimization: Some operations we could perform in-place,
// saving some memory allocation work. E.g., ADD, SUBTRACT. Just need
// to make sure that we don't do an in-place modification on a matrix
// that was an input argument!
// handle right-associative operators, greedily consuming them. These
// include transpose and inverse. This is called by the main recursion
// method.
static inline matd_t *matd_op_gobble_right(const char *expr, int *pos, matd_t *acc, matd_t **garb, int *garbpos)
{
while (expr[*pos] != 0) {
switch (expr[*pos]) {
case '\'': {
assert(acc != NULL); // either a syntax error or a math op failed, producing null
matd_t *res = matd_transpose(acc);
garb[*garbpos] = res;
(*garbpos)++;
acc = res;
(*pos)++;
break;
}
// handle inverse ^-1. No other exponents are allowed.
case '^': {
assert(acc != NULL);
assert(expr[*pos+1] == '-');
assert(expr[*pos+2] == '1');
matd_t *res = matd_inverse(acc);
garb[*garbpos] = res;
(*garbpos)++;
acc = res;
(*pos)+=3;
break;
}
default:
return acc;
}
}
return acc;
}
// @garb, garbpos A list of every matrix allocated during evaluation... used to assist cleanup.
// @oneterm: we should return at the end of this term (i.e., stop at a PLUS, MINUS, LPAREN).
static matd_t *matd_op_recurse(const char *expr, int *pos, matd_t *acc, matd_t **args, int *argpos,
matd_t **garb, int *garbpos, int oneterm)
{
while (expr[*pos] != 0) {
switch (expr[*pos]) {
case '(': {
if (oneterm && acc != NULL)
return acc;
(*pos)++;
matd_t *rhs = matd_op_recurse(expr, pos, NULL, args, argpos, garb, garbpos, 0);
rhs = matd_op_gobble_right(expr, pos, rhs, garb, garbpos);
if (acc == NULL) {
acc = rhs;
} else {
matd_t *res = matd_multiply(acc, rhs);
garb[*garbpos] = res;
(*garbpos)++;
acc = res;
}
break;
}
case ')': {
if (oneterm)
return acc;
(*pos)++;
return acc;
}
case '*': {
(*pos)++;
matd_t *rhs = matd_op_recurse(expr, pos, NULL, args, argpos, garb, garbpos, 1);
rhs = matd_op_gobble_right(expr, pos, rhs, garb, garbpos);
if (acc == NULL) {
acc = rhs;
} else {
matd_t *res = matd_multiply(acc, rhs);
garb[*garbpos] = res;
(*garbpos)++;
acc = res;
}
break;
}
case 'F': {
matd_t *rhs = args[*argpos];
garb[*garbpos] = rhs;
(*garbpos)++;
(*pos)++;
(*argpos)++;
rhs = matd_op_gobble_right(expr, pos, rhs, garb, garbpos);
if (acc == NULL) {
acc = rhs;
} else {
matd_t *res = matd_multiply(acc, rhs);
garb[*garbpos] = res;
(*garbpos)++;
acc = res;
}
break;
}
case 'M': {
matd_t *rhs = args[*argpos];
(*pos)++;
(*argpos)++;
rhs = matd_op_gobble_right(expr, pos, rhs, garb, garbpos);
if (acc == NULL) {
acc = rhs;
} else {
matd_t *res = matd_multiply(acc, rhs);
garb[*garbpos] = res;
(*garbpos)++;
acc = res;
}
break;
}
/*
case 'D': {
int rows = expr[*pos+1]-'0';
int cols = expr[*pos+2]-'0';
matd_t *rhs = matd_create(rows, cols);
break;
}
*/
// a constant (SCALAR) defined inline. Treat just like M, creating a matd_t on the fly.
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.': {
const char *start = &expr[*pos];
char *end;
double s = strtod(start, &end);
(*pos) += (end - start);
matd_t *rhs = matd_create_scalar(s);
garb[*garbpos] = rhs;
(*garbpos)++;
rhs = matd_op_gobble_right(expr, pos, rhs, garb, garbpos);
if (acc == NULL) {
acc = rhs;
} else {
matd_t *res = matd_multiply(acc, rhs);
garb[*garbpos] = res;
(*garbpos)++;
acc = res;
}
break;
}
case '+': {
if (oneterm && acc != NULL)
return acc;
// don't support unary plus
assert(acc != NULL);
(*pos)++;
matd_t *rhs = matd_op_recurse(expr, pos, NULL, args, argpos, garb, garbpos, 1);
rhs = matd_op_gobble_right(expr, pos, rhs, garb, garbpos);
matd_t *res = matd_add(acc, rhs);
garb[*garbpos] = res;
(*garbpos)++;
acc = res;
break;
}
case '-': {
if (oneterm && acc != NULL)
return acc;
if (acc == NULL) {
// unary minus
(*pos)++;
matd_t *rhs = matd_op_recurse(expr, pos, NULL, args, argpos, garb, garbpos, 1);
rhs = matd_op_gobble_right(expr, pos, rhs, garb, garbpos);
matd_t *res = matd_scale(rhs, -1);
garb[*garbpos] = res;
(*garbpos)++;
acc = res;
} else {
// subtract
(*pos)++;
matd_t *rhs = matd_op_recurse(expr, pos, NULL, args, argpos, garb, garbpos, 1);
rhs = matd_op_gobble_right(expr, pos, rhs, garb, garbpos);
matd_t *res = matd_subtract(acc, rhs);
garb[*garbpos] = res;
(*garbpos)++;
acc = res;
}
break;
}
case ' ': {
// nothing to do. spaces are meaningless.
(*pos)++;
break;
}
default: {
debug_print("Unknown character: '%c'\n", expr[*pos]);
assert(expr[*pos] != expr[*pos]);
}
}
}
return acc;
}
// always returns a new matrix.
matd_t *matd_op(const char *expr, ...)
{
int nargs = 0;
int exprlen = 0;
assert(expr != NULL);
for (const char *p = expr; *p != 0; p++) {
if (*p == 'M' || *p == 'F')
nargs++;
exprlen++;
}
assert(nargs > 0);
if (!exprlen) // expr = ""
return NULL;
va_list ap;
va_start(ap, expr);
matd_t **args = malloc(sizeof(matd_t*)*nargs);
for (int i = 0; i < nargs; i++) {
args[i] = va_arg(ap, matd_t*);
// XXX: sanity check argument; emit warning/error if args[i]
// doesn't look like a matd_t*.
}
va_end(ap);
int pos = 0;
int argpos = 0;
int garbpos = 0;
// can't create more than 2 new result per character
// one result, and possibly one argument to free
matd_t **garb = malloc(sizeof(matd_t*)*2*exprlen);
matd_t *res = matd_op_recurse(expr, &pos, NULL, args, &argpos, garb, &garbpos, 0);
free(args);
// 'res' may need to be freed as part of garbage collection (i.e. expr = "F")
matd_t *res_copy = (res ? matd_copy(res) : NULL);
for (int i = 0; i < garbpos; i++) {
matd_destroy(garb[i]);
}
free(garb);
return res_copy;
}
double matd_vec_mag(const matd_t *a)
{
assert(a != NULL);
assert(matd_is_vector(a));
double mag = 0.0;
int len = a->nrows*a->ncols;
for (int i = 0; i < len; i++)
mag += sq(a->data[i]);
return sqrt(mag);
}
double matd_vec_dist(const matd_t *a, const matd_t *b)
{
assert(a != NULL);
assert(b != NULL);
assert(matd_is_vector(a) && matd_is_vector(b));
assert(a->nrows*a->ncols == b->nrows*b->ncols);
int lena = a->nrows*a->ncols;
return matd_vec_dist_n(a, b, lena);
}
double matd_vec_dist_n(const matd_t *a, const matd_t *b, int n)
{
assert(a != NULL);
assert(b != NULL);
assert(matd_is_vector(a) && matd_is_vector(b));
int lena = a->nrows*a->ncols;
int lenb = b->nrows*b->ncols;
assert(n <= lena && n <= lenb);
(void)lena;
(void)lenb;
double mag = 0.0;
for (int i = 0; i < n; i++)
mag += sq(a->data[i] - b->data[i]);
return sqrt(mag);
}
// find the index of the off-diagonal element with the largest mag
static inline int max_idx(const matd_t *A, int row, int maxcol)
{
int maxi = 0;
double maxv = -1;
for (int i = 0; i < maxcol; i++) {
if (i == row)
continue;
double v = fabs(MATD_EL(A, row, i));
if (v > maxv) {
maxi = i;
maxv = v;
}
}
return maxi;
}
double matd_vec_dot_product(const matd_t *a, const matd_t *b)
{
assert(a != NULL);
assert(b != NULL);
assert(matd_is_vector(a) && matd_is_vector(b));
int adim = a->ncols*a->nrows;
int bdim = b->ncols*b->nrows;
assert(adim == bdim);
(void)bdim;
double acc = 0;
for (int i = 0; i < adim; i++) {
acc += a->data[i] * b->data[i];
}
return acc;
}
matd_t *matd_vec_normalize(const matd_t *a)
{
assert(a != NULL);
assert(matd_is_vector(a));
double mag = matd_vec_mag(a);
assert(mag > 0);
matd_t *b = matd_create(a->nrows, a->ncols);
int len = a->nrows*a->ncols;
for(int i = 0; i < len; i++)
b->data[i] = a->data[i] / mag;
return b;
}
matd_t *matd_crossproduct(const matd_t *a, const matd_t *b)
{ // only defined for vecs (col or row) of length 3
assert(a != NULL);
assert(b != NULL);
assert(matd_is_vector_len(a, 3) && matd_is_vector_len(b, 3));
matd_t * r = matd_create(a->nrows, a->ncols);
r->data[0] = a->data[1] * b->data[2] - a->data[2] * b->data[1];
r->data[1] = a->data[2] * b->data[0] - a->data[0] * b->data[2];
r->data[2] = a->data[0] * b->data[1] - a->data[1] * b->data[0];
return r;
}
TYPE matd_err_inf(const matd_t *a, const matd_t *b)
{
assert(a->nrows == b->nrows);
assert(a->ncols == b->ncols);
TYPE maxf = 0;
for (unsigned int i = 0; i < a->nrows; i++) {
for (unsigned int j = 0; j < a->ncols; j++) {
TYPE av = MATD_EL(a, i, j);
TYPE bv = MATD_EL(b, i, j);
TYPE err = fabs(av - bv);
maxf = fmax(maxf, err);
}
}
return maxf;
}
// Computes an SVD for square or tall matrices. This code doesn't work
// for wide matrices, because the bidiagonalization results in one
// non-zero element too far to the right for us to rotate away.
//
// Caller is responsible for destroying U, S, and V.
static matd_svd_t matd_svd_tall(matd_t *A, int flags)
{
matd_t *B = matd_copy(A);
// Apply householder reflections on each side to reduce A to
// bidiagonal form. Specifically:
//
// A = LS*B*RS'
//
// Where B is bidiagonal, and LS/RS are unitary.
//
// Why are we doing this? Some sort of transformation is necessary
// to reduce the matrix's nz elements to a square region. QR could
// work too. We need nzs confined to a square region so that the
// subsequent iterative process, which is based on rotations, can
// work. (To zero out a term at (i,j), our rotations will also
// affect (j,i).
//
// We prefer bidiagonalization over QR because it gets us "closer"
// to the SVD, which should mean fewer iterations.
// LS: cumulative left-handed transformations
matd_t *LS = matd_identity(A->nrows);