-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathndarray.c
2230 lines (2082 loc) · 86 KB
/
ndarray.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
/*
* This file is part of the micropython-ulab project,
*
* https://github.com/v923z/micropython-ulab
*
* The MIT License (MIT)
*
* Copyright (c) 2019-2022 Zoltán Vörös
* 2020 Jeff Epler for Adafruit Industries
* 2020 Taku Fukada
*/
#include <unistd.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "py/runtime.h"
#include "py/binary.h"
#include "py/obj.h"
#include "py/objtuple.h"
#include "py/objint.h"
#include "ulab_tools.h"
#include "ndarray.h"
#include "ndarray_operators.h"
#include "numpy/carray/carray.h"
#include "numpy/carray/carray_tools.h"
mp_uint_t ndarray_print_threshold = NDARRAY_PRINT_THRESHOLD;
mp_uint_t ndarray_print_edgeitems = NDARRAY_PRINT_EDGEITEMS;
//| """Manipulate numeric data similar to numpy
//|
//| `ulab` is a numpy-like module for micropython, meant to simplify and
//| speed up common mathematical operations on arrays. The primary goal was to
//| implement a small subset of numpy that might be useful in the context of a
//| microcontroller. This means low-level data processing of linear (array) and
//| two-dimensional (matrix) data.
//|
//| `ulab` is adapted from micropython-ulab, and the original project's
//| documentation can be found at
//| https://micropython-ulab.readthedocs.io/en/latest/
//|
//| `ulab` is modeled after numpy, and aims to be a compatible subset where
//| possible. Numpy's documentation can be found at
//| https://docs.scipy.org/doc/numpy/index.html"""
//|
void ndarray_set_complex_value(void *p, size_t index, mp_obj_t value) {
mp_float_t real, imag;
if(mp_obj_is_type(value, &mp_type_complex)) {
mp_obj_get_complex(value, &real, &imag);
((mp_float_t *)p)[2 * index] = real;
((mp_float_t *)p)[2 * index + 1] = imag;
} else {
real = mp_obj_get_float(value);
((mp_float_t *)p)[2 * index] = real;
((mp_float_t *)p)[2 * index + 1] = MICROPY_FLOAT_CONST(0.0);
}
}
#ifdef CIRCUITPY
void ndarray_set_value(char typecode, void *p, size_t index, mp_obj_t val_in) {
switch (typecode) {
case NDARRAY_INT8:
((signed char *)p)[index] = mp_obj_get_int(val_in);
break;
case NDARRAY_UINT8:
((unsigned char *)p)[index] = mp_obj_get_int(val_in);
break;
case NDARRAY_INT16:
((short *)p)[index] = mp_obj_get_int(val_in);
break;
case NDARRAY_UINT16:
((unsigned short *)p)[index] = mp_obj_get_int(val_in);
break;
case NDARRAY_FLOAT:
((mp_float_t *)p)[index] = mp_obj_get_float(val_in);
break;
#if ULAB_SUPPORTS_COMPLEX
case NDARRAY_COMPLEX:
ndarray_set_complex_value(p, index, val_in);
break;
#endif
}
}
#endif
#if defined(MICROPY_VERSION_MAJOR) && MICROPY_VERSION_MAJOR == 1 && MICROPY_VERSION_MINOR == 11
void mp_obj_slice_indices(mp_obj_t self_in, mp_int_t length, mp_bound_slice_t *result) {
mp_obj_slice_t *self = MP_OBJ_TO_PTR(self_in);
mp_int_t start, stop, step;
if (self->step == mp_const_none) {
step = 1;
} else {
step = mp_obj_get_int(self->step);
if (step == 0) {
mp_raise_ValueError(translate("slice step can't be zero"));
}
}
if (step > 0) {
// Positive step
if (self->start == mp_const_none) {
start = 0;
} else {
start = mp_obj_get_int(self->start);
if (start < 0) {
start += length;
}
start = MIN(length, MAX(start, 0));
}
if (self->stop == mp_const_none) {
stop = length;
} else {
stop = mp_obj_get_int(self->stop);
if (stop < 0) {
stop += length;
}
stop = MIN(length, MAX(stop, 0));
}
} else {
// Negative step
if (self->start == mp_const_none) {
start = length - 1;
} else {
start = mp_obj_get_int(self->start);
if (start < 0) {
start += length;
}
start = MIN(length - 1, MAX(start, -1));
}
if (self->stop == mp_const_none) {
stop = -1;
} else {
stop = mp_obj_get_int(self->stop);
if (stop < 0) {
stop += length;
}
stop = MIN(length - 1, MAX(stop, -1));
}
}
result->start = start;
result->stop = stop;
result->step = step;
}
#endif /* MICROPY_VERSION v1.11 */
void ndarray_fill_array_iterable(mp_float_t *array, mp_obj_t iterable) {
mp_obj_iter_buf_t x_buf;
mp_obj_t x_item, x_iterable = mp_getiter(iterable, &x_buf);
while ((x_item = mp_iternext(x_iterable)) != MP_OBJ_STOP_ITERATION) {
*array++ = (mp_float_t)mp_obj_get_float(x_item);
}
}
#if ULAB_HAS_FUNCTION_ITERATOR
size_t *ndarray_new_coords(uint8_t ndim) {
size_t *coords = m_new0(size_t, ndim);
return coords;
}
void ndarray_rewind_array(uint8_t ndim, uint8_t *array, size_t *shape, int32_t *strides, size_t *coords) {
// resets the data pointer of a single array, whenever an axis is full
// since we always iterate over the very last axis, we have to keep track of
// the last ndim-2 axes only
array -= shape[ULAB_MAX_DIMS - 1] * strides[ULAB_MAX_DIMS - 1];
array += strides[ULAB_MAX_DIMS - 2];
for(uint8_t i=1; i < ndim-1; i++) {
coords[ULAB_MAX_DIMS - 1 - i] += 1;
if(coords[ULAB_MAX_DIMS - 1 - i] == shape[ULAB_MAX_DIMS - 1 - i]) { // we are at a dimension boundary
array -= shape[ULAB_MAX_DIMS - 1 - i] * strides[ULAB_MAX_DIMS - 1 - i];
array += strides[ULAB_MAX_DIMS - 2 - i];
coords[ULAB_MAX_DIMS - 1 - i] = 0;
coords[ULAB_MAX_DIMS - 2 - i] += 1;
} else { // coordinates can change only, if the last coordinate changes
return;
}
}
}
#endif
static int32_t *strides_from_shape(size_t *shape, uint8_t dtype) {
// returns a strides array that corresponds to a dense array with the prescribed shape
int32_t *strides = m_new(int32_t, ULAB_MAX_DIMS);
strides[ULAB_MAX_DIMS-1] = (int32_t)ulab_binary_get_size(dtype);
for(uint8_t i=ULAB_MAX_DIMS; i > 1; i--) {
strides[i-2] = strides[i-1] * shape[i-1];
}
return strides;
}
size_t *ndarray_shape_vector(size_t a, size_t b, size_t c, size_t d) {
// returns a ULAB_MAX_DIMS-aware array of shapes
// WARNING: this assumes that the maximum possible dimension is 4!
size_t *shape = m_new(size_t, ULAB_MAX_DIMS);
shape[ULAB_MAX_DIMS - 1] = d;
#if ULAB_MAX_DIMS > 1
shape[ULAB_MAX_DIMS - 2] = c;
#endif
#if ULAB_MAX_DIMS > 2
shape[ULAB_MAX_DIMS - 3] = b;
#endif
#if ULAB_MAX_DIMS > 3
shape[ULAB_MAX_DIMS - 4] = a;
#endif
return shape;
}
bool ndarray_object_is_array_like(mp_obj_t o_in) {
if(mp_obj_is_type(o_in, &ulab_ndarray_type) ||
mp_obj_is_type(o_in, &mp_type_tuple) ||
mp_obj_is_type(o_in, &mp_type_list) ||
mp_obj_is_type(o_in, &mp_type_range)) {
return true;
}
return false;
}
void fill_array_iterable(mp_float_t *array, mp_obj_t iterable) {
mp_obj_iter_buf_t x_buf;
mp_obj_t x_item, x_iterable = mp_getiter(iterable, &x_buf);
size_t i=0;
while ((x_item = mp_iternext(x_iterable)) != MP_OBJ_STOP_ITERATION) {
array[i] = (mp_float_t)mp_obj_get_float(x_item);
i++;
}
}
#if NDARRAY_HAS_DTYPE
#if ULAB_HAS_DTYPE_OBJECT
void ndarray_dtype_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
dtype_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_print_str(print, "dtype('");
if(self->dtype == NDARRAY_BOOLEAN) {
mp_print_str(print, "bool')");
} else if(self->dtype == NDARRAY_UINT8) {
mp_print_str(print, "uint8')");
} else if(self->dtype == NDARRAY_INT8) {
mp_print_str(print, "int8')");
} else if(self->dtype == NDARRAY_UINT16) {
mp_print_str(print, "uint16')");
} else if(self->dtype == NDARRAY_INT16) {
mp_print_str(print, "int16')");
}
#if ULAB_SUPPORTS_COMPLEX
else if(self->dtype == NDARRAY_COMPLEX) {
mp_print_str(print, "complex')");
}
#endif
else {
#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
mp_print_str(print, "float32')");
#else
mp_print_str(print, "float64')");
#endif
}
}
mp_obj_t ndarray_dtype_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
(void) type;
mp_arg_check_num(n_args, n_kw, 0, 1, true);
mp_map_t kw_args;
mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_, MP_ARG_OBJ, { .u_rom_obj = MP_ROM_NONE } },
};
mp_arg_val_t _args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args, args, &kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, _args);
dtype_obj_t *dtype = m_new_obj(dtype_obj_t);
dtype->base.type = &ulab_dtype_type;
if(mp_obj_is_type(args[0], &ulab_ndarray_type)) {
// return the dtype of the array
ndarray_obj_t *ndarray = MP_OBJ_TO_PTR(args[0]);
dtype->dtype = ndarray->dtype;
} else {
uint8_t _dtype;
if(mp_obj_is_int(_args[0].u_obj)) {
_dtype = mp_obj_get_int(_args[0].u_obj);
if((_dtype != NDARRAY_BOOL) && (_dtype != NDARRAY_UINT8)
&& (_dtype != NDARRAY_INT8) && (_dtype != NDARRAY_UINT16)
&& (_dtype != NDARRAY_INT16) && (_dtype != NDARRAY_FLOAT)) {
mp_raise_TypeError(translate("data type not understood"));
}
} else {
GET_STR_DATA_LEN(_args[0].u_obj, _dtype_, len);
if(memcmp(_dtype_, "uint8", 5) == 0) {
_dtype = NDARRAY_UINT8;
} else if(memcmp(_dtype_, "int8", 4) == 0) {
_dtype = NDARRAY_INT8;
} else if(memcmp(_dtype_, "uint16", 6) == 0) {
_dtype = NDARRAY_UINT16;
} else if(memcmp(_dtype_, "int16", 5) == 0) {
_dtype = NDARRAY_INT16;
} else if(memcmp(_dtype_, "float", 5) == 0) {
_dtype = NDARRAY_FLOAT;
}
#if ULAB_SUPPORTS_COMPLEX
else if(memcmp(_dtype_, "complex", 7) == 0) {
_dtype = NDARRAY_COMPLEX;
}
#endif
else {
mp_raise_TypeError(translate("data type not understood"));
}
}
dtype->dtype = _dtype;
}
return MP_OBJ_FROM_PTR(dtype);
}
mp_obj_t ndarray_dtype(mp_obj_t self_in) {
ndarray_obj_t *self = MP_OBJ_TO_PTR(self_in);
dtype_obj_t *dtype = m_new_obj(dtype_obj_t);
dtype->base.type = &ulab_dtype_type;
dtype->dtype = self->dtype;
return MP_OBJ_FROM_PTR(dtype);
}
#else
// this is the cheap implementation of tbe dtype
mp_obj_t ndarray_dtype(mp_obj_t self_in) {
uint8_t dtype;
if(mp_obj_is_type(self_in, &ulab_ndarray_type)) {
ndarray_obj_t *self = MP_OBJ_TO_PTR(self_in);
dtype = self->dtype;
} else { // we assume here that the input is a single character
GET_STR_DATA_LEN(self_in, _dtype, len);
if((len != 1) || ((*_dtype != NDARRAY_BOOL) && (*_dtype != NDARRAY_UINT8)
&& (*_dtype != NDARRAY_INT8) && (*_dtype != NDARRAY_UINT16)
&& (*_dtype != NDARRAY_INT16) && (*_dtype != NDARRAY_FLOAT)
#if ULAB_SUPPORTS_COMPLEX
&& (*_dtype != NDARRAY_COMPLEX)
#endif
)) {
mp_raise_TypeError(translate("data type not understood"));
}
dtype = *_dtype;
}
return mp_obj_new_int(dtype);
}
#endif /* ULAB_HAS_DTYPE_OBJECT */
#endif /* NDARRAY_HAS_DTYPE */
#if ULAB_HAS_PRINTOPTIONS
mp_obj_t ndarray_set_printoptions(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_threshold, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
{ MP_QSTR_edgeitems, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
if(args[0].u_obj != mp_const_none) {
ndarray_print_threshold = mp_obj_get_int(args[0].u_obj);
}
if(args[1].u_obj != mp_const_none) {
ndarray_print_edgeitems = mp_obj_get_int(args[1].u_obj);
}
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_KW(ndarray_set_printoptions_obj, 0, ndarray_set_printoptions);
mp_obj_t ndarray_get_printoptions(void) {
mp_obj_t dict = mp_obj_new_dict(2);
mp_obj_dict_store(MP_OBJ_FROM_PTR(dict), MP_OBJ_NEW_QSTR(MP_QSTR_threshold), mp_obj_new_int(ndarray_print_threshold));
mp_obj_dict_store(MP_OBJ_FROM_PTR(dict), MP_OBJ_NEW_QSTR(MP_QSTR_edgeitems), mp_obj_new_int(ndarray_print_edgeitems));
return dict;
}
MP_DEFINE_CONST_FUN_OBJ_0(ndarray_get_printoptions_obj, ndarray_get_printoptions);
#endif
mp_obj_t ndarray_get_item(ndarray_obj_t *ndarray, void *array) {
// returns a proper micropython object from an array
if(!ndarray->boolean) {
#if ULAB_SUPPORTS_COMPLEX
if(ndarray->dtype == NDARRAY_COMPLEX) {
mp_float_t *c = (mp_float_t *)array;
mp_float_t real = *c++;
mp_float_t imag = *c;
return mp_obj_new_complex(real, imag);
}
#endif
return mp_binary_get_val_array(ndarray->dtype, array, 0);
} else {
if(*(uint8_t *)array) {
return mp_const_true;
} else {
return mp_const_false;
}
}
}
static void ndarray_print_element(const mp_print_t *print, ndarray_obj_t *ndarray, uint8_t *array) {
#if ULAB_SUPPORTS_COMPLEX
if(ndarray->dtype == NDARRAY_COMPLEX) {
// real part first
mp_float_t fvalue = *(mp_float_t *)array;
mp_obj_print_helper(print, mp_obj_new_float(fvalue), PRINT_REPR);
// imaginary part
array += ndarray->itemsize / 2;
fvalue = *(mp_float_t *)array;
if(fvalue >= MICROPY_FLOAT_CONST(0.0) || isnan(fvalue)) {
mp_print_str(print, "+");
}
array += ndarray->itemsize / 2;
mp_obj_print_helper(print, mp_obj_new_float(fvalue), PRINT_REPR);
mp_print_str(print, "j");
} else {
mp_obj_print_helper(print, ndarray_get_item(ndarray, array), PRINT_REPR);
}
#else
mp_obj_print_helper(print, ndarray_get_item(ndarray, array), PRINT_REPR);
#endif
}
static void ndarray_print_row(const mp_print_t *print, ndarray_obj_t *ndarray, uint8_t *array, int32_t stride, size_t n) {
if(n == 0) {
return;
}
mp_print_str(print, "[");
if((n <= ndarray_print_threshold) || (n <= 2*ndarray_print_edgeitems)) { // if the array is short, print everything
ndarray_print_element(print, ndarray, array);
array += stride;
for(size_t i=1; i < n; i++, array += stride) {
mp_print_str(print, ", ");
ndarray_print_element(print, ndarray, array);
}
} else {
ndarray_print_element(print, ndarray, array);
array += stride;
for(size_t i=1; i < ndarray_print_edgeitems; i++, array += stride) {
mp_print_str(print, ", ");
ndarray_print_element(print, ndarray, array);
}
mp_printf(print, ", ..., ");
array += stride * (n - 2 * ndarray_print_edgeitems);
ndarray_print_element(print, ndarray, array);
array += stride;
for(size_t i=1; i < ndarray_print_edgeitems; i++, array += stride) {
mp_print_str(print, ", ");
ndarray_print_element(print, ndarray, array);
}
}
mp_print_str(print, "]");
}
#if ULAB_MAX_DIMS > 1
static void ndarray_print_bracket(const mp_print_t *print, const size_t condition, const size_t shape, const char *string) {
if(condition < shape) {
mp_print_str(print, string);
}
}
#endif
void ndarray_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
ndarray_obj_t *self = MP_OBJ_TO_PTR(self_in);
uint8_t *array = (uint8_t *)self->array;
mp_print_str(print, "array(");
if(self->len == 0) {
mp_print_str(print, "[]");
if(self->ndim > 1) {
mp_print_str(print, ", shape=(");
#if ULAB_MAX_DIMS > 1
for(uint8_t ndim = self->ndim; ndim > 1; ndim--) {
mp_printf(MP_PYTHON_PRINTER, "%d,", self->shape[ULAB_MAX_DIMS - ndim]);
}
#else
mp_printf(MP_PYTHON_PRINTER, "%d,", self->shape[0]);
#endif
mp_printf(MP_PYTHON_PRINTER, "%d)", self->shape[ULAB_MAX_DIMS - 1]);
}
} else {
#if ULAB_MAX_DIMS > 3
size_t i=0;
ndarray_print_bracket(print, 0, self->shape[ULAB_MAX_DIMS-4], "[");
do {
#endif
#if ULAB_MAX_DIMS > 2
size_t j = 0;
ndarray_print_bracket(print, 0, self->shape[ULAB_MAX_DIMS-3], "[");
do {
#endif
#if ULAB_MAX_DIMS > 1
size_t k = 0;
ndarray_print_bracket(print, 0, self->shape[ULAB_MAX_DIMS-2], "[");
do {
#endif
ndarray_print_row(print, self, array, self->strides[ULAB_MAX_DIMS-1], self->shape[ULAB_MAX_DIMS-1]);
#if ULAB_MAX_DIMS > 1
array += self->strides[ULAB_MAX_DIMS-2];
k++;
ndarray_print_bracket(print, k, self->shape[ULAB_MAX_DIMS-2], ",\n ");
} while(k < self->shape[ULAB_MAX_DIMS-2]);
ndarray_print_bracket(print, 0, self->shape[ULAB_MAX_DIMS-2], "]");
#endif
#if ULAB_MAX_DIMS > 2
j++;
ndarray_print_bracket(print, j, self->shape[ULAB_MAX_DIMS-3], ",\n\n ");
array -= self->strides[ULAB_MAX_DIMS-2] * self->shape[ULAB_MAX_DIMS-2];
array += self->strides[ULAB_MAX_DIMS-3];
} while(j < self->shape[ULAB_MAX_DIMS-3]);
ndarray_print_bracket(print, 0, self->shape[ULAB_MAX_DIMS-3], "]");
#endif
#if ULAB_MAX_DIMS > 3
array -= self->strides[ULAB_MAX_DIMS-3] * self->shape[ULAB_MAX_DIMS-3];
array += self->strides[ULAB_MAX_DIMS-4];
i++;
ndarray_print_bracket(print, i, self->shape[ULAB_MAX_DIMS-4], ",\n\n ");
} while(i < self->shape[ULAB_MAX_DIMS-4]);
ndarray_print_bracket(print, 0, self->shape[ULAB_MAX_DIMS-4], "]");
#endif
}
mp_print_str(print, ", dtype=");
if(self->boolean) {
mp_print_str(print, "bool)");
} else if(self->dtype == NDARRAY_UINT8) {
mp_print_str(print, "uint8)");
} else if(self->dtype == NDARRAY_INT8) {
mp_print_str(print, "int8)");
} else if(self->dtype == NDARRAY_UINT16) {
mp_print_str(print, "uint16)");
} else if(self->dtype == NDARRAY_INT16) {
mp_print_str(print, "int16)");
}
#if ULAB_SUPPORTS_COMPLEX
else if(self->dtype == NDARRAY_COMPLEX) {
mp_print_str(print, "complex)");
}
#endif /* ULAB_SUPPORTS_COMPLEX */
else {
#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
mp_print_str(print, "float32)");
#else
mp_print_str(print, "float64)");
#endif
}
}
void ndarray_assign_elements(ndarray_obj_t *ndarray, mp_obj_t iterable, uint8_t dtype, size_t *idx) {
// assigns a single row in the tensor
mp_obj_t item;
if(ndarray->boolean) {
uint8_t *array = (uint8_t *)ndarray->array;
array += *idx;
while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
if(mp_obj_is_true(item)) {
*array = 1;
}
array++;
(*idx)++;
}
} else {
while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
#if ULAB_SUPPORTS_COMPLEX
mp_float_t real;
mp_float_t imag;
if(dtype == NDARRAY_COMPLEX) {
mp_obj_get_complex(item, &real, &imag);
ndarray_set_value(NDARRAY_FLOAT, ndarray->array, (*idx)++, mp_obj_new_float(real));
ndarray_set_value(NDARRAY_FLOAT, ndarray->array, (*idx)++, mp_obj_new_float(imag));
} else {
ndarray_set_value(dtype, ndarray->array, (*idx)++, item);
}
#else
ndarray_set_value(dtype, ndarray->array, (*idx)++, item);
#endif
}
}
}
bool ndarray_is_dense(ndarray_obj_t *ndarray) {
// returns true, if the array is dense, false otherwise
// the array should be dense, if the very first stride can be calculated from shape
int32_t stride = ndarray->itemsize;
for(uint8_t i = ULAB_MAX_DIMS - 1; i > ULAB_MAX_DIMS-ndarray->ndim; i--) {
stride *= ndarray->shape[i];
}
return stride == ndarray->strides[ULAB_MAX_DIMS-ndarray->ndim] ? true : false;
}
static size_t multiply_size(size_t a, size_t b) {
size_t result;
if (__builtin_mul_overflow(a, b, &result)) {
mp_raise_ValueError(translate("array is too big"));
}
return result;
}
ndarray_obj_t *ndarray_new_ndarray(uint8_t ndim, size_t *shape, int32_t *strides, uint8_t dtype) {
// Creates the base ndarray with shape, and initialises the values to straight 0s
ndarray_obj_t *ndarray = m_new_obj(ndarray_obj_t);
ndarray->base.type = &ulab_ndarray_type;
ndarray->dtype = dtype == NDARRAY_BOOL ? NDARRAY_UINT8 : dtype;
ndarray->boolean = dtype == NDARRAY_BOOL ? NDARRAY_BOOLEAN : NDARRAY_NUMERIC;
ndarray->ndim = ndim;
ndarray->len = ndim == 0 ? 0 : 1;
ndarray->itemsize = ulab_binary_get_size(dtype);
int32_t *_strides;
if(strides == NULL) {
_strides = strides_from_shape(shape, ndarray->dtype);
} else {
_strides = strides;
}
for(uint8_t i=ULAB_MAX_DIMS; i > ULAB_MAX_DIMS-ndim; i--) {
ndarray->shape[i-1] = shape[i-1];
ndarray->strides[i-1] = _strides[i-1];
ndarray->len = multiply_size(ndarray->len, shape[i-1]);
}
// if the length is 0, still allocate a single item, so that contractions can be handled
size_t len = multiply_size(ndarray->itemsize, MAX(1, ndarray->len));
uint8_t *array = m_new0(byte, len);
// this should set all elements to 0, irrespective of the of the dtype (all bits are zero)
// we could, perhaps, leave this step out, and initialise the array only, when needed
ndarray->array = array;
ndarray->origin = array;
return ndarray;
}
ndarray_obj_t *ndarray_new_dense_ndarray(uint8_t ndim, size_t *shape, uint8_t dtype) {
// creates a dense array, i.e., one, where the strides are derived directly from the shapes
// the function should work in the general n-dimensional case
int32_t *strides = m_new(int32_t, ULAB_MAX_DIMS);
strides[ULAB_MAX_DIMS-1] = (int32_t)ulab_binary_get_size(dtype);
for(size_t i=ULAB_MAX_DIMS; i > 1; i--) {
strides[i-2] = strides[i-1] * MAX(1, shape[i-1]);
}
return ndarray_new_ndarray(ndim, shape, strides, dtype);
}
ndarray_obj_t *ndarray_new_ndarray_from_tuple(mp_obj_tuple_t *_shape, uint8_t dtype) {
// creates a dense array from a tuple
// the function should work in the general n-dimensional case
size_t *shape = m_new(size_t, ULAB_MAX_DIMS);
for(size_t i=0; i < ULAB_MAX_DIMS; i++) {
if(i < ULAB_MAX_DIMS - _shape->len) {
shape[i] = 0;
} else {
shape[i] = mp_obj_get_int(_shape->items[i]);
}
}
return ndarray_new_dense_ndarray(_shape->len, shape, dtype);
}
void ndarray_copy_array(ndarray_obj_t *source, ndarray_obj_t *target, uint8_t shift) {
// TODO: if the array is dense, the content could be copied in a single pass
// copies the content of source->array into a new dense void pointer
// it is assumed that the dtypes in source and target are the same
// Since the target is a new array, it is supposed to be dense
uint8_t *sarray = (uint8_t *)source->array;
uint8_t *tarray = (uint8_t *)target->array;
#if ULAB_SUPPORTS_COMPLEX
if(source->dtype == NDARRAY_COMPLEX) {
sarray += shift;
}
#endif
#if ULAB_MAX_DIMS > 3
size_t i = 0;
do {
#endif
#if ULAB_MAX_DIMS > 2
size_t j = 0;
do {
#endif
#if ULAB_MAX_DIMS > 1
size_t k = 0;
do {
#endif
size_t l = 0;
do {
memcpy(tarray, sarray, target->itemsize);
tarray += target->itemsize;
sarray += source->strides[ULAB_MAX_DIMS - 1];
l++;
} while(l < source->shape[ULAB_MAX_DIMS - 1]);
#if ULAB_MAX_DIMS > 1
sarray -= source->strides[ULAB_MAX_DIMS - 1] * source->shape[ULAB_MAX_DIMS-1];
sarray += source->strides[ULAB_MAX_DIMS - 2];
k++;
} while(k < source->shape[ULAB_MAX_DIMS - 2]);
#endif
#if ULAB_MAX_DIMS > 2
sarray -= source->strides[ULAB_MAX_DIMS - 2] * source->shape[ULAB_MAX_DIMS-2];
sarray += source->strides[ULAB_MAX_DIMS - 3];
j++;
} while(j < source->shape[ULAB_MAX_DIMS - 3]);
#endif
#if ULAB_MAX_DIMS > 3
sarray -= source->strides[ULAB_MAX_DIMS - 3] * source->shape[ULAB_MAX_DIMS-3];
sarray += source->strides[ULAB_MAX_DIMS - 4];
i++;
} while(i < source->shape[ULAB_MAX_DIMS - 4]);
#endif
}
ndarray_obj_t *ndarray_new_view(ndarray_obj_t *source, uint8_t ndim, size_t *shape, int32_t *strides, int32_t offset) {
// creates a new view from the input arguments
ndarray_obj_t *ndarray = m_new_obj(ndarray_obj_t);
ndarray->base.type = &ulab_ndarray_type;
ndarray->boolean = source->boolean;
ndarray->dtype = source->dtype;
ndarray->ndim = ndim;
ndarray->itemsize = source->itemsize;
ndarray->len = ndim == 0 ? 0 : 1;
for(uint8_t i=ULAB_MAX_DIMS; i > ULAB_MAX_DIMS-ndim; i--) {
ndarray->shape[i-1] = shape[i-1];
ndarray->strides[i-1] = strides[i-1];
ndarray->len *= shape[i-1];
}
uint8_t *pointer = (uint8_t *)source->array;
pointer += offset;
ndarray->array = pointer;
ndarray->origin = source->origin;
return ndarray;
}
ndarray_obj_t *ndarray_copy_view(ndarray_obj_t *source) {
// creates a one-to-one deep copy of the input ndarray or its view
// the function should work in the general n-dimensional case
// In order to make it dtype-agnostic, we copy the memory content
// instead of reading out the values
int32_t *strides = strides_from_shape(source->shape, source->dtype);
uint8_t dtype = source->dtype;
if(source->boolean) {
dtype = NDARRAY_BOOL;
}
ndarray_obj_t *ndarray = ndarray_new_ndarray(source->ndim, source->shape, strides, dtype);
ndarray_copy_array(source, ndarray, 0);
return ndarray;
}
ndarray_obj_t *ndarray_copy_view_convert_type(ndarray_obj_t *source, uint8_t dtype) {
// creates a copy, similar to ndarray_copy_view, but it also converts the dtype, if necessary
if(dtype == source->dtype) {
return ndarray_copy_view(source);
}
ndarray_obj_t *ndarray = ndarray_new_dense_ndarray(source->ndim, source->shape, dtype);
uint8_t *sarray = (uint8_t *)source->array;
uint8_t *array = (uint8_t *)ndarray->array;
#if ULAB_SUPPORTS_COMPLEX
uint8_t complex_size = 2 * sizeof(mp_float_t);
#endif
#if ULAB_MAX_DIMS > 3
size_t i = 0;
do {
#endif
#if ULAB_MAX_DIMS > 2
size_t j = 0;
do {
#endif
#if ULAB_MAX_DIMS > 1
size_t k = 0;
do {
#endif
size_t l = 0;
do {
mp_obj_t item;
#if ULAB_SUPPORTS_COMPLEX
if(source->dtype == NDARRAY_COMPLEX) {
if(dtype != NDARRAY_COMPLEX) {
mp_raise_TypeError(translate("cannot convert complex type"));
} else {
memcpy(array, sarray, complex_size);
}
} else {
#endif
if((source->dtype == NDARRAY_FLOAT) && (dtype != NDARRAY_FLOAT)) {
// floats must be treated separately, because they can't directly be converted to integer types
mp_float_t f = ndarray_get_float_value(sarray, source->dtype);
item = mp_obj_new_int((int32_t)MICROPY_FLOAT_C_FUN(round)(f));
} else {
item = mp_binary_get_val_array(source->dtype, sarray, 0);
}
#if ULAB_SUPPORTS_COMPLEX
if(dtype == NDARRAY_COMPLEX) {
ndarray_set_value(NDARRAY_FLOAT, array, 0, item);
} else {
ndarray_set_value(dtype, array, 0, item);
}
}
#else
ndarray_set_value(dtype, array, 0, item);
#endif
array += ndarray->itemsize;
sarray += source->strides[ULAB_MAX_DIMS - 1];
l++;
} while(l < source->shape[ULAB_MAX_DIMS - 1]);
#if ULAB_MAX_DIMS > 1
sarray -= source->strides[ULAB_MAX_DIMS - 1] * source->shape[ULAB_MAX_DIMS-1];
sarray += source->strides[ULAB_MAX_DIMS - 2];
k++;
} while(k < source->shape[ULAB_MAX_DIMS - 2]);
#endif
#if ULAB_MAX_DIMS > 2
sarray -= source->strides[ULAB_MAX_DIMS - 2] * source->shape[ULAB_MAX_DIMS-2];
sarray += source->strides[ULAB_MAX_DIMS - 3];
j++;
} while(j < source->shape[ULAB_MAX_DIMS - 3]);
#endif
#if ULAB_MAX_DIMS > 3
sarray -= source->strides[ULAB_MAX_DIMS - 3] * source->shape[ULAB_MAX_DIMS-3];
sarray += source->strides[ULAB_MAX_DIMS - 4];
i++;
} while(i < source->shape[ULAB_MAX_DIMS - 4]);
#endif
return ndarray;
}
#if NDARRAY_HAS_BYTESWAP
mp_obj_t ndarray_byteswap(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
// changes the endiannes of an array
// if the dtype of the input uint8/int8/bool, simply return a copy or view
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_, MP_ARG_REQUIRED | MP_ARG_OBJ, { .u_rom_obj = MP_ROM_NONE } },
{ MP_QSTR_inplace, MP_ARG_KW_ONLY | MP_ARG_OBJ, { .u_rom_obj = MP_ROM_FALSE } },
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
ndarray_obj_t *self = MP_OBJ_TO_PTR(args[0].u_obj);
ndarray_obj_t *ndarray = NULL;
if(args[1].u_obj == mp_const_false) {
ndarray = ndarray_copy_view(self);
} else {
ndarray = ndarray_new_view(self, self->ndim, self->shape, self->strides, 0);
}
if((self->dtype == NDARRAY_BOOL) || (self->dtype == NDARRAY_UINT8) || (self->dtype == NDARRAY_INT8)) {
return MP_OBJ_FROM_PTR(ndarray);
} else {
uint8_t *array = (uint8_t *)ndarray->array;
#if ULAB_MAX_DIMS > 3
size_t i = 0;
do {
#endif
#if ULAB_MAX_DIMS > 2
size_t j = 0;
do {
#endif
#if ULAB_MAX_DIMS > 1
size_t k = 0;
do {
#endif
size_t l = 0;
do {
if(self->dtype == NDARRAY_FLOAT) {
#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
SWAP(uint8_t, array[0], array[3]);
SWAP(uint8_t, array[1], array[2]);
#else
SWAP(uint8_t, array[0], array[7]);
SWAP(uint8_t, array[1], array[6]);
SWAP(uint8_t, array[2], array[5]);
SWAP(uint8_t, array[3], array[4]);
#endif
} else {
SWAP(uint8_t, array[0], array[1]);
}
array += ndarray->strides[ULAB_MAX_DIMS - 1];
l++;
} while(l < ndarray->shape[ULAB_MAX_DIMS - 1]);
#if ULAB_MAX_DIMS > 1
array -= ndarray->strides[ULAB_MAX_DIMS - 1] * ndarray->shape[ULAB_MAX_DIMS-1];
array += ndarray->strides[ULAB_MAX_DIMS - 2];
k++;
} while(k < ndarray->shape[ULAB_MAX_DIMS - 2]);
#endif
#if ULAB_MAX_DIMS > 2
array -= ndarray->strides[ULAB_MAX_DIMS - 2] * ndarray->shape[ULAB_MAX_DIMS-2];
array += ndarray->strides[ULAB_MAX_DIMS - 3];
j++;
} while(j < ndarray->shape[ULAB_MAX_DIMS - 3]);
#endif
#if ULAB_MAX_DIMS > 3
array -= ndarray->strides[ULAB_MAX_DIMS - 3] * ndarray->shape[ULAB_MAX_DIMS-3];
array += ndarray->strides[ULAB_MAX_DIMS - 4];
i++;
} while(i < ndarray->shape[ULAB_MAX_DIMS - 4]);
#endif
}
return MP_OBJ_FROM_PTR(ndarray);
}
MP_DEFINE_CONST_FUN_OBJ_KW(ndarray_byteswap_obj, 1, ndarray_byteswap);
#endif
#if NDARRAY_HAS_COPY
mp_obj_t ndarray_copy(mp_obj_t self_in) {
ndarray_obj_t *self = MP_OBJ_TO_PTR(self_in);
return MP_OBJ_FROM_PTR(ndarray_copy_view(self));
}
MP_DEFINE_CONST_FUN_OBJ_1(ndarray_copy_obj, ndarray_copy);
#endif
ndarray_obj_t *ndarray_new_linear_array(size_t len, uint8_t dtype) {
size_t *shape = m_new(size_t, ULAB_MAX_DIMS);
if(len == 0) {
return ndarray_new_dense_ndarray(0, shape, dtype);
}
shape[ULAB_MAX_DIMS-1] = len;
return ndarray_new_dense_ndarray(1, shape, dtype);
}
ndarray_obj_t *ndarray_from_iterable(mp_obj_t obj, uint8_t dtype) {
// returns an ndarray from an iterable micropython object
// if the input is an ndarray, returns the input...
if(mp_obj_is_type(obj, &ulab_ndarray_type)) {
return MP_OBJ_TO_PTR(obj);
}
// ... otherwise, takes the values from the iterable, and creates the corresponding ndarray
// First, we have to figure out, whether the elements of the iterable are iterables themself
uint8_t ndim = 0;
size_t shape[ULAB_MAX_DIMS];
mp_obj_iter_buf_t iter_buf[ULAB_MAX_DIMS];
mp_obj_t iterable[ULAB_MAX_DIMS];
// inspect only the very first element in each dimension; this is fast,
// but not completely safe, e.g., length compatibility is not checked
mp_obj_t item = obj;
while(1) {
if(mp_obj_len_maybe(item) == MP_OBJ_NULL) {
break;
}
if(ndim == ULAB_MAX_DIMS) {
mp_raise_ValueError(translate("too many dimensions"));
}
shape[ndim] = MP_OBJ_SMALL_INT_VALUE(mp_obj_len_maybe(item));
if(shape[ndim] == 0) {
ndim++;
break;
}
iterable[ndim] = mp_getiter(item, &iter_buf[ndim]);
item = mp_iternext(iterable[ndim]);
ndim++;
}
for(uint8_t i = 0; i < ndim; i++) {
// align all values to the right
shape[ULAB_MAX_DIMS - i - 1] = shape[ndim - 1 - i];
}
ndarray_obj_t *ndarray = ndarray_new_dense_ndarray(ndim, shape, dtype);
item = obj;
for(uint8_t i = 0; i < ndim - 1; i++) {
// if ndim > 1, descend into the hierarchy
iterable[ULAB_MAX_DIMS - ndim + i] = mp_getiter(item, &iter_buf[ULAB_MAX_DIMS - ndim + i]);
item = mp_iternext(iterable[ULAB_MAX_DIMS - ndim + i]);
}
size_t idx = 0;
// TODO: this could surely be done in a more elegant way...
#if ULAB_MAX_DIMS > 3
do {
#endif
#if ULAB_MAX_DIMS > 2
do {
#endif
#if ULAB_MAX_DIMS > 1
do {
#endif
iterable[ULAB_MAX_DIMS - 1] = mp_getiter(item, &iter_buf[ULAB_MAX_DIMS - 1]);
ndarray_assign_elements(ndarray, iterable[ULAB_MAX_DIMS - 1], ndarray->dtype, &idx);
#if ULAB_MAX_DIMS > 1
item = ndim > 1 ? mp_iternext(iterable[ULAB_MAX_DIMS - 2]) : MP_OBJ_STOP_ITERATION;
} while(item != MP_OBJ_STOP_ITERATION);
#endif
#if ULAB_MAX_DIMS > 2
item = ndim > 2 ? mp_iternext(iterable[ULAB_MAX_DIMS - 3]) : MP_OBJ_STOP_ITERATION;
if(item != MP_OBJ_STOP_ITERATION) {
iterable[ULAB_MAX_DIMS - 2] = mp_getiter(item, &iter_buf[ULAB_MAX_DIMS - 2]);
item = mp_iternext(iterable[ULAB_MAX_DIMS - 2]);
} else {
iterable[ULAB_MAX_DIMS - 2] = MP_OBJ_STOP_ITERATION;
}
} while(iterable[ULAB_MAX_DIMS - 2] != MP_OBJ_STOP_ITERATION);
#endif
#if ULAB_MAX_DIMS > 3
item = ndim > 3 ? mp_iternext(iterable[ULAB_MAX_DIMS - 4]) : MP_OBJ_STOP_ITERATION;
if(item != MP_OBJ_STOP_ITERATION) {