-
Notifications
You must be signed in to change notification settings - Fork 0
/
numc.c
441 lines (397 loc) · 13.5 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
#include "numc.h"
#include <structmember.h>
PyTypeObject Matrix61cType;
/* 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 */
}
/*
* 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 */
}
/*
* 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 */
}
/*
* Negates the given numc.Matrix.
*/
PyObject *Matrix61c_neg(Matrix61c* self) {
/* TODO: YOUR CODE HERE */
}
/*
* Take the element-wise absolute value of this numc.Matrix.
*/
PyObject *Matrix61c_abs(Matrix61c *self) {
/* TODO: YOUR CODE HERE */
}
/*
* 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 */
}
/*
* Create a PyNumberMethods struct for overloading operators with all the number methods you have
* define. You might find this link helpful: https://docs.python.org/3.6/c-api/typeobj.html
*/
PyNumberMethods Matrix61c_as_number = {
/* TODO: YOUR CODE HERE */
};
/* 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 */
}
/*
* 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 */
}
/*
* 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 */
{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 */
}
/*
* 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 */
}
PyMappingMethods Matrix61c_mapping = {
NULL,
(binaryfunc) Matrix61c_subscript,
(objobjargproc) Matrix61c_set_subscript,
};
/* INSTANCE ATTRIBUTES*/
PyMemberDef Matrix61c_members[] = {
{
"shape", T_OBJECT_EX, offsetof(Matrix61c, shape), 0,
"(rows, cols)"
},
{NULL} /* Sentinel */
};
PyTypeObject Matrix61cType = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "numc.Matrix",
.tp_basicsize = sizeof(Matrix61c),
.tp_dealloc = (destructor)Matrix61c_dealloc,
.tp_repr = (reprfunc)Matrix61c_repr,
.tp_as_number = &Matrix61c_as_number,
.tp_flags = Py_TPFLAGS_DEFAULT |
Py_TPFLAGS_BASETYPE,
.tp_doc = "numc.Matrix objects",
.tp_methods = Matrix61c_methods,
.tp_members = Matrix61c_members,
.tp_as_mapping = &Matrix61c_mapping,
.tp_init = (initproc)Matrix61c_init,
.tp_new = Matrix61c_new
};
struct PyModuleDef numcmodule = {
PyModuleDef_HEAD_INIT,
"numc",
"Numc matrix operations",
-1,
Matrix61c_class_methods
};
/* Initialize the numc module */
PyMODINIT_FUNC PyInit_numc(void) {
PyObject* m;
if (PyType_Ready(&Matrix61cType) < 0)
return NULL;
m = PyModule_Create(&numcmodule);
if (m == NULL)
return NULL;
Py_INCREF(&Matrix61cType);
PyModule_AddObject(m, "Matrix", (PyObject *)&Matrix61cType);
printf("CS61C Fall 2020 Project 4: numc imported!\n");
fflush(stdout);
return m;
}