forked from translunar/nmatrix
/
yale.cpp
1697 lines (1279 loc) · 48.9 KB
/
yale.cpp
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
/////////////////////////////////////////////////////////////////////
// = NMatrix
//
// A linear algebra library for scientific computation in Ruby.
// NMatrix is part of SciRuby.
//
// NMatrix was originally inspired by and derived from NArray, by
// Masahiro Tanaka: http://narray.rubyforge.org
//
// == Copyright Information
//
// SciRuby is Copyright (c) 2010 - 2012, Ruby Science Foundation
// NMatrix is Copyright (c) 2012, Ruby Science Foundation
//
// Please see LICENSE.txt for additional copyright notices.
//
// == Contributing
//
// By contributing source code to SciRuby, you agree to be bound by
// our Contributor Agreement:
//
// * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement
//
// == yale.c
//
// "new yale" storage format for 2D matrices (like yale, but with
// the diagonal pulled out for O(1) access).
//
// Specifications:
// * dtype and index dtype must necessarily differ
// * index dtype is defined by whatever unsigned type can store
// max(rows,cols)
// * that means vector ija stores only index dtype, but a stores
// dtype
// * vectors must be able to grow as necessary
// * maximum size is rows*cols+1
/*
* Standard Includes
*/
#include <ruby.h>
#include <algorithm> // std::min
#include <cstdio> // std::fprintf
/*
* Project Includes
*/
// #include "types.h"
#include "util/math.h"
#include "data/data.h"
#include "common.h"
#include "yale.h"
#include "nmatrix.h"
#include "ruby_constants.h"
/*
* Macros
*/
#ifndef NM_MAX
#define NM_MAX(a,b) (((a)>(b))?(a):(b))
#define NM_MIN(a,b) (((a)<(b))?(a):(b))
#endif
/*
* Forward Declarations
*/
extern "C" {
static YALE_STORAGE* nm_copy_alloc_struct(const YALE_STORAGE* rhs, const nm::dtype_t new_dtype, const size_t new_capacity, const size_t new_size);
static YALE_STORAGE* alloc(nm::dtype_t dtype, size_t* shape, size_t dim);
/* Ruby-accessible functions */
static VALUE nm_size(VALUE self);
static VALUE nm_a(VALUE self);
static VALUE nm_d(VALUE self);
static VALUE nm_lu(VALUE self);
static VALUE nm_ia(VALUE self);
static VALUE nm_ja(VALUE self);
static VALUE nm_ija(VALUE self);
} // end extern "C" block
namespace nm { namespace yale_storage {
template <typename DType, typename IType>
static bool ndrow_is_empty(const YALE_STORAGE* s, IType ija, const IType ija_next);
template <typename LDType, typename RDType, typename IType>
static bool ndrow_eqeq_ndrow(const YALE_STORAGE* l, const YALE_STORAGE* r, IType l_ija, const IType l_ija_next, IType r_ija, const IType r_ija_next);
template <typename LDType, typename RDType, typename IType>
static bool eqeq(const YALE_STORAGE* left, const YALE_STORAGE* right);
template <typename IType>
static YALE_STORAGE* copy_alloc_struct(const YALE_STORAGE* rhs, const dtype_t new_dtype, const size_t new_capacity, const size_t new_size);
template <typename IType>
static void increment_ia_after(YALE_STORAGE* s, IType ija_size, IType i, IType n);
template <typename IType>
static IType insert_search(YALE_STORAGE* s, IType left, IType right, IType key, bool* found);
template <typename DType, typename IType>
static char vector_insert(YALE_STORAGE* s, size_t pos, size_t* j, DType* val, size_t n, bool struct_only);
template <typename DType, typename IType>
static char vector_insert_resize(YALE_STORAGE* s, size_t current_size, size_t pos, size_t* j, size_t n, bool struct_only);
template <typename nm::ewop_t op, typename IType, typename DType>
YALE_STORAGE* ew_op(const YALE_STORAGE* left, const YALE_STORAGE* right, dtype_t dtype);
/*
* Functions
*/
/*
* Create Yale storage from IA, JA, and A vectors given in Old Yale format (probably from a file, since NMatrix only uses
* new Yale for its storage).
*
* This function is needed for Matlab .MAT v5 IO.
*/
template <typename LDType, typename RDType, typename IType>
YALE_STORAGE* create_from_old_yale(dtype_t dtype, size_t* shape, void* r_ia, void* r_ja, void* r_a) {
IType* ir = reinterpret_cast<IType*>(r_ia);
IType* jr = reinterpret_cast<IType*>(r_ja);
RDType* ar = reinterpret_cast<RDType*>(r_a);
// Read through ia and ja and figure out the ndnz (non-diagonal non-zeros) count.
size_t ndnz = 0, i, p, p_next;
for (i = 0; i < shape[0]; ++i) { // Walk down rows
for (p = ir[i], p_next = ir[i+1]; p < p_next; ++p) { // Now walk through columns
if (i != jr[p]) ++ndnz; // entry is non-diagonal and probably nonzero
}
}
// Having walked through the matrix, we now go about allocating the space for it.
YALE_STORAGE* s = alloc(dtype, shape, 2);
s->capacity = shape[0] + ndnz + 1;
s->ndnz = ndnz;
// Setup IJA and A arrays
s->ija = ALLOC_N( IType, s->capacity );
s->a = ALLOC_N( LDType, s->capacity );
IType* ijl = reinterpret_cast<IType*>(s->ija);
LDType* al = reinterpret_cast<LDType*>(s->a);
// set the diagonal to zero -- this prevents uninitialized values from popping up.
for (size_t index = 0; index < shape[0]; ++index) {
al[index] = 0;
}
// Figure out where to start writing JA in IJA:
size_t pp = s->shape[0]+1;
// Find beginning of first row
p = ir[0];
// Now fill the arrays
for (i = 0; i < s->shape[0]; ++i) {
// Set the beginning of the row (of output)
ijl[i] = pp;
// Now walk through columns, starting at end of row (of input)
for (size_t p_next = ir[i+1]; p < p_next; ++p, ++pp) {
if (i == jr[p]) { // diagonal
al[i] = ar[p];
--pp;
} else { // nondiagonal
ijl[pp] = jr[p];
al[pp] = ar[p];
}
}
}
ijl[i] = pp; // Set the end of the last row
// Set the zero position for our output matrix
al[i] = 0;
return s;
}
/*
* Take two Yale storages and merge them into a new Yale storage.
*
* Uses the left as a template for the creation of a new one.
*/
template <typename DType, typename IType>
YALE_STORAGE* create_merged(const YALE_STORAGE* left, const YALE_STORAGE* right) {
char ins_type;
size_t size = get_size<IType>(left);
// s represents the resulting storage
YALE_STORAGE* s = copy_alloc_struct<IType>(left, left->dtype, NM_MAX(left->capacity, right->capacity), size);
IType* sija = reinterpret_cast<IType*>(s->ija);
IType* rija = reinterpret_cast<IType*>(right->ija);
// set the element between D and LU (the boundary in A), which should be 0.
reinterpret_cast<DType*>(s->a)[s->shape[0]] = reinterpret_cast<DType*>(left->a)[left->shape[0]];
if (right && right != left) {
// some operations are unary and don't need this; others are x+x and don't need this
for (IType i = 0; i < s->shape[0]; ++i) {
IType ija = sija[i];
IType ija_next = sija[i+1];
for (IType r_ija = rija[i]; r_ija < rija[i+1]; ++r_ija) {
size_t ja = sija[ija]; // insert expects a size_t
if (ija == ija_next) {
// destination row is empty
ins_type = vector_insert<DType,IType>(s, ija, &ja, NULL, 1, true);
increment_ia_after<IType>(s, s->shape[0], i, 1);
++(s->ndnz);
++ija;
if (ins_type == 'i') ++ija_next;
} else {
bool found;
// merge positions into destination row
IType pos = insert_search<IType>(s, ija, ija_next-1, sija[ija], &found);
if (!found) {
vector_insert<DType,IType>(s, pos, &ja, NULL, 1, true);
increment_ia_after<IType>(s, s->shape[0], i, 1);
++(s->ndnz);
if (ins_type == 'i') ++ija_next;
}
// can now set a left boundary for the next search
ija = pos + 1;
}
}
}
}
return s;
}
/*
* Empty the matrix by initializing the IJA vector and setting the diagonal to 0.
*
* Called when most YALE_STORAGE objects are created.
*/
template <typename DType, typename IType>
void init(YALE_STORAGE* s) {
IType IA_INIT = s->shape[0] + 1;
IType* ija = reinterpret_cast<IType*>(s->ija);
// clear out IJA vector
for (IType i = 0; i < IA_INIT; ++i) {
ija[i] = IA_INIT; // set initial values for IJA
}
clear_diagonal_and_zero<DType>(s);
}
size_t max_size(YALE_STORAGE* s) {
size_t result = s->shape[0]*s->shape[1] + 1;
if (s->shape[0] > s->shape[1])
result += s->shape[0] - s->shape[1];
return result;
}
///////////////
// Accessors //
///////////////
/*
* Returns a slice of YALE_STORAGE object by copy
*
* Slicing-related.
*/
template <typename DType,typename IType>
void* get(YALE_STORAGE* storage, SLICE* slice) {
size_t *offset = slice->coords;
// Copy shape for yale construction
size_t* shape = ALLOC_N(size_t, 2);
shape[0] = slice->lengths[0];
shape[1] = slice->lengths[1];
IType *src_ija = reinterpret_cast<IType*>(storage->ija);
DType *src_a = reinterpret_cast<DType*>(storage->a);
// Calc ndnz
size_t ndnz = 0;
size_t i,j; // indexes of destination matrix
size_t k,l; // indexes of source matrix
for (i = 0; i < shape[0]; i++) {
k = i + offset[0];
for (j = 0; j < shape[1]; j++) {
l = j + offset[1];
if (j == i) continue;
if (k == l && src_a[k] != 0) ndnz++; // for diagonal element of source
else { // for non-diagonal element
for (size_t c = src_ija[k]; c < src_ija[k+1]; c++)
if (src_ija[c] == l) { ndnz++; break; }
}
}
}
size_t request_capacity = shape[0] + ndnz + 1;
YALE_STORAGE* ns = nm_yale_storage_create(storage->dtype, shape, 2, request_capacity);
if (ns->capacity < request_capacity)
rb_raise(nm_eStorageTypeError, "conversion failed; capacity of %ld requested, max allowable is %ld", request_capacity, ns->capacity);
// Initialize the A and IJA arrays
init<DType,IType>(ns);
IType *dst_ija = reinterpret_cast<IType*>(ns->ija);
DType *dst_a = reinterpret_cast<DType*>(ns->a);
size_t ija = shape[0] + 1;
DType val;
for (i = 0; i < shape[0]; ++i) {
k = i + offset[0];
for (j = 0; j < shape[1]; ++j) {
l = j + offset[1];
// Get value from source matrix
if (k == l) val = src_a[k];
else {
// copy non-diagonal element
for (size_t c = src_ija[k]; c < src_ija[k+1]; ++c) {
if (src_ija[c] == l) val = src_a[c];
}
}
// Set value to destination matrix
if (i == j) dst_a[i] = val;
else {
// copy non-diagonal element
dst_ija[ija] = j;
dst_a[ija] = val;
++ija;
for (size_t c = i + 1; c <= shape[0]; ++c) {
dst_ija[c] = ija;
}
}
}
}
dst_ija[shape[0]] = ija; // indicate the end of the last row
ns->ndnz = ndnz;
return ns;
}
/*
* Returns a pointer to the correct location in the A vector of a YALE_STORAGE object, given some set of coordinates
* (the coordinates are stored in slice).
*/
template <typename DType,typename IType>
void* ref(YALE_STORAGE* storage, SLICE* slice) {
size_t* coords = slice->coords;
if (!slice->single) rb_raise(rb_eNotImpError, "This type slicing not supported yet.");
DType* a = reinterpret_cast<DType*>(storage->a);
IType* ija = reinterpret_cast<IType*>(storage->ija);
if (coords[0] == coords[1])
return &(a[ coords[0] ]); // return diagonal entry
if (ija[coords[0]] == ija[coords[0]+1])
return &(a[ storage->shape[0] ]); // return zero pointer
// binary search for the column's location
int pos = binary_search<IType>(storage,
ija[coords[0]],
ija[coords[0]+1]-1,
coords[1]);
if (pos != -1 && ija[pos] == coords[1])
return &(a[pos]); // found exact value
return &(a[ storage->shape[0] ]); // return a pointer that happens to be zero
}
/*
* Attempt to set some cell in a YALE_STORAGE object. Must supply coordinates and a pointer to a value (which will be
* copied into the storage object).
*/
template <typename DType, typename IType>
char set(YALE_STORAGE* storage, SLICE* slice, void* value) {
DType* v = reinterpret_cast<DType*>(value);
size_t* coords = slice->coords;
bool found = false;
char ins_type;
if (coords[0] == coords[1]) {
reinterpret_cast<DType*>(storage->a)[coords[0]] = *v; // set diagonal
return 'r';
}
// Get IJA positions of the beginning and end of the row
if (reinterpret_cast<IType*>(storage->ija)[coords[0]] == reinterpret_cast<IType*>(storage->ija)[coords[0]+1]) {
// empty row
ins_type = vector_insert<DType,IType>(storage, reinterpret_cast<IType*>(storage->ija)[coords[0]], &(coords[1]), v, 1, false);
increment_ia_after<IType>(storage, storage->shape[0], coords[0], 1);
storage->ndnz++;
return ins_type;
}
// non-empty row. search for coords[1] in the IJA array, between ija and ija_next
// (including ija, not including ija_next)
//ija_size = get_size<IType>(storage);
// Do a binary search for the column
size_t pos = insert_search<IType>(storage,
reinterpret_cast<IType*>(storage->ija)[coords[0]],
reinterpret_cast<IType*>(storage->ija)[coords[0]+1]-1,
coords[1], &found);
if (found) { // replace
reinterpret_cast<IType*>(storage->ija)[pos] = coords[1];
reinterpret_cast<DType*>(storage->a)[pos] = *v;
return 'r';
}
ins_type = vector_insert<DType,IType>(storage, pos, &(coords[1]), v, 1, false);
increment_ia_after<IType>(storage, storage->shape[0], coords[0], 1);
storage->ndnz++;
return ins_type;
}
///////////
// Tests //
///////////
/*
* Yale eql? -- for whole-matrix comparison returning a single value.
*/
template <typename LDType, typename RDType, typename IType>
static bool eqeq(const YALE_STORAGE* left, const YALE_STORAGE* right) {
LDType* la = reinterpret_cast<LDType*>(left->a);
RDType* ra = reinterpret_cast<RDType*>(right->a);
// Compare the diagonals first.
for (size_t index = 0; index < left->shape[0]; ++index) {
if (la[index] != ra[index]) return false;
}
IType* lij = reinterpret_cast<IType*>(left->ija);
IType* rij = reinterpret_cast<IType*>(right->ija);
for (IType i = 0; i < left->shape[0]; ++i) {
// Get start and end positions of row
IType l_ija = lij[i],
l_ija_next = lij[i+1],
r_ija = rij[i],
r_ija_next = rij[i+1];
// Check to see if one row is empty and the other isn't.
if (ndrow_is_empty<LDType,IType>(left, l_ija, l_ija_next)) {
if (!ndrow_is_empty<RDType,IType>(right, r_ija, r_ija_next)) {
return false;
}
} else if (ndrow_is_empty<RDType,IType>(right, r_ija, r_ija_next)) {
// one is empty but the other isn't
return false;
} else if (!ndrow_eqeq_ndrow<LDType,RDType,IType>(left, right, l_ija, l_ija_next, r_ija, r_ija_next)) {
// Neither row is empty. Must compare the rows directly.
return false;
}
}
return true;
}
/*
* Are two non-diagonal rows the same? We already know.
*/
template <typename LDType, typename RDType, typename IType>
static bool ndrow_eqeq_ndrow(const YALE_STORAGE* l, const YALE_STORAGE* r, IType l_ija, const IType l_ija_next, IType r_ija, const IType r_ija_next) {
bool l_no_more = false, r_no_more = false;
IType *lij = reinterpret_cast<IType*>(l->ija),
*rij = reinterpret_cast<IType*>(r->ija);
LDType* la = reinterpret_cast<LDType*>(l->a);
RDType* ra = reinterpret_cast<RDType*>(r->a);
IType l_ja = lij[l_ija],
r_ja = rij[r_ija];
IType ja = std::min(l_ja, r_ja);
while (!(l_no_more && r_no_more)) {
if (l_ja == r_ja) {
if (ra[r_ija] != la[l_ija]) return false; // Direct comparison
++l_ija;
++r_ija;
if (l_ija < l_ija_next) {
l_ja = lij[l_ija];
} else {
l_no_more = true;
}
if (r_ija < r_ija_next) {
r_ja = rij[r_ija];
} else {
r_no_more = true;
}
ja = std::min(l_ja, r_ja);
} else if (l_no_more || ja < l_ja) {
if (ra[r_ija] != 0) return false;
++r_ija;
if (r_ija < r_ija_next) {
// get next column
r_ja = rij[r_ija];
ja = std::min(l_ja, r_ja);
} else {
l_no_more = true;
}
} else if (r_no_more || ja < r_ja) {
if (la[l_ija] != 0) return false;
++l_ija;
if (l_ija < l_ija_next) {
// get next column
l_ja = lij[l_ija];
ja = std::min(l_ja, r_ja);
} else {
l_no_more = true;
}
} else {
std::fprintf(stderr, "Unhandled in eqeq: l_ja=%d, r_ja=%d\n", (int)l_ja, (int)r_ja);
}
}
// every item matched
return true;
}
/*
* Is the non-diagonal portion of the row empty?
*/
template <typename DType, typename IType>
static bool ndrow_is_empty(const YALE_STORAGE* s, IType ija, const IType ija_next) {
if (ija == ija_next) return true;
DType* a = reinterpret_cast<DType*>(s->a);
// do all the entries = zero?
for (; ija < ija_next; ++ija) {
if (a[ija] != 0) return false;
}
return true;
}
//////////
// Math //
//////////
#define YALE_IA(s) (reinterpret_cast<IType*>(s->ija))
#define YALE_IJ(s) (reinterpret_cast<IType*>(s->ija) + s->shape[0] + 1)
#define YALE_COUNT(yale) (yale->ndnz + yale->shape[0])
template <typename nm::ewop_t op, typename IType, typename DType>
YALE_STORAGE* ew_op(const YALE_STORAGE* left, const YALE_STORAGE* right, dtype_t dtype) {
size_t init_capacity;
size_t* new_shape;
unsigned int da_index,
la_index,
ra_index,
a_index_offset,
la_row_max,
ra_row_max,
row_index;
DType tmp_result;
DType * la = reinterpret_cast<DType*> (left->a),
* ra = reinterpret_cast<DType*>(right->a),
* da;
YALE_STORAGE* dest;
new_shape = reinterpret_cast<size_t*>(calloc(2, sizeof(size_t)));
new_shape[0] = left->shape[0];
new_shape[1] = left->shape[1];
init_capacity = std::min(left->ndnz + right->ndnz + new_shape[0], new_shape[0] * new_shape[1]);
dest = nm_yale_storage_create(dtype, new_shape, 2, init_capacity);
da = reinterpret_cast<DType*>(dest->a);
// Calculate diagonal values.
for (da_index = 0; da_index < dest->shape[0]; ++da_index) {
da[da_index] = ew_op_switch<op, DType, DType>(la[da_index], ra[da_index]);
}
// Set the zero representation seperator.
da[da_index] = typeid(DType) == typeid(RubyObject) ? INT2FIX(0) : 0;
/*
* Calculate the offset between start of the A arrays and the non-diagonal
* entries.
*/
a_index_offset = dest->shape[0] + 1;
// Re-base the A arrays.
la = la + a_index_offset;
ra = ra + a_index_offset;
da = da + a_index_offset;
// Initialize our A array indices.
la_index = ra_index = da_index = 0;
// Calculate the non-diagonal values.
for (row_index = 0; row_index < dest->shape[0]; ++row_index) {
/*
* Each row.
*/
printf("Row %d\n", row_index);
// Get row bounds.
la_row_max = YALE_IA( left)[row_index + 1] - a_index_offset;
ra_row_max = YALE_IA(right)[row_index + 1] - a_index_offset;
printf("Left : Row Start: %d - Row End %d\n", la_index + a_index_offset, la_row_max + a_index_offset);
printf("Right : Row Start: %d - Row End %d\n", ra_index + a_index_offset, ra_row_max + a_index_offset);
/*
* Set this row's left bound (which is also the previous row's right
* bound).
*/
YALE_IA(dest)[row_index] = da_index + a_index_offset;
printf("Left bound of row %d in destination: %d\n", (int)row_index, (int)YALE_IA(dest)[row_index]);
// Iterate over non-diagonal entries in this row.
while (la_index < la_row_max and ra_index < ra_row_max) {
/*
* Elements are present on both the left- and right-hand side.
*/
printf("Marker 0\n");
if (YALE_IJ(left)[la_index] == YALE_IJ(right)[ra_index]) {
/*
* Current left- and right-hand values are in the same row and
* column.
*/
printf("Calculating value for [%d, %d].\n", (int)row_index, (int)YALE_IJ(left)[la_index]);
tmp_result = ew_op_switch<op, DType, DType>(la[la_index], ra[ra_index]);
if (tmp_result != 0) {
printf("Setting value for [%d, %d] at index %d in destination's A array.\n", (int)row_index, (int)YALE_IJ(left)[la_index], (int)(da_index + a_index_offset));
da[da_index] = tmp_result;
YALE_IJ(dest)[da_index] = YALE_IJ(left)[la_index];
++da_index;
} else {
printf("Result was 0. Skipping.\n");
}
++la_index;
++ra_index;
} else if (YALE_IJ(left)[la_index] < YALE_IJ(right)[ra_index]) {
/*
* The right-hand index is ahead of the left-hand index.
*/
if (op != EW_MUL) {
// If this is multiplion there is no point in doing the operation.
tmp_result = ew_op_switch<op, DType, DType>(la[la_index], typeid(DType) == typeid(RubyObject) ? INT2FIX(0) : 0);
printf("Setting value for [%d, %d].\n", (int)row_index, (int)YALE_IJ(left)[la_index]);
if (tmp_result != 0) {
da[da_index] = tmp_result;
YALE_IJ(dest)[da_index] = YALE_IJ(left)[la_index];
++da_index;
}
}
++la_index;
} else {
/*
* The left-hand index is ahead of the right-hand index.
*/
if (op != EW_MUL) {
// If this is multiplion there is no point in doing the operation.
tmp_result = ew_op_switch<op, DType, DType>(typeid(DType) == typeid(RubyObject) ? INT2FIX(0) : 0, ra[ra_index]);
printf("Setting value for [%d, %d].\n", (int)row_index, (int)YALE_IJ(right)[ra_index]);
if (tmp_result != 0) {
da[da_index] = tmp_result;
YALE_IJ(dest)[da_index] = YALE_IJ(right)[ra_index];
++da_index;
}
}
++ra_index;
}
}
if (op != EW_MUL) {
/*
* Process the remaining elements on the left- or right-hand side. One or
* the other, or neither, of the following loops may execute, but not
* both.
*
* If we are doing multiplication this is unnecessary as all remaining
* operations will produce a zero value.
*/
while (la_index < la_row_max) {
/*
* Process the remaining elements on the left-hand side.
*/
printf("Marker 1\n");
tmp_result = ew_op_switch<op, DType, DType>(la[la_index], typeid(DType) == typeid(RubyObject) ? INT2FIX(0) : 0);
printf("Setting value for [%d, %d].\n", (int)row_index, (int)YALE_IJ(left)[la_index]);
if (tmp_result != 0) {
da[da_index] = tmp_result;
YALE_IJ(dest)[da_index] = YALE_IJ(left)[la_index];
++da_index;
}
++la_index;
}
while (ra_index < ra_row_max) {
/*
* Process the remaining elements on the right-hand side.
*/
printf("Marker 2\n");
tmp_result = ew_op_switch<op, DType, DType>(typeid(DType) == typeid(RubyObject) ? INT2FIX(0) : 0, ra[ra_index]);
printf("Setting value for [%d, %d].\n", (int)row_index, (int)YALE_IJ(right)[ra_index]);
if (tmp_result != 0) {
da[da_index] = tmp_result;
YALE_IJ(dest)[da_index] = YALE_IJ(right)[ra_index];
++da_index;
}
++ra_index;
}
}
// Advance the row indices.
la_index = la_row_max;
ra_index = ra_row_max;
printf("End of row %d\n\n", row_index);
}
// Set the last row's right bound.
YALE_IA(dest)[row_index] = da_index + a_index_offset;
printf("Right bound of row %d in destination: %d\n", row_index - 1, da_index + a_index_offset);
// Set the number of non-diagonal non-zero entries in the destination matrix.
dest->ndnz = da_index;
printf("Number of non-diagonal non-zero entires: %ld\n\n", (unsigned long)(dest->ndnz));
// Set the capacity of the destination matrix.
dest->capacity = dest->shape[0] + dest->ndnz + 1;
// Resize the destination matrix.
dest->a = realloc(dest->a, sizeof(DType) * dest->capacity);
dest->ija = realloc(dest->ija, sizeof(IType) * dest->capacity);
return dest;
}
/////////////
// Utility //
/////////////
/*
* Binary search for returning stored values. Returns a non-negative position, or -1 for not found.
*/
template <typename IType>
int binary_search(YALE_STORAGE* s, IType left, IType right, IType key) {
if (left > right) return -1;
IType* ija = reinterpret_cast<IType*>(s->ija);
IType mid = (left + right)/2;
IType mid_j = ija[mid];
if (mid_j == key)
return mid;
else if (mid_j > key)
return binary_search<IType>(s, left, mid - 1, key);
else
return binary_search<IType>(s, mid + 1, right, key);
}
/*
* Resize yale storage vectors A and IJA in preparation for an insertion.
*/
template <typename DType, typename IType>
static char vector_insert_resize(YALE_STORAGE* s, size_t current_size, size_t pos, size_t* j, size_t n, bool struct_only) {
// Determine the new capacity for the IJA and A vectors.
size_t new_capacity = s->capacity * GROWTH_CONSTANT;
size_t max_capacity = max_size(s);
if (new_capacity > max_capacity) {
new_capacity = max_capacity;
if (current_size + n > max_capacity) rb_raise(rb_eNoMemError, "insertion size exceeded maximum yale matrix size");
}
if (new_capacity < current_size + n)
new_capacity = current_size + n;
// Allocate the new vectors.
IType* new_ija = ALLOC_N( IType, new_capacity );
NM_CHECK_ALLOC(new_ija);
DType* new_a = ALLOC_N( DType, new_capacity );
NM_CHECK_ALLOC(new_a);
IType* old_ija = reinterpret_cast<IType*>(s->ija);
DType* old_a = reinterpret_cast<DType*>(s->a);
// Copy all values prior to the insertion site to the new IJA and new A
if (struct_only) {
for (size_t i = 0; i < pos; ++i) {
new_ija[i] = old_ija[i];
}
} else {
for (size_t i = 0; i < pos; ++i) {
new_ija[i] = old_ija[i];
new_a[i] = old_a[i];
}
}
// Copy all values subsequent to the insertion site to the new IJA and new A, leaving room (size n) for insertion.
if (struct_only) {
for (size_t i = pos; i < current_size - pos + n - 1; ++i) {
new_ija[i+n] = old_ija[i];
}
} else {
for (size_t i = pos; i < current_size - pos + n - 1; ++i) {
new_ija[i+n] = old_ija[i];
new_a[i+n] = old_a[i];
}
}
s->capacity = new_capacity;
free(s->ija);
free(s->a);
s->ija = reinterpret_cast<void*>(new_ija);
s->a = reinterpret_cast<void*>(new_a);
return 'i';
}
/*
* Insert a value or contiguous values in the ija and a vectors (after ja and
* diag). Does not free anything; you are responsible!
*
* TODO: Improve this so it can handle non-contiguous element insertions
* efficiently. For now, we can just sort the elements in the row in
* question.)
*/
template <typename DType, typename IType>
static char vector_insert(YALE_STORAGE* s, size_t pos, size_t* j, DType* val, size_t n, bool struct_only) {
if (pos < s->shape[0]) {
rb_raise(rb_eArgError, "vector insert pos is before beginning of ja; this should not happen");
}
size_t size = get_size<IType>(s);
IType* ija = reinterpret_cast<IType*>(s->ija);
DType* a = reinterpret_cast<DType*>(s->a);
if (size + n > s->capacity) {
vector_insert_resize<DType,IType>(s, size, pos, j, n, struct_only);
// Need to get the new locations for ija and a.
ija = reinterpret_cast<IType*>(s->ija);
a = reinterpret_cast<DType*>(s->a);
} else {
/*
* No resize required:
* easy (but somewhat slow), just copy elements to the tail, starting at
* the end, one element at a time.
*
* TODO: This can be made slightly more efficient, but only after the tests
* are written.
*/
if (struct_only) {
for (size_t i = 0; i < size - pos; ++i) {
ija[size+n-1-i] = ija[size-1-i];
}
} else {
for (size_t i = 0; i < size - pos; ++i) {
ija[size+n-1-i] = ija[size-1-i];
a[size+n-1-i] = a[size-1-i];
}
}
}
// Now insert the new values.
if (struct_only) {
for (size_t i = 0; i < n; ++i) {
ija[pos+i] = j[i];
}
} else {
for (size_t i = 0; i < n; ++i) {
ija[pos+i] = j[i];
a[pos+i] = val[i];
}
}
return 'i';