-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumc.c
1151 lines (1065 loc) · 44.8 KB
/
numc.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
#include "numc.h"
#include <structmember.h>
PyTypeObject Matrix61cType;
int isASingleNumberIndex(Matrix61c*, PyObject *key);
/* Helper functions for initalization of matrices and vectors */
/*
* Return a tuple given rows and cols
*/
PyObject *get_shape(int rows, int cols) {
if (rows == 1 || cols == 1) {
return PyTuple_Pack(1, PyLong_FromLong(rows * cols));
} else {
return PyTuple_Pack(2, PyLong_FromLong(rows), PyLong_FromLong(cols));
}
}
/*
* Matrix(rows, cols, low, high). Fill a matrix random double values
*/
int init_rand(PyObject *self, int rows, int cols, unsigned int seed, double low,
double high) {
matrix *new_mat;
int alloc_failed = allocate_matrix(&new_mat, rows, cols);
if (alloc_failed) return alloc_failed;
rand_matrix(new_mat, seed, low, high);
((Matrix61c *)self)->mat = new_mat;
((Matrix61c *)self)->shape = get_shape(new_mat->rows, new_mat->cols);
return 0;
}
/*
* Matrix(rows, cols, val). Fill a matrix of dimension rows * cols with val
*/
int init_fill(PyObject *self, int rows, int cols, double val) {
matrix *new_mat;
int alloc_failed = allocate_matrix(&new_mat, rows, cols);
if (alloc_failed)
return alloc_failed;
else {
fill_matrix(new_mat, val);
((Matrix61c *)self)->mat = new_mat;
((Matrix61c *)self)->shape = get_shape(new_mat->rows, new_mat->cols);
}
return 0;
}
/*
* Matrix(rows, cols, 1d_list). Fill a matrix with dimension rows * cols with 1d_list values
*/
int init_1d(PyObject *self, int rows, int cols, PyObject *lst) {
if (rows * cols != PyList_Size(lst)) {
PyErr_SetString(PyExc_ValueError, "Incorrect number of elements in list");
return -1;
}
matrix *new_mat;
int alloc_failed = allocate_matrix(&new_mat, rows, cols);
if (alloc_failed) return alloc_failed;
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
set(new_mat, i, j, PyFloat_AsDouble(PyList_GetItem(lst, count)));
count++;
}
}
((Matrix61c *)self)->mat = new_mat;
((Matrix61c *)self)->shape = get_shape(new_mat->rows, new_mat->cols);
return 0;
}
/*
* Matrix(2d_list). Fill a matrix with dimension len(2d_list) * len(2d_list[0])
*/
int init_2d(PyObject *self, PyObject *lst) {
int rows = PyList_Size(lst);
if (rows == 0) {
PyErr_SetString(PyExc_ValueError,
"Cannot initialize numc.Matrix with an empty list");
return -1;
}
int cols;
if (!PyList_Check(PyList_GetItem(lst, 0))) {
PyErr_SetString(PyExc_ValueError, "List values not valid");
return -1;
} else {
cols = PyList_Size(PyList_GetItem(lst, 0));
}
for (int i = 0; i < rows; i++) {
if (!PyList_Check(PyList_GetItem(lst, i)) ||
PyList_Size(PyList_GetItem(lst, i)) != cols) {
PyErr_SetString(PyExc_ValueError, "List values not valid");
return -1;
}
}
matrix *new_mat;
int alloc_failed = allocate_matrix(&new_mat, rows, cols);
if (alloc_failed) return alloc_failed;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
set(new_mat, i, j,
PyFloat_AsDouble(PyList_GetItem(PyList_GetItem(lst, i), j)));
}
}
((Matrix61c *)self)->mat = new_mat;
((Matrix61c *)self)->shape = get_shape(new_mat->rows, new_mat->cols);
return 0;
}
/*
* This deallocation function is called when reference count is 0
*/
void Matrix61c_dealloc(Matrix61c *self) {
deallocate_matrix(self->mat);
Py_TYPE(self)->tp_free(self);
}
/* For immutable types all initializations should take place in tp_new */
PyObject *Matrix61c_new(PyTypeObject *type, PyObject *args,
PyObject *kwds) {
/* size of allocated memory is tp_basicsize + nitems*tp_itemsize*/
Matrix61c *self = (Matrix61c *)type->tp_alloc(type, 0);
return (PyObject *)self;
}
/*
* This matrix61c type is mutable, so needs init function. Return 0 on success otherwise -1
*/
int Matrix61c_init(PyObject *self, PyObject *args, PyObject *kwds) {
/* Generate random matrices */
if (kwds != NULL) {
PyObject *rand = PyDict_GetItemString(kwds, "rand");
if (!rand) {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
if (!PyBool_Check(rand)) {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
if (rand != Py_True) {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
PyObject *low = PyDict_GetItemString(kwds, "low");
PyObject *high = PyDict_GetItemString(kwds, "high");
PyObject *seed = PyDict_GetItemString(kwds, "seed");
double double_low = 0;
double double_high = 1;
unsigned int unsigned_seed = 0;
if (low) {
if (PyFloat_Check(low)) {
double_low = PyFloat_AsDouble(low);
} else if (PyLong_Check(low)) {
double_low = PyLong_AsLong(low);
}
}
if (high) {
if (PyFloat_Check(high)) {
double_high = PyFloat_AsDouble(high);
} else if (PyLong_Check(high)) {
double_high = PyLong_AsLong(high);
}
}
if (double_low >= double_high) {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
// Set seed if argument exists
if (seed) {
if (PyLong_Check(seed)) {
unsigned_seed = PyLong_AsUnsignedLong(seed);
}
}
PyObject *rows = NULL;
PyObject *cols = NULL;
if (PyArg_UnpackTuple(args, "args", 2, 2, &rows, &cols)) {
if (rows && cols && PyLong_Check(rows) && PyLong_Check(cols)) {
return init_rand(self, PyLong_AsLong(rows), PyLong_AsLong(cols), unsigned_seed, double_low,
double_high);
}
} else {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
}
PyObject *arg1 = NULL;
PyObject *arg2 = NULL;
PyObject *arg3 = NULL;
if (PyArg_UnpackTuple(args, "args", 1, 3, &arg1, &arg2, &arg3)) {
/* arguments are (rows, cols, val) */
if (arg1 && arg2 && arg3 && PyLong_Check(arg1) && PyLong_Check(arg2) && (PyLong_Check(arg3)
|| PyFloat_Check(arg3))) {
if (PyLong_Check(arg3)) {
return init_fill(self, PyLong_AsLong(arg1), PyLong_AsLong(arg2), PyLong_AsLong(arg3));
} else
return init_fill(self, PyLong_AsLong(arg1), PyLong_AsLong(arg2), PyFloat_AsDouble(arg3));
} else if (arg1 && arg2 && arg3 && PyLong_Check(arg1) && PyLong_Check(arg2) && PyList_Check(arg3)) {
/* Matrix(rows, cols, 1D list) */
return init_1d(self, PyLong_AsLong(arg1), PyLong_AsLong(arg2), arg3);
} else if (arg1 && PyList_Check(arg1) && arg2 == NULL && arg3 == NULL) {
/* Matrix(rows, cols, 1D list) */
return init_2d(self, arg1);
} else if (arg1 && arg2 && PyLong_Check(arg1) && PyLong_Check(arg2) && arg3 == NULL) {
/* Matrix(rows, cols, 1D list) */
return init_fill(self, PyLong_AsLong(arg1), PyLong_AsLong(arg2), 0);
} else {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
} else {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return -1;
}
}
/*
* List of lists representations for matrices
*/
PyObject *Matrix61c_to_list(Matrix61c *self) {
int rows = self->mat->rows;
int cols = self->mat->cols;
PyObject *py_lst = NULL;
if (self->mat->is_1d) { // If 1D matrix, print as a single list
py_lst = PyList_New(rows * cols);
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
PyList_SetItem(py_lst, count, PyFloat_FromDouble(get(self->mat, i, j)));
count++;
}
}
} else { // if 2D, print as nested list
py_lst = PyList_New(rows);
for (int i = 0; i < rows; i++) {
PyList_SetItem(py_lst, i, PyList_New(cols));
PyObject *curr_row = PyList_GetItem(py_lst, i);
for (int j = 0; j < cols; j++) {
PyList_SetItem(curr_row, j, PyFloat_FromDouble(get(self->mat, i, j)));
}
}
}
return py_lst;
}
PyObject *Matrix61c_class_to_list(Matrix61c *self, PyObject *args) {
PyObject *mat = NULL;
if (PyArg_UnpackTuple(args, "args", 1, 1, &mat)) {
if (!PyObject_TypeCheck(mat, &Matrix61cType)) {
PyErr_SetString(PyExc_TypeError, "Argument must of type numc.Matrix!");
return NULL;
}
Matrix61c* mat61c = (Matrix61c*)mat;
return Matrix61c_to_list(mat61c);
} else {
PyErr_SetString(PyExc_TypeError, "Invalid arguments");
return NULL;
}
}
/*
* Add class methods
*/
PyMethodDef Matrix61c_class_methods[] = {
{"to_list", (PyCFunction)Matrix61c_class_to_list, METH_VARARGS, "Returns a list representation of numc.Matrix"},
{NULL, NULL, 0, NULL}
};
/*
* Matrix61c string representation. For printing purposes.
*/
PyObject *Matrix61c_repr(PyObject *self) {
PyObject *py_lst = Matrix61c_to_list((Matrix61c *)self);
return PyObject_Repr(py_lst);
}
/* NUMBER METHODS */
/*
* Add the second numc.Matrix (Matrix61c) object to the first one. The first operand is
* self, and the second operand can be obtained by casting `args`.
*/
PyObject *Matrix61c_add(Matrix61c* self, PyObject* args) {
/* TODO: YOUR CODE HERE */
//if (PyArg_UnpackTuple(args, "args", 1, 1, &mat)) {
if (PyObject_TypeCheck(args, &Matrix61cType)) {
Matrix61c* other = (Matrix61c *) args;
matrix **newMat = (matrix **) malloc(sizeof(matrix*));
int allocateSuccess = allocate_matrix(newMat, self->mat->rows, self->mat->cols);
if (allocateSuccess == 0) {
Matrix61c *rv = (Matrix61c *) Matrix61c_new(&Matrix61cType, NULL, NULL);
int success = add_matrix(*newMat, self->mat, other->mat);
if (success != 0) {
deallocate_matrix(*newMat);
return NULL;
}
rv->mat = *newMat;
rv->shape = get_shape(rv->mat->rows, rv->mat->cols);
return (PyObject *)rv;
} else {
deallocate_matrix(*newMat);
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Argument must of type numc.Matrix!");
return NULL;
}
}
/*
* Substract the second numc.Matrix (Matrix61c) object from the first one. The first operand is
* self, and the second operand can be obtained by casting `args`.
*/
PyObject *Matrix61c_sub(Matrix61c* self, PyObject* args) {
/* TODO: YOUR CODE HERE */
if (PyObject_TypeCheck(args, &Matrix61cType)) {
Matrix61c* other = (Matrix61c *) args;
matrix **newMat = (matrix **) malloc(sizeof(matrix*));
int allocateSuccess = allocate_matrix(newMat, self->mat->rows, self->mat->cols);
if (allocateSuccess == 0) {
Matrix61c *rv = (Matrix61c *) Matrix61c_new(&Matrix61cType, NULL, NULL);
int success = sub_matrix(*newMat, self->mat, other->mat);
if (success != 0) {
deallocate_matrix(*newMat);
return NULL;
}
rv->mat = *newMat;
rv->shape = get_shape(rv->mat->rows, rv->mat->cols);
return (PyObject *)rv;
} else {
deallocate_matrix(*newMat);
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Argument must of type numc.Matrix!");
return NULL;
}
}
/*
* NOT element-wise multiplication. The first operand is self, and the second operand
* can be obtained by casting `args`.
*/
PyObject *Matrix61c_multiply(Matrix61c* self, PyObject *args) {
/* TODO: YOUR CODE HERE */
if (PyObject_TypeCheck(args, &Matrix61cType)) {
Matrix61c* other = (Matrix61c *) args;
matrix **newMat = (matrix **) malloc(sizeof(matrix*));
int allocateSuccess = allocate_matrix(newMat, self->mat->rows, other->mat->cols);
if (allocateSuccess == 0) {
Matrix61c *rv = (Matrix61c *) Matrix61c_new(&Matrix61cType, NULL, NULL);
int success = mul_matrix(*newMat, self->mat, other->mat);
if (success != 0) {
deallocate_matrix(*newMat);
PyErr_SetString(PyExc_ValueError, "Not valid dimensions");
return NULL;
}
rv->mat = *newMat;
rv->shape = get_shape(rv->mat->rows, rv->mat->cols);
return (PyObject *)rv;
} else {
deallocate_matrix(*newMat);
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Argument must of type numc.Matrix!");
return NULL;
}
}
/*
* Negates the given numc.Matrix.
*/
PyObject *Matrix61c_neg(Matrix61c* self) {
/* TODO: YOUR CODE HERE */
matrix **newMat = (matrix **) malloc(sizeof(matrix*));
int allocateSuccess = allocate_matrix(newMat, self->mat->rows, self->mat->cols);
if (allocateSuccess == 0) {
Matrix61c *rv = (Matrix61c *) Matrix61c_new(&Matrix61cType, NULL, NULL);
int success = neg_matrix(*newMat, self->mat);
if (success != 0) {
deallocate_matrix(*newMat);
return NULL;
}
rv->mat = *newMat;
rv->shape = get_shape(rv->mat->rows, rv->mat->cols);
return (PyObject *)rv;
} else {
deallocate_matrix(*newMat);
return NULL;
}
}
/*
* Take the element-wise absolute value of this numc.Matrix.
*/
PyObject *Matrix61c_abs(Matrix61c *self) {
/* TODO: YOUR CODE HERE */
matrix **newMat = (matrix **) malloc(sizeof(matrix*));
int allocateSuccess = allocate_matrix(newMat, self->mat->rows, self->mat->cols);
if (allocateSuccess == 0) {
Matrix61c *rv = (Matrix61c *) Matrix61c_new(&Matrix61cType, NULL, NULL);
int success = abs_matrix(*newMat, self->mat);
if (success != 0) {
deallocate_matrix(*newMat);
return NULL;
}
rv->mat = *newMat;
rv->shape = get_shape(rv->mat->rows, rv->mat->cols);
return (PyObject *)rv;
} else {
deallocate_matrix(*newMat);
return NULL;
}
}
/*
* Raise numc.Matrix (Matrix61c) to the `pow`th power. You can ignore the argument `optional`.
*/
PyObject *Matrix61c_pow(Matrix61c *self, PyObject *pow, PyObject *optional) {
/* TODO: YOUR CODE HERE */
if (PyLong_Check(pow)) {
int toPow = (int)PyLong_AsLong(pow);
matrix **newMat = (matrix **) malloc(sizeof(matrix*));
int allocateSuccess = allocate_matrix(newMat, self->mat->rows, self->mat->cols);
if (allocateSuccess == 0) {
Matrix61c *rv = (Matrix61c *) Matrix61c_new(&Matrix61cType, NULL, NULL);
int success = pow_matrix(*newMat, self->mat, toPow);
if (success != 0) {
PyErr_SetString(PyExc_ValueError, "Not valid dimensions");
deallocate_matrix(*newMat);
return NULL;
}
rv->mat = *newMat;
rv->shape = get_shape(rv->mat->rows, rv->mat->cols);
return (PyObject *)rv;
} else {
deallocate_matrix(*newMat);
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Argument must be an integer!");
return NULL;
}
}
/*
* Create a PyNumberMethods struct for overloading operators with all the number methods you have
* define. Ybinaryfuncou might find this link helpful: https://docs.python.org/3.6/c-api/typeobj.html
*/
PyNumberMethods Matrix61c_as_number = {
/* TODO: YOUR CODE HERE */
.nb_add = (binaryfunc) Matrix61c_add,
.nb_subtract = (binaryfunc) Matrix61c_sub,
.nb_multiply = (binaryfunc) Matrix61c_multiply,
.nb_absolute = (unaryfunc) Matrix61c_abs,
.nb_negative = (unaryfunc) Matrix61c_neg,
.nb_power = (ternaryfunc) Matrix61c_pow
};
/* INSTANCE METHODS */
/*
* Given a numc.Matrix self, parse `args` to (int) row, (int) col, and (double/int) val.
* Return None in Python (this is different from returning null).
*/
PyObject *Matrix61c_set_value(Matrix61c *self, PyObject* args) {
/* TODO: YOUR CODE HERE */
if (PyTuple_Size(args) == 3) {
PyObject *rows = NULL;
PyObject *cols = NULL;
PyObject *val = NULL;
PyArg_UnpackTuple(args, "args", 3, 3, &rows, &cols, &val);
if (rows && cols && val && PyLong_Check(rows) && PyLong_Check(cols) && (PyLong_Check(val)
|| PyFloat_Check(val))) {
int toRows = (int)PyLong_AsLong(rows);
int toCols = (int)PyLong_AsLong(cols);
double toVal;
if (PyLong_Check(val)) {
toVal = (double)PyLong_AsDouble(val);
} else {
toVal = (double)PyFloat_AsDouble(val);
}
if (!(toRows >= self->mat->rows || toCols >= self->mat->cols)) {
set(self->mat, toRows, toCols, toVal);
Py_RETURN_NONE;
} else {
PyErr_SetString(PyExc_IndexError, "Specified row or column is out of range!");
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Wrong types for arguments!");
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Wrong number of arguments!");
return NULL;
}
}
/*
* Given a numc.Matrix `self`, parse `args` to (int) row and (int) col.
* Return the value at the `row`th row and `col`th column, which is a Python
* float/int.
*/
PyObject *Matrix61c_get_value(Matrix61c *self, PyObject* args) {
/* TODO: YOUR CODE HERE */
if (PyTuple_Size(args) == 2) {
PyObject *rows = NULL;
PyObject *cols = NULL;
PyArg_UnpackTuple(args, "args", 2, 2, &rows, &cols);
if (rows && cols && PyLong_Check(rows) && PyLong_Check(cols)) {
int toRows = (int)PyLong_AsLong(rows);
int toCols = (int)PyLong_AsLong(cols);
if (!(toRows >= self->mat->rows || toCols >= self->mat->cols)) {
double val = get(self->mat, toRows, toCols);
PyObject *result = PyFloat_FromDouble(val);
return result;
} else {
PyErr_SetString(PyExc_IndexError, "Specified row or column is out of range!");
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Wrong types for arguments!");
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Wrong number of arguments!");
return NULL;
}
}
/*
* Create an array of PyMethodDef structs to hold the instance methods.
* Name the python function corresponding to Matrix61c_get_value as "get" and Matrix61c_set_value
* as "set"
* You might find this link helpful: https://docs.python.org/3.6/c-api/structures.html
*/
PyMethodDef Matrix61c_methods[] = {
/* TODO: YOUR CODE HERE */
//{"set", (PyCFunction)(*Matrix61c_set_value), 4, "docstring"},
{"get", (PyCFunction)(&Matrix61c_get_value), METH_VARARGS, "matrix getter"},
{"set", (PyCFunction)(&Matrix61c_set_value), METH_VARARGS, "matrix setter"},
{NULL, NULL, 0, NULL}
};
/* INDEXING */
/*
* Given a numc.Matrix `self`, index into it with `key`. Return the indexed result.
*/
PyObject *Matrix61c_subscript(Matrix61c* self, PyObject* key) {
/* TODO: YOUR CODE HERE */
if (self->mat->rows == 1 || self->mat->cols == 1) {
int length;
if (self->mat->rows == 1) {
length = self->mat->cols;
} else {
length = self->mat->rows;
}
if (PyLong_Check(key)) {
int index = (int)PyLong_AsLong(key);
if (self->mat->rows == 1) {
if (index >= self->mat->cols || index < 0) {
PyErr_SetString(PyExc_IndexError, "Index out of range!");
return NULL;
}
return PyFloat_FromDouble(self->mat->data[0][index]);
} else {
if (index >= self->mat->rows || index < 0) {
PyErr_SetString(PyExc_IndexError, "Index out of range!");
return NULL;
}
return PyFloat_FromDouble(self->mat->data[index][0]);
}
} else if (PySlice_Check(key)) {
Py_ssize_t start = 0;
Py_ssize_t end = 0;
Py_ssize_t step = 0;
Py_ssize_t sliceLength = 0;
int success = PySlice_GetIndicesEx(key, length, &start, &end, &step, &sliceLength);
if (end - start == 0 || step != 1 || start > end) {
PyErr_SetString(PyExc_ValueError, "Slice info not valid!");
return NULL;
}
if (success == 0) {
if (end - start == 1) {
if (self->mat->rows == 1) {
return PyFloat_FromDouble(self->mat->data[0][start]);
} else {
return PyFloat_FromDouble(self->mat->data[start][0]);
}
}
matrix **newMat = (matrix **) malloc(sizeof(matrix*));
Matrix61c *rv = (Matrix61c *) Matrix61c_new(&Matrix61cType, NULL, NULL);
int allRefSuccess;
if (self->mat->rows == 1) {
allRefSuccess = allocate_matrix_ref(newMat, self->mat, 0, start, 1, end - start);
} else {
allRefSuccess = allocate_matrix_ref(newMat, self->mat, start, 0, end - start, 1);
}
if (allRefSuccess != 0) {
Matrix61c_dealloc(rv);
deallocate_matrix(*newMat);
return NULL;
}
rv->mat = *newMat;
rv->shape = get_shape(rv->mat->rows, rv->mat->cols);
return (PyObject *)rv;
} else {
PyErr_SetString(PyExc_TypeError, "PySlice_GetIndicesEx could not parse key!");
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Key is not an integer or a slice for 1D matrix!");
return NULL;
}
} else {
int length = self->mat->rows;
if (PyLong_Check(key)) {
int selectedRow = (int)PyLong_AsLong(key);
if (selectedRow >= self->mat->rows || selectedRow < 0) {
PyErr_SetString(PyExc_IndexError, "Index out of range!");
return NULL;
}
matrix **newMat2D = (matrix **) malloc(sizeof(matrix*));
Matrix61c *rv2 = (Matrix61c *) Matrix61c_new(&Matrix61cType, NULL, NULL);
int integer2DSuccess = allocate_matrix_ref(newMat2D, self->mat, selectedRow, 0, 1, self->mat->cols);
if (integer2DSuccess != 0) {
Matrix61c_dealloc(rv2);
deallocate_matrix(*newMat2D);
return NULL;
}
rv2->mat = *newMat2D;
rv2->shape = get_shape(rv2->mat->rows, rv2->mat->cols);
return (PyObject *)rv2;
} else if (PySlice_Check(key)) {
Py_ssize_t start2Dslice = 0;
Py_ssize_t end2Dslice = 0;
Py_ssize_t step2Dslice = 0;
Py_ssize_t sliceLength2Dslice = 0;
int success2Dslice = PySlice_GetIndicesEx(key, length, &start2Dslice, &end2Dslice, &step2Dslice, &sliceLength2Dslice);
if (end2Dslice - start2Dslice == 0 || step2Dslice != 1 || start2Dslice > end2Dslice) {
PyErr_SetString(PyExc_ValueError, "Slice info not valid!");
return NULL;
}
if (success2Dslice == 0) {
matrix **newMat2D = (matrix **) malloc(sizeof(matrix*));
Matrix61c *rv2 = (Matrix61c *) Matrix61c_new(&Matrix61cType, NULL, NULL);
int allRefSuccess2D;
allRefSuccess2D = allocate_matrix_ref(newMat2D, self->mat, start2Dslice, 0, end2Dslice - start2Dslice, self->mat->cols);
if (allRefSuccess2D != 0) {
Matrix61c_dealloc(rv2);
deallocate_matrix(*newMat2D);
return NULL;
}
rv2->mat = *newMat2D;
rv2->shape = get_shape(rv2->mat->rows, rv2->mat->cols);
return (PyObject *)rv2;
} else {
PyErr_SetString(PyExc_TypeError, "PySlice_GetIndicesEx could not parse key!");
return NULL;
}
} else if (PyTuple_Check(key)) {
if (PyTuple_Size(key) == 2) {
PyObject *rows = NULL;
PyObject *cols = NULL;
if (PyArg_UnpackTuple(key, "args", 2, 2, &rows, &cols)) {
if (PyLong_Check(rows)) {
int rowIndex = (int)PyLong_AsLong(rows);
if (rowIndex >= self->mat->rows || rowIndex < 0) {
PyErr_SetString(PyExc_IndexError, "Index out of range!");
return NULL;
}
if (PyLong_Check(cols)) {
int colIndex = (int)PyLong_AsLong(cols);
if (colIndex >= self->mat->cols || colIndex < 0) {
PyErr_SetString(PyExc_IndexError, "Index out of range!");
return NULL;
}
return PyFloat_FromDouble(self->mat->data[rowIndex][colIndex]);
} else if (PySlice_Check(cols)) {
Py_ssize_t start2Dtuple = 0;
Py_ssize_t end2Dtuple = 0;
Py_ssize_t step2Dtuple = 0;
Py_ssize_t sliceLength2Dtuple = 0;
int success2Dtuple = PySlice_GetIndicesEx(cols, length, &start2Dtuple, &end2Dtuple, &step2Dtuple, &sliceLength2Dtuple);
if (end2Dtuple - start2Dtuple == 0 || step2Dtuple != 1 || start2Dtuple > end2Dtuple) {
PyErr_SetString(PyExc_ValueError, "Slice info not valid!");
return NULL;
}
if (success2Dtuple == 0) {
if (end2Dtuple - start2Dtuple == 1) {
return PyFloat_FromDouble(self->mat->data[rowIndex][start2Dtuple]);
}
matrix **newMat2D = (matrix **) malloc(sizeof(matrix*));
Matrix61c *rv2 = (Matrix61c *) Matrix61c_new(&Matrix61cType, NULL, NULL);
int allRefSuccess2D;
allRefSuccess2D = allocate_matrix_ref(newMat2D, self->mat, rowIndex, start2Dtuple, 1, end2Dtuple - start2Dtuple);
if (allRefSuccess2D != 0) {
Matrix61c_dealloc(rv2);
deallocate_matrix(*newMat2D);
return NULL;
}
rv2->mat = *newMat2D;
rv2->shape = get_shape(rv2->mat->rows, rv2->mat->cols);
return (PyObject *)rv2;
} else {
PyErr_SetString(PyExc_TypeError, "PySlice_GetIndicesEx could not parse key!");
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Key is not an integer, slice or a tuple for 2D matrix!");
return NULL;
}
} else if (PyLong_Check(cols)) {
int colIndex = (int)PyLong_AsLong(cols);
if (colIndex >= self->mat->cols || colIndex < 0) {
PyErr_SetString(PyExc_IndexError, "Index out of range!");
return NULL;
}
if (PySlice_Check(rows)) {
Py_ssize_t start2Dtuple = 0;
Py_ssize_t end2Dtuple = 0;
Py_ssize_t step2Dtuple = 0;
Py_ssize_t sliceLength2Dtuple = 0;
int success2Dtuple = PySlice_GetIndicesEx(rows, length, &start2Dtuple, &end2Dtuple, &step2Dtuple, &sliceLength2Dtuple);
if (end2Dtuple - start2Dtuple == 0 || step2Dtuple != 1 || start2Dtuple > end2Dtuple) {
PyErr_SetString(PyExc_TypeError, "slice info not valid!");
return NULL;
}
if (success2Dtuple == 0) {
if (end2Dtuple - start2Dtuple == 1) {
return PyFloat_FromDouble(self->mat->data[start2Dtuple][colIndex]);
}
matrix **newMat2D = (matrix **) malloc(sizeof(matrix*));
Matrix61c *rv2 = (Matrix61c *) Matrix61c_new(&Matrix61cType, NULL, NULL);
int allRefSuccess2D;
allRefSuccess2D = allocate_matrix_ref(newMat2D, self->mat, start2Dtuple, colIndex, end2Dtuple - start2Dtuple, 1);
if (allRefSuccess2D != 0) {
Matrix61c_dealloc(rv2);
deallocate_matrix(*newMat2D);
return NULL;
}
rv2->mat = *newMat2D;
rv2->shape = get_shape(rv2->mat->rows, rv2->mat->cols);
return (PyObject *)rv2;
} else {
PyErr_SetString(PyExc_TypeError, "PySlice_GetIndicesEx could not parse key!");
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Key is not an integer, slice or a tuple for 2D matrix!");
return NULL;
}
} else if (PySlice_Check(cols) && PySlice_Check(rows)) {
Py_ssize_t start2Dtuple1 = 0;
Py_ssize_t end2Dtuple1 = 0;
Py_ssize_t step2Dtuple1 = 0;
Py_ssize_t sliceLength2Dtuple1 = 0;
int success2Dtuple1 = PySlice_GetIndicesEx(rows, length, &start2Dtuple1, &end2Dtuple1, &step2Dtuple1, &sliceLength2Dtuple1);
Py_ssize_t start2Dtuple2 = 0;
Py_ssize_t end2Dtuple2 = 0;
Py_ssize_t step2Dtuple2 = 0;
Py_ssize_t sliceLength2Dtuple2 = 0;
int success2Dtuple2 = PySlice_GetIndicesEx(cols, length, &start2Dtuple2, &end2Dtuple2, &step2Dtuple2, &sliceLength2Dtuple2);
if (end2Dtuple1 - start2Dtuple1 == 0 || end2Dtuple2 - start2Dtuple2 == 0 || step2Dtuple1 != 1 || step2Dtuple2 != 1
|| start2Dtuple1 > end2Dtuple1 || start2Dtuple2 > end2Dtuple2) {
PyErr_SetString(PyExc_ValueError, "Slice info not valid!");
return NULL;
}
if (end2Dtuple1 - start2Dtuple1 == 1 && end2Dtuple2 - start2Dtuple2 == 1) {
return PyFloat_FromDouble(self->mat->data[start2Dtuple1][start2Dtuple2]);
}
if (success2Dtuple1 == 0 && success2Dtuple2 == 0) {
matrix **newMat2D = (matrix **) malloc(sizeof(matrix*));
Matrix61c *rv2 = (Matrix61c *) Matrix61c_new(&Matrix61cType, NULL, NULL);
int allRefSuccess2D;
allRefSuccess2D = allocate_matrix_ref(newMat2D, self->mat, start2Dtuple1, start2Dtuple2, end2Dtuple1 - start2Dtuple1, end2Dtuple2 - start2Dtuple2);
if (allRefSuccess2D != 0) {
Matrix61c_dealloc(rv2);
deallocate_matrix(*newMat2D);
return NULL;
}
rv2->mat = *newMat2D;
rv2->shape = get_shape(rv2->mat->rows, rv2->mat->cols);
return (PyObject *)rv2;
} else {
PyErr_SetString(PyExc_TypeError, "PySlice_GetIndicesEx could not parse key!");
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Key is not an integer, slice or a tuple for 2D matrix!");
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Invalid arguments for 2D tuple!");
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Tuple is not of size 2!");
return NULL;
}
} else {
PyErr_SetString(PyExc_TypeError, "Key is not an integer, slice or a tuple for 2D matrix!");
return NULL;
}
}
}
/*
* Given a numc.Matrix `self`, index into it with `key`, and set the indexed result to `v`.
*/
int Matrix61c_set_subscript(Matrix61c * self, PyObject * key, PyObject * v) {
/* TODO: YOUR CODE HERE */
PyObject *subscripted = Matrix61c_subscript(self, key);
if (subscripted != NULL) {
if (isASingleNumberIndex(self, subscripted)) {
double value;
if (!(PyLong_Check(v) || PyFloat_Check(v))) {
PyErr_SetString(PyExc_TypeError, "The Value is not of type integer or float!");
return -1;
}
if (PyLong_Check(v)) {
value = (double)PyLong_AsDouble(v);
} else {
value = (double)PyFloat_AsDouble(v);
}
if (PyLong_Check(key)) {
int index = (int)PyLong_AsLong(key);
if (self->mat->rows == 1) {
set(self->mat, 0, index, value);
return 0;
} else {
set(self->mat, index, 0, value);
return 0;
}
} else if (PySlice_Check(key)) {
int length;
if (self->mat->rows == 1) {
length = self->mat->cols;
} else {
length = self->mat->rows;
}
Py_ssize_t start = 0;
Py_ssize_t end = 0;
Py_ssize_t step = 0;
Py_ssize_t slicelength = 0;
PySlice_GetIndicesEx(key, length, &start, &end, &step, &slicelength);
if (self->mat->rows == 1) {
set(self->mat, 0, start, value);
} else {
set(self->mat, start, 0, value);
}
return 0;
} else if (PyTuple_Check(key)) {
int length = self->mat->rows;
PyObject *rows = NULL;
PyObject *cols = NULL;
PyArg_UnpackTuple(key, "args", 2, 2, &rows, &cols);
if (PyLong_Check(rows)) {
if (PyLong_Check(cols)) {
set(self->mat, (int)PyLong_AsLong(rows), (int)PyLong_AsLong(cols), value);
} else {
Py_ssize_t startTuple = 0;
Py_ssize_t endTuple = 0;
Py_ssize_t stepTuple = 0;
Py_ssize_t sliceLengthTuple = 0;
PySlice_GetIndicesEx(cols, length, &startTuple, &endTuple, &stepTuple, &sliceLengthTuple);
set(self->mat, (int)PyLong_AsLong(rows), startTuple, value);
}
} else {
if (PyLong_Check(cols)) {
Py_ssize_t startTuple = 0;
Py_ssize_t endTuple = 0;
Py_ssize_t stepTuple = 0;
Py_ssize_t sliceLengthTuple = 0;
PySlice_GetIndicesEx(rows, length, &startTuple, &endTuple, &stepTuple, &sliceLengthTuple);
set(self->mat, startTuple, (int)PyLong_AsLong(cols), value);
} else {
Py_ssize_t startTuple1 = 0;
Py_ssize_t endTuple1 = 0;
Py_ssize_t stepTuple1 = 0;
Py_ssize_t sliceLengthTuple1 = 0;
PySlice_GetIndicesEx(rows, length, &startTuple1, &endTuple1, &stepTuple1, &sliceLengthTuple1);
Py_ssize_t startTuple2 = 0;
Py_ssize_t endTuple2 = 0;
Py_ssize_t stepTuple2 = 0;
Py_ssize_t sliceLengthTuple2 = 0;
PySlice_GetIndicesEx(cols, length, &startTuple2, &endTuple2, &stepTuple2, &sliceLengthTuple2);
set(self->mat, startTuple1, startTuple2, value);
}
}
return 0;
} else {
PyErr_SetString(PyExc_TypeError, "The Key is not valid!");
return -1;
}
} else {
if (!PyList_Check(v)) {
PyErr_SetString(PyExc_TypeError, "The Value is not of a list!");
return -1;
}
Matrix61c *rv = (Matrix61c*)subscripted;
int rows = rv->mat->rows;
int cols = rv->mat->cols;
int size = PyList_Size(v);
int i, j;
if (rows == 1 || cols == 1) {
if (!(PyList_Check(v)) || PyList_Size(v) != rows * cols) {
PyErr_SetString(PyExc_ValueError, "The list if not of correct dimension");
return -1;
}
int w;
for (w = 0; w < size; w++) {
if (!PyLong_Check(PyList_GetItem(v, w)) && !PyFloat_Check(PyList_GetItem(v, w))) {
PyErr_SetString(PyExc_ValueError, "The list contains a non-double type value!");
return -1;
}
}
int count = 0;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
set(rv->mat, i, j, PyFloat_AsDouble(PyList_GetItem(v, count)));
count++;
}
}
return 0;
} else {
int y;
if (PyList_Size(v) != rows) {
PyErr_SetString(PyExc_ValueError, "The list is of wrong size!");
return -1;
}
for (y = 0; y < size; y++) {
if (!PyList_Check(PyList_GetItem(v, y))) {
PyErr_SetString(PyExc_ValueError, "The list contains a non-list type value!");
return -1;
} else {
int x;
int innerSize = PyList_Size(PyList_GetItem(v, y));
if (PyList_Size(PyList_GetItem(v, y)) != cols) {
PyErr_SetString(PyExc_ValueError, "The list is of wrong size!");
return -1;
}
for (x = 0; x < innerSize; x++) {
if (!(PyLong_Check(PyList_GetItem(PyList_GetItem(v, y), x))) && !(PyFloat_Check(PyList_GetItem(PyList_GetItem(v, y), x)))) {
PyErr_SetString(PyExc_ValueError, "The list contains a non-double type value!");
return -1;
}
}
}
}
int outer, inner;
for (outer = 0; outer < rows; outer++) {