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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
|
ndarray, the base class
=======================
The ``ndarray`` is the underlying container of numerical data. It can be
thought of as micropython’s own ``array`` object, but has a great number
of extra features starting with how it can be initialised, which
operations can be done on it, and which functions can accept it as an
argument. One important property of an ``ndarray`` is that it is also a
proper ``micropython`` iterable.
The ``ndarray`` consists of a short header, and a pointer that holds the
data. The pointer always points to a contiguous segment in memory
(``numpy`` is more flexible in this regard), and the header tells the
interpreter, how the data from this segment is to be read out, and what
the bytes mean. Some operations, e.g., ``reshape``, are fast, because
they do not operate on the data, they work on the header, and therefore,
only a couple of bytes are manipulated, even if there are a million data
entries. A more detailed exposition of how operators are implemented can
be found in the section titled `Programming ulab <#Programming_ula>`__.
Since the ``ndarray`` is a binary container, it is also compact, meaning
that it takes only a couple of bytes of extra RAM in addition to what is
required for storing the numbers themselves. ``ndarray``\ s are also
type-aware, i.e., one can save RAM by specifying a data type, and using
the smallest reasonable one. Five such types are defined, namely
``uint8``, ``int8``, which occupy a single byte of memory per datum,
``uint16``, and ``int16``, which occupy two bytes per datum, and
``float``, which occupies four or eight bytes per datum. The
precision/size of the ``float`` type depends on the definition of
``mp_float_t``. Some platforms, e.g., the PYBD, implement ``double``\ s,
but some, e.g., the pyboard.v.11, do not. You can find out, what type of
float your particular platform implements by looking at the output of
the `.itemsize <#.itemsize>`__ class property, or looking at the exact
``dtype``, when you print out an array.
In addition to the five above-mentioned numerical types, it is also
possible to define Boolean arrays, which can be used in the indexing of
data. However, Boolean arrays are really nothing but arrays of type
``uint8`` with an extra flag.
On the following pages, we will see how one can work with
``ndarray``\ s. Those familiar with ``numpy`` should find that the
nomenclature and naming conventions of ``numpy`` are adhered to as
closely as possible. We will point out the few differences, where
necessary.
For the sake of comparison, in addition to the ``ulab`` code snippets,
sometimes the equivalent ``numpy`` code is also presented. You can find
out, where the snippet is supposed to run by looking at its first line,
the header of the code block.
The ndinfo function
-------------------
A concise summary of a couple of the properties of an ``ndarray`` can be
printed out by calling the ``ndinfo`` function. In addition to finding
out what the *shape* and *strides* of the array array, we also get the
``itemsize``, as well as the type. An interesting piece of information
is the *data pointer*, which tells us, what the address of the data
segment of the ``ndarray`` is. We will see the significance of this in
the section `Slicing and indexing <#Slicing-and-indexing>`__.
Note that this function simply prints some information, but does not
return anything. If you need to get a handle of the data contained in
the printout, you should call the dedicated ``shape``, ``strides``, or
``itemsize`` functions directly.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(5), dtype=np.float)
b = np.array(range(25), dtype=np.uint8).reshape((5, 5))
np.ndinfo(a)
print('\n')
np.ndinfo(b)
.. parsed-literal::
class: ndarray
shape: (5,)
strides: (8,)
itemsize: 8
data pointer: 0x7f8f6fa2e240
type: float
class: ndarray
shape: (5, 5)
strides: (5, 1)
itemsize: 1
data pointer: 0x7f8f6fa2e2e0
type: uint8
Initialising an array
---------------------
A new array can be created by passing either a standard micropython
iterable, or another ``ndarray`` into the constructor.
Initialising by passing iterables
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the iterable is one-dimensional, i.e., one whose elements are
numbers, then a row vector will be created and returned. If the iterable
is two-dimensional, i.e., one whose elements are again iterables, a
matrix will be created. If the lengths of the iterables are not
consistent, a ``ValueError`` will be raised. Iterables of different
types can be mixed in the initialisation function.
If the ``dtype`` keyword with the possible
``uint8/int8/uint16/int16/float`` values is supplied, the new
``ndarray`` will have that type, otherwise, it assumes ``float`` as
default. In addition, if ``ULAB_SUPPORTS_COMPLEX`` is set to 1 in
`ulab.h <https://github.com/v923z/micropython-ulab/blob/master/code/ulab.h>`__,
the ``dtype`` can also take on the value of ``complex``.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = np.array(a)
print("a:\t", a)
print("b:\t", b)
# a two-dimensional array with mixed-type initialisers
c = np.array([range(5), range(20, 25, 1), [44, 55, 66, 77, 88]], dtype=np.uint8)
print("\nc:\t", c)
# and now we throw an exception
d = np.array([range(5), range(10), [44, 55, 66, 77, 88]], dtype=np.uint8)
print("\nd:\t", d)
.. parsed-literal::
a: [1, 2, 3, 4, 5, 6, 7, 8]
b: array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], dtype=float64)
c: array([[0, 1, 2, 3, 4],
[20, 21, 22, 23, 24],
[44, 55, 66, 77, 88]], dtype=uint8)
Traceback (most recent call last):
File "/dev/shm/micropython.py", line 15, in <module>
ValueError: iterables are not of the same length
Initialising by passing arrays
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An ``ndarray`` can be initialised by supplying another array. This
statement is almost trivial, since ``ndarray``\ s are iterables
themselves, though it should be pointed out that initialising through
arrays is a bit faster. This statement is especially true, if the
``dtype``\ s of the source and output arrays are the same, because then
the contents can simply be copied without further ado. While type
conversion is also possible, it will always be slower than straight
copying.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = np.array(a)
c = np.array(b)
d = np.array(b, dtype=np.uint8)
print("a:\t", a)
print("\nb:\t", b)
print("\nc:\t", c)
print("\nd:\t", d)
.. parsed-literal::
a: [1, 2, 3, 4, 5, 6, 7, 8]
b: array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], dtype=float64)
c: array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], dtype=float64)
d: array([1, 2, 3, 4, 5, 6, 7, 8], dtype=uint8)
Note that the default type of the ``ndarray`` is ``float``. Hence, if
the array is initialised from another array, type conversion will always
take place, except, when the output type is specifically supplied. I.e.,
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(5), dtype=np.uint8)
b = np.array(a)
print("a:\t", a)
print("\nb:\t", b)
.. parsed-literal::
a: array([0, 1, 2, 3, 4], dtype=uint8)
b: array([0.0, 1.0, 2.0, 3.0, 4.0], dtype=float64)
will iterate over the elements in ``a``, since in the assignment
``b = np.array(a)``, no output type was given, therefore, ``float`` was
assumed. On the other hand,
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(5), dtype=np.uint8)
b = np.array(a, dtype=np.uint8)
print("a:\t", a)
print("\nb:\t", b)
.. parsed-literal::
a: array([0, 1, 2, 3, 4], dtype=uint8)
b: array([0, 1, 2, 3, 4], dtype=uint8)
will simply copy the content of ``a`` into ``b`` without any iteration,
and will, therefore, be faster. Keep this in mind, whenever the output
type, or performance is important.
Array initialisation functions
------------------------------
There are nine functions that can be used for initialising an array.
Starred functions accept ``complex`` as the value of the ``dtype``, if
the firmware was compiled with complex support.
1. `numpy.arange <#arange>`__
2. `numpy.concatenate <#concatenate>`__
3. `numpy.diag\* <#diag>`__
4. `numpy.empty\* <#empty>`__
5. `numpy.eye\* <#eye>`__
6. `numpy.frombuffer <#frombuffer>`__
7. `numpy.full\* <#full>`__
8. `numpy.linspace\* <#linspace>`__
9. `numpy.logspace <#logspace>`__
10. `numpy.ones\* <#ones>`__
11. `numpy.zeros\* <#zeros>`__
arange
~~~~~~
``numpy``:
https://numpy.org/doc/stable/reference/generated/numpy.arange.html
The function returns a one-dimensional array with evenly spaced values.
Takes 3 positional arguments (two are optional), and the ``dtype``
keyword argument.
.. code::
# code to be run in micropython
from ulab import numpy as np
print(np.arange(10))
print(np.arange(2, 10))
print(np.arange(2, 10, 3))
print(np.arange(2, 10, 3, dtype=np.float))
.. parsed-literal::
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int16)
array([2, 3, 4, 5, 6, 7, 8, 9], dtype=int16)
array([2, 5, 8], dtype=int16)
array([2.0, 5.0, 8.0], dtype=float64)
concatenate
~~~~~~~~~~~
``numpy``:
https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html
The function joins a sequence of arrays, if they are compatible in
shape, i.e., if all shapes except the one along the joining axis are
equal.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(25), dtype=np.uint8).reshape((5, 5))
b = np.array(range(15), dtype=np.uint8).reshape((3, 5))
c = np.concatenate((a, b), axis=0)
print(c)
.. parsed-literal::
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]], dtype=uint8)
**WARNING**: ``numpy`` accepts arbitrary ``dtype``\ s in the sequence of
arrays, in ``ulab`` the ``dtype``\ s must be identical. If you want to
concatenate different types, you have to convert all arrays to the same
type first. Here ``b`` is of ``float`` type, so it cannot directly be
concatenated to ``a``. However, if we cast the ``dtype`` of ``b``, the
concatenation works:
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(25), dtype=np.uint8).reshape((5, 5))
b = np.array(range(15), dtype=np.float).reshape((5, 3))
d = np.array(b+1, dtype=np.uint8)
print('a: ', a)
print('='*20 + '\nd: ', d)
c = np.concatenate((d, a), axis=1)
print('='*20 + '\nc: ', c)
.. parsed-literal::
a: array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]], dtype=uint8)
====================
d: array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
[13, 14, 15]], dtype=uint8)
====================
c: array([[1, 2, 3, 0, 1, 2, 3, 4],
[4, 5, 6, 5, 6, 7, 8, 9],
[7, 8, 9, 10, 11, 12, 13, 14],
[10, 11, 12, 15, 16, 17, 18, 19],
[13, 14, 15, 20, 21, 22, 23, 24]], dtype=uint8)
diag
----
``numpy``:
https://numpy.org/doc/stable/reference/generated/numpy.diag.html
Extract a diagonal, or construct a diagonal array.
The function takes two arguments, an ``ndarray``, and a shift. If the
first argument is a two-dimensional array, the function returns a
one-dimensional array containing the diagonal entries. The diagonal can
be shifted by an amount given in the second argument.
If the first argument is a one-dimensional array, the function returns a
two-dimensional tensor with its diagonal elements given by the first
argument.
The ``diag`` function can accept a complex array, if the firmware was
compiled with complex support.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3, 4])
print(np.diag(a))
.. parsed-literal::
array([[1.0, 0.0, 0.0, 0.0],
[0.0, 2.0, 0.0, 0.0],
[0.0, 0.0, 3.0, 0.0],
[0.0, 0.0, 0.0, 4.0]], dtype=float64)
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(16)).reshape((4, 4))
print('a: ', a)
print()
print('diagonal of a: ', np.diag(a))
.. parsed-literal::
a: array([[0.0, 1.0, 2.0, 3.0],
[4.0, 5.0, 6.0, 7.0],
[8.0, 9.0, 10.0, 11.0],
[12.0, 13.0, 14.0, 15.0]], dtype=float64)
diagonal of a: array([0.0, 5.0, 10.0, 15.0], dtype=float64)
empty
-----
``numpy``:
https://numpy.org/doc/stable/reference/generated/numpy.empty.html
``empty`` is simply an alias for ``zeros``, i.e., as opposed to
``numpy``, the entries of the tensor will be initialised to zero.
The ``empty`` function can accept complex as the value of the dtype, if
the firmware was compiled with complex support.
eye
~~~
``numpy``:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.eye.html
Another special array method is the ``eye`` function, whose call
signature is
.. code:: python
eye(N, M, k=0, dtype=float)
where ``N`` (``M``) specify the dimensions of the matrix (if only ``N``
is supplied, then we get a square matrix, otherwise one with ``M`` rows,
and ``N`` columns), and ``k`` is the shift of the ones (the main
diagonal corresponds to ``k=0``). Here are a couple of examples.
The ``eye`` function can accept ``complex`` as the value of the
``dtype``, if the firmware was compiled with complex support.
With a single argument
^^^^^^^^^^^^^^^^^^^^^^
.. code::
# code to be run in micropython
from ulab import numpy as np
print(np.eye(5))
.. parsed-literal::
array([[1.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 0.0, 1.0]], dtype=float64)
Specifying the dimensions of the matrix
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code::
# code to be run in micropython
from ulab import numpy as np
print(np.eye(4, M=6, k=-1, dtype=np.int16))
.. parsed-literal::
array([[0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0]], dtype=int16)
.. code::
# code to be run in micropython
from ulab import numpy as np
print(np.eye(4, M=6, dtype=np.int8))
.. parsed-literal::
array([[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0]], dtype=int8)
frombuffer
~~~~~~~~~~
``numpy``:
https://numpy.org/doc/stable/reference/generated/numpy.frombuffer.html
The function interprets a contiguous buffer as a one-dimensional array,
and thus can be used for piping buffered data directly into an array.
This method of analysing, e.g., ADC data is much more efficient than
passing the ADC buffer into the ``array`` constructor, because
``frombuffer`` simply creates the ``ndarray`` header and blindly copies
the memory segment, without inspecting the underlying data.
The function takes a single positional argument, the buffer, and three
keyword arguments. These are the ``dtype`` with a default value of
``float``, the ``offset``, with a default of 0, and the ``count``, with
a default of -1, meaning that all data are taken in.
.. code::
# code to be run in micropython
from ulab import numpy as np
buffer = b'\x01\x02\x03\x04\x05\x06\x07\x08'
print('buffer: ', buffer)
a = np.frombuffer(buffer, dtype=np.uint8)
print('a, all data read: ', a)
b = np.frombuffer(buffer, dtype=np.uint8, offset=2)
print('b, all data with an offset: ', b)
c = np.frombuffer(buffer, dtype=np.uint8, offset=2, count=3)
print('c, only 3 items with an offset: ', c)
.. parsed-literal::
buffer: b'\x01\x02\x03\x04\x05\x06\x07\x08'
a, all data read: array([1, 2, 3, 4, 5, 6, 7, 8], dtype=uint8)
b, all data with an offset: array([3, 4, 5, 6, 7, 8], dtype=uint8)
c, only 3 items with an offset: array([3, 4, 5], dtype=uint8)
full
~~~~
``numpy``:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html
The function returns an array of arbitrary dimension, whose elements are
all equal to the second positional argument. The first argument is a
tuple describing the shape of the tensor. The ``dtype`` keyword argument
with a default value of ``float`` can also be supplied.
The ``full`` function can accept a complex scalar, or ``complex`` as the
value of ``dtype``, if the firmware was compiled with complex support.
.. code::
# code to be run in micropython
from ulab import numpy as np
# create an array with the default type
print(np.full((2, 4), 3))
print('\n' + '='*20 + '\n')
# the array type is uint8 now
print(np.full((2, 4), 3, dtype=np.uint8))
.. parsed-literal::
array([[3.0, 3.0, 3.0, 3.0],
[3.0, 3.0, 3.0, 3.0]], dtype=float64)
====================
array([[3, 3, 3, 3],
[3, 3, 3, 3]], dtype=uint8)
linspace
~~~~~~~~
``numpy``:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html
This function returns an array, whose elements are uniformly spaced
between the ``start``, and ``stop`` points. The number of intervals is
determined by the ``num`` keyword argument, whose default value is 50.
With the ``endpoint`` keyword argument (defaults to ``True``) one can
include ``stop`` in the sequence. In addition, the ``dtype`` keyword can
be supplied to force type conversion of the output. The default is
``float``. Note that, when ``dtype`` is of integer type, the sequence is
not necessarily evenly spaced. This is not an error, rather a
consequence of rounding. (This is also the ``numpy`` behaviour.)
The ``linspace`` function can accept ``complex`` as the value of the
``dtype``, if the firmware was compiled with complex support. The output
``dtype`` is automatically complex, if either of the endpoints is a
complex scalar.
.. code::
# code to be run in micropython
from ulab import numpy as np
# generate a sequence with defaults
print('default sequence:\t', np.linspace(0, 10))
# num=5
print('num=5:\t\t\t', np.linspace(0, 10, num=5))
# num=5, endpoint=False
print('num=5:\t\t\t', np.linspace(0, 10, num=5, endpoint=False))
# num=5, endpoint=False, dtype=uint8
print('num=5:\t\t\t', np.linspace(0, 5, num=7, endpoint=False, dtype=np.uint8))
.. parsed-literal::
default sequence: array([0.0, 0.2040816326530612, 0.4081632653061225, ..., 9.591836734693871, 9.795918367346932, 9.999999999999993], dtype=float64)
num=5: array([0.0, 2.5, 5.0, 7.5, 10.0], dtype=float64)
num=5: array([0.0, 2.0, 4.0, 6.0, 8.0], dtype=float64)
num=5: array([0, 0, 1, 2, 2, 3, 4], dtype=uint8)
logspace
~~~~~~~~
``linspace``\ ’ equivalent for logarithmically spaced data is
``logspace``. This function produces a sequence of numbers, in which the
quotient of consecutive numbers is constant. This is a geometric
sequence.
``numpy``:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.logspace.html
This function returns an array, whose elements are uniformly spaced
between the ``start``, and ``stop`` points. The number of intervals is
determined by the ``num`` keyword argument, whose default value is 50.
With the ``endpoint`` keyword argument (defaults to ``True``) one can
include ``stop`` in the sequence. In addition, the ``dtype`` keyword can
be supplied to force type conversion of the output. The default is
``float``. Note that, exactly as in ``linspace``, when ``dtype`` is of
integer type, the sequence is not necessarily evenly spaced in log
space.
In addition to the keyword arguments found in ``linspace``, ``logspace``
also accepts the ``base`` argument. The default value is 10.
.. code::
# code to be run in micropython
from ulab import numpy as np
# generate a sequence with defaults
print('default sequence:\t', np.logspace(0, 3))
# num=5
print('num=5:\t\t\t', np.logspace(1, 10, num=5))
# num=5, endpoint=False
print('num=5:\t\t\t', np.logspace(1, 10, num=5, endpoint=False))
# num=5, endpoint=False
print('num=5:\t\t\t', np.logspace(1, 10, num=5, endpoint=False, base=2))
.. parsed-literal::
default sequence: array([1.0, 1.151395399326447, 1.325711365590109, ..., 754.3120063354646, 868.5113737513561, 1000.000000000004], dtype=float64)
num=5: array([10.0, 1778.279410038923, 316227.766016838, 56234132.5190349, 10000000000.0], dtype=float64)
num=5: array([10.0, 630.9573444801933, 39810.71705534974, 2511886.431509581, 158489319.2461114], dtype=float64)
num=5: array([2.0, 6.964404506368993, 24.25146506416637, 84.44850628946524, 294.066778879241], dtype=float64)
ones, zeros
~~~~~~~~~~~
``numpy``:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
``numpy``:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ones.html
A couple of special arrays and matrices can easily be initialised by
calling one of the ``ones``, or ``zeros`` functions. ``ones`` and
``zeros`` follow the same pattern, and have the call signature
.. code:: python
ones(shape, dtype=float)
zeros(shape, dtype=float)
where shape is either an integer, or a tuple specifying the shape.
The ``ones/zeros`` functions can accept complex as the value of the
dtype, if the firmware was compiled with complex support.
.. code::
# code to be run in micropython
from ulab import numpy as np
print(np.ones(6, dtype=np.uint8))
print(np.zeros((6, 4)))
.. parsed-literal::
array([1, 1, 1, 1, 1, 1], dtype=uint8)
array([[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0]], dtype=float64)
When specifying the shape, make sure that the length of the tuple is not
larger than the maximum dimension of your firmware.
.. code::
# code to be run in micropython
from ulab import numpy as np
import ulab
print('maximum number of dimensions: ', ulab.__version__)
print(np.zeros((2, 2, 2)))
.. parsed-literal::
maximum number of dimensions: 2.1.0-2D
Traceback (most recent call last):
File "/dev/shm/micropython.py", line 7, in <module>
TypeError: too many dimensions
Customising array printouts
---------------------------
``ndarray``\ s are pretty-printed, i.e., if the number of entries along
the last axis is larger than 10 (default value), then only the first and
last three entries will be printed. Also note that, as opposed to
``numpy``, the printout always contains the ``dtype``.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(200))
print("a:\t", a)
.. parsed-literal::
a: array([0.0, 1.0, 2.0, ..., 197.0, 198.0, 199.0], dtype=float64)
set_printoptions
~~~~~~~~~~~~~~~~
The default values can be overwritten by means of the
``set_printoptions`` function
`numpy.set_printoptions <https://numpy.org/doc/1.18/reference/generated/numpy.set_printoptions.html>`__,
which accepts two keywords arguments, the ``threshold``, and the
``edgeitems``. The first of these arguments determines the length of the
longest array that will be printed in full, while the second is the
number of items that will be printed on the left and right hand side of
the ellipsis, if the array is longer than ``threshold``.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(20))
print("a printed with defaults:\t", a)
np.set_printoptions(threshold=200)
print("\na printed in full:\t\t", a)
np.set_printoptions(threshold=10, edgeitems=2)
print("\na truncated with 2 edgeitems:\t", a)
.. parsed-literal::
a printed with defaults: array([0.0, 1.0, 2.0, ..., 17.0, 18.0, 19.0], dtype=float64)
a printed in full: array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0], dtype=float64)
a truncated with 2 edgeitems: array([0.0, 1.0, ..., 18.0, 19.0], dtype=float64)
get_printoptions
~~~~~~~~~~~~~~~~
The set value of the ``threshold`` and ``edgeitems`` can be retrieved by
calling the ``get_printoptions`` function with no arguments. The
function returns a *dictionary* with two keys.
.. code::
# code to be run in micropython
from ulab import numpy as np
np.set_printoptions(threshold=100, edgeitems=20)
print(np.get_printoptions())
.. parsed-literal::
{'threshold': 100, 'edgeitems': 20}
Methods and properties of ndarrays
----------------------------------
Arrays have several *properties* that can queried, and some methods that
can be called. With the exception of the flatten and transpose
operators, properties return an object that describe some feature of the
array, while the methods return a new array-like object. The ``imag``,
and ``real`` properties are included in the firmware only, when it was
compiled with complex support.
1. `.byteswap <#.byteswap>`__
2. `.copy <#.copy>`__
3. `.dtype <#.dtype>`__
4. `.flat <#.flat>`__
5. `.flatten <#.flatten>`__
6. `.imag\* <#.imag>`__
7. `.itemsize <#.itemsize>`__
8. `.real\* <#.real>`__
9. `.reshape <#.reshape>`__
10. `.shape <#.shape>`__
11. `.size <#.size>`__
12. `.T <#.transpose>`__
13. `.tobytes <#.tobytes>`__
14. `.tolist <#.tolist>`__
15. `.transpose <#.transpose>`__
16. `.sort <#.sort>`__
.byteswap
~~~~~~~~~
``numpy``
https://numpy.org/doc/stable/reference/generated/numpy.char.chararray.byteswap.html
The method takes a single keyword argument, ``inplace``, with values
``True`` or ``False``, and swaps the bytes in the array. If
``inplace = False``, a new ``ndarray`` is returned, otherwise the
original values are overwritten.
The ``frombuffer`` function is a convenient way of receiving data from
peripheral devices that work with buffers. However, it is not guaranteed
that the byte order (in other words, the *endianness*) of the peripheral
device matches that of the microcontroller. The ``.byteswap`` method
makes it possible to change the endianness of the incoming data stream.
Obviously, byteswapping makes sense only for those cases, when a datum
occupies more than one byte, i.e., for the ``uint16``, ``int16``, and
``float`` ``dtype``\ s. When ``dtype`` is either ``uint8``, or ``int8``,
the method simply returns a view or copy of self, depending upon the
value of ``inplace``.
.. code::
# code to be run in micropython
from ulab import numpy as np
buffer = b'\x01\x02\x03\x04\x05\x06\x07\x08'
print('buffer: ', buffer)
a = np.frombuffer(buffer, dtype=np.uint16)
print('a: ', a)
b = a.byteswap()
print('b: ', b)
.. parsed-literal::
buffer: b'\x01\x02\x03\x04\x05\x06\x07\x08'
a: array([513, 1027, 1541, 2055], dtype=uint16)
b: array([258, 772, 1286, 1800], dtype=uint16)
.copy
~~~~~
The ``.copy`` method creates a new *deep copy* of an array, i.e., the
entries of the source array are *copied* into the target array.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3, 4], dtype=np.int8)
b = a.copy()
print('a: ', a)
print('='*20)
print('b: ', b)
.. parsed-literal::
a: array([1, 2, 3, 4], dtype=int8)
====================
b: array([1, 2, 3, 4], dtype=int8)
.dtype
~~~~~~
``numpy``:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.dtype.htm
The ``.dtype`` property is the ``dtype`` of an array. This can then be
used for initialising another array with the matching type. ``ulab``
implements two versions of ``dtype``; one that is ``numpy``-like, i.e.,
one, which returns a ``dtype`` object, and one that is significantly
cheaper in terms of flash space, but does not define a ``dtype`` object,
and holds a single character (number) instead.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3, 4], dtype=np.int8)
b = np.array([5, 6, 7], dtype=a.dtype)
print('a: ', a)
print('dtype of a: ', a.dtype)
print('\nb: ', b)
.. parsed-literal::
a: array([1, 2, 3, 4], dtype=int8)
dtype of a: dtype('int8')
b: array([5, 6, 7], dtype=int8)
If the ``ulab.h`` header file sets the pre-processor constant
``ULAB_HAS_DTYPE_OBJECT`` to 0 as
.. code:: c
#define ULAB_HAS_DTYPE_OBJECT (0)
then the output of the previous snippet will be
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3, 4], dtype=np.int8)
b = np.array([5, 6, 7], dtype=a.dtype)
print('a: ', a)
print('dtype of a: ', a.dtype)
print('\nb: ', b)
.. parsed-literal::
a: array([1, 2, 3, 4], dtype=int8)
dtype of a: 98
b: array([5, 6, 7], dtype=int8)
Here 98 is nothing but the ASCII value of the character ``b``, which is
the type code for signed 8-bit integers. The object definition adds
around 600 bytes to the firmware.
.flat
~~~~~
numpy:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.htm
``.flat`` returns the array’s flat iterator. For one-dimensional objects
the flat iterator is equivalent to the standart iterator, while for
higher dimensional tensors, it amounts to first flattening the array,
and then iterating over it. Note, however, that the flat iterator does
not consume RAM beyond what is required for holding the position of the
iterator itself, while flattening produces a new copy.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3, 4], dtype=np.int8)
for _a in a:
print(_a)
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=np.int8)
print('a:\n', a)
for _a in a:
print(_a)
for _a in a.flat:
print(_a)
.. parsed-literal::
1
2
3
4
a:
array([[1, 2, 3, 4],
[5, 6, 7, 8]], dtype=int8)
array([1, 2, 3, 4], dtype=int8)
array([5, 6, 7, 8], dtype=int8)
1
2
3
4
5
6
7
8
.flatten
~~~~~~~~
``numpy``:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.htm
``.flatten`` returns the flattened array. The array can be flattened in
``C`` style (i.e., moving along the last axis in the tensor), or in
``fortran`` style (i.e., moving along the first axis in the tensor).
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3, 4], dtype=np.int8)
print("a: \t\t", a)
print("a flattened: \t", a.flatten())
b = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int8)
print("\nb:", b)
print("b flattened (C): \t", b.flatten())
print("b flattened (F): \t", b.flatten(order='F'))
.. parsed-literal::
a: array([1, 2, 3, 4], dtype=int8)
a flattened: array([1, 2, 3, 4], dtype=int8)
b: array([[1, 2, 3],
[4, 5, 6]], dtype=int8)
b flattened (C): array([1, 2, 3, 4, 5, 6], dtype=int8)
b flattened (F): array([1, 4, 2, 5, 3, 6], dtype=int8)
.imag
~~~~~
``numpy``:
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.imag.html
The ``.imag`` property is defined only, if the firmware was compiled
with complex support, and returns a copy with the imaginary part of an
array. If the array is real, then the output is straight zeros with the
``dtype`` of the input. If the input is complex, the output ``dtype`` is
always ``float``, irrespective of the values.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3], dtype=np.uint16)
print("a:\t", a)
print("a.imag:\t", a.imag)
b = np.array([1, 2+1j, 3-1j], dtype=np.complex)
print("\nb:\t", b)
print("b.imag:\t", b.imag)
.. parsed-literal::
a: array([1, 2, 3], dtype=uint16)
a.imag: array([0, 0, 0], dtype=uint16)
b: array([1.0+0.0j, 2.0+1.0j, 3.0-1.0j], dtype=complex)
b.imag: array([0.0, 1.0, -1.0], dtype=float64)
.itemsize
~~~~~~~~~
``numpy``:
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.itemsize.html
The ``.itemsize`` property is an integer with the size of elements in
the array.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3], dtype=np.int8)
print("a:\n", a)
print("itemsize of a:", a.itemsize)
b= np.array([[1, 2], [3, 4]], dtype=np.float)
print("\nb:\n", b)
print("itemsize of b:", b.itemsize)
.. parsed-literal::
a:
array([1, 2, 3], dtype=int8)
itemsize of a: 1
b:
array([[1.0, 2.0],
[3.0, 4.0]], dtype=float64)
itemsize of b: 8
.real
~~~~~
numpy:
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.real.html
The ``.real`` property is defined only, if the firmware was compiled
with complex support, and returns a copy with the real part of an array.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3], dtype=np.uint16)
print("a:\t", a)
print("a.real:\t", a.real)
b = np.array([1, 2+1j, 3-1j], dtype=np.complex)
print("\nb:\t", b)
print("b.real:\t", b.real)
.. parsed-literal::
a: array([1, 2, 3], dtype=uint16)
a.real: array([1, 2, 3], dtype=uint16)
b: array([1.0+0.0j, 2.0+1.0j, 3.0-1.0j], dtype=complex)
b.real: array([1.0, 2.0, 3.0], dtype=float64)
.reshape
~~~~~~~~
``numpy``:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html
``reshape`` re-writes the shape properties of an ``ndarray``, but the
array will not be modified in any other way. The function takes a single
2-tuple with two integers as its argument. The 2-tuple should specify
the desired number of rows and columns. If the new shape is not
consistent with the old, a ``ValueError`` exception will be raised.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], dtype=np.uint8)
print('a (4 by 4):', a)
print('a (2 by 8):', a.reshape((2, 8)))
print('a (1 by 16):', a.reshape((1, 16)))
.. parsed-literal::
a (4 by 4): array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]], dtype=uint8)
a (2 by 8): array([[1, 2, 3, 4, 5, 6, 7, 8],
[9, 10, 11, 12, 13, 14, 15, 16]], dtype=uint8)
a (1 by 16): array([[1, 2, 3, ..., 14, 15, 16]], dtype=uint8)
.. code::
# code to be run in CPython
Note that `ndarray.reshape()` can also be called by assigning to `ndarray.shape`.
.shape
~~~~~~
``numpy``:
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.shape.html
The ``.shape`` property is a tuple whose elements are the length of the
array along each axis.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3, 4], dtype=np.int8)
print("a:\n", a)
print("shape of a:", a.shape)
b= np.array([[1, 2], [3, 4]], dtype=np.int8)
print("\nb:\n", b)
print("shape of b:", b.shape)
.. parsed-literal::
a:
array([1, 2, 3, 4], dtype=int8)
shape of a: (4,)
b:
array([[1, 2],
[3, 4]], dtype=int8)
shape of b: (2, 2)
By assigning a tuple to the ``.shape`` property, the array can be
``reshape``\ d:
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print('a:\n', a)
a.shape = (3, 3)
print('\na:\n', a)
.. parsed-literal::
a:
array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], dtype=float64)
a:
array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]], dtype=float64)
.size
~~~~~
``numpy``:
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.size.html
The ``.size`` property is an integer specifying the number of elements
in the array.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3], dtype=np.int8)
print("a:\n", a)
print("size of a:", a.size)
b= np.array([[1, 2], [3, 4]], dtype=np.int8)
print("\nb:\n", b)
print("size of b:", b.size)
.. parsed-literal::
a:
array([1, 2, 3], dtype=int8)
size of a: 3
b:
array([[1, 2],
[3, 4]], dtype=int8)
size of b: 4
.T
The ``.T`` property of the ``ndarray`` is equivalent to
`.transpose <#.transpose>`__.
.tobytes
~~~~~~~~
``numpy``:
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.tobytes.html
The ``.tobytes`` method can be used for acquiring a handle of the
underlying data pointer of an array, and it returns a new ``bytearray``
that can be fed into any method that can accep a ``bytearray``, e.g.,
ADC data can be buffered into this ``bytearray``, or the ``bytearray``
can be fed into a DAC. Since the ``bytearray`` is really nothing but the
bare data container of the array, any manipulation on the ``bytearray``
automatically modifies the array itself.
Note that the method raises a ``ValueError`` exception, if the array is
not dense (i.e., it has already been sliced).
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(8), dtype=np.uint8)
print('a: ', a)
b = a.tobytes()
print('b: ', b)
# modify b
b[0] = 13
print('='*20)
print('b: ', b)
print('a: ', a)
.. parsed-literal::
a: array([0, 1, 2, 3, 4, 5, 6, 7], dtype=uint8)
b: bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07')
====================
b: bytearray(b'\r\x01\x02\x03\x04\x05\x06\x07')
a: array([13, 1, 2, 3, 4, 5, 6, 7], dtype=uint8)
.tolist
~~~~~~~
``numpy``:
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.tolist.html
The ``.tolist`` method can be used for converting the numerical array
into a (nested) ``python`` lists.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(4), dtype=np.uint8)
print('a: ', a)
b = a.tolist()
print('b: ', b)
c = a.reshape((2, 2))
print('='*20)
print('c: ', c)
d = c.tolist()
print('d: ', d)
.. parsed-literal::
a: array([0, 1, 2, 3], dtype=uint8)
b: [0, 1, 2, 3]
====================
c: array([[0, 1],
[2, 3]], dtype=uint8)
d: [[0, 1], [2, 3]]
.transpose
~~~~~~~~~~
``numpy``:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html
Returns the transposed array. Only defined, if the number of maximum
dimensions is larger than 1.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=np.uint8)
print('a:\n', a)
print('shape of a:', a.shape)
a.transpose()
print('\ntranspose of a:\n', a)
print('shape of a:', a.shape)
.. parsed-literal::
a:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]], dtype=uint8)
shape of a: (4, 3)
transpose of a:
array([[1, 4, 7, 10],
[2, 5, 8, 11],
[3, 6, 9, 12]], dtype=uint8)
shape of a: (3, 4)
The transpose of the array can also be gotten through the ``T``
property:
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.uint8)
print('a:\n', a)
print('\ntranspose of a:\n', a.T)
.. parsed-literal::
a:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]], dtype=uint8)
transpose of a:
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]], dtype=uint8)
.sort
~~~~~
``numpy``:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html
In-place sorting of an ``ndarray``. For a more detailed exposition, see
`sort <#sort>`__.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([[1, 12, 3, 0], [5, 3, 4, 1], [9, 11, 1, 8], [7, 10, 0, 1]], dtype=np.uint8)
print('\na:\n', a)
a.sort(axis=0)
print('\na sorted along vertical axis:\n', a)
a = np.array([[1, 12, 3, 0], [5, 3, 4, 1], [9, 11, 1, 8], [7, 10, 0, 1]], dtype=np.uint8)
a.sort(axis=1)
print('\na sorted along horizontal axis:\n', a)
a = np.array([[1, 12, 3, 0], [5, 3, 4, 1], [9, 11, 1, 8], [7, 10, 0, 1]], dtype=np.uint8)
a.sort(axis=None)
print('\nflattened a sorted:\n', a)
.. parsed-literal::
a:
array([[1, 12, 3, 0],
[5, 3, 4, 1],
[9, 11, 1, 8],
[7, 10, 0, 1]], dtype=uint8)
a sorted along vertical axis:
array([[1, 3, 0, 0],
[5, 10, 1, 1],
[7, 11, 3, 1],
[9, 12, 4, 8]], dtype=uint8)
a sorted along horizontal axis:
array([[0, 1, 3, 12],
[1, 3, 4, 5],
[1, 8, 9, 11],
[0, 1, 7, 10]], dtype=uint8)
flattened a sorted:
array([0, 0, 1, ..., 10, 11, 12], dtype=uint8)
Unary operators
---------------
With the exception of ``len``, which returns a single number, all unary
operators manipulate the underlying data element-wise.
len
~~~
This operator takes a single argument, the array, and returns either the
length of the first axis.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3, 4, 5], dtype=np.uint8)
b = np.array([range(5), range(5), range(5), range(5)], dtype=np.uint8)
print("a:\t", a)
print("length of a: ", len(a))
print("shape of a: ", a.shape)
print("\nb:\t", b)
print("length of b: ", len(b))
print("shape of b: ", b.shape)
.. parsed-literal::
a: array([1, 2, 3, 4, 5], dtype=uint8)
length of a: 5
shape of a: (5,)
b: array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]], dtype=uint8)
length of b: 2
shape of b: (4, 5)
The number returned by ``len`` is also the length of the iterations,
when the array supplies the elements for an iteration (see later).
invert
~~~~~~
The function is defined for integer data types (``uint8``, ``int8``,
``uint16``, and ``int16``) only, takes a single argument, and returns
the element-by-element, bit-wise inverse of the array. If a ``float`` is
supplied, the function raises a ``ValueError`` exception.
With signed integers (``int8``, and ``int16``), the results might be
unexpected, as in the example below:
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([0, -1, -100], dtype=np.int8)
print("a:\t\t", a)
print("inverse of a:\t", ~a)
a = np.array([0, 1, 254, 255], dtype=np.uint8)
print("\na:\t\t", a)
print("inverse of a:\t", ~a)
.. parsed-literal::
a: array([0, -1, -100], dtype=int8)
inverse of a: array([-1, 0, 99], dtype=int8)
a: array([0, 1, 254, 255], dtype=uint8)
inverse of a: array([255, 254, 1, 0], dtype=uint8)
abs
~~~
This function takes a single argument, and returns the
element-by-element absolute value of the array. When the data type is
unsigned (``uint8``, or ``uint16``), a copy of the array will be
returned immediately, and no calculation takes place.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([0, -1, -100], dtype=np.int8)
print("a:\t\t\t ", a)
print("absolute value of a:\t ", abs(a))
.. parsed-literal::
a: array([0, -1, -100], dtype=int8)
absolute value of a: array([0, 1, 100], dtype=int8)
neg
~~~
This operator takes a single argument, and changes the sign of each
element in the array. Unsigned values are wrapped.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([10, -1, 1], dtype=np.int8)
print("a:\t\t", a)
print("negative of a:\t", -a)
b = np.array([0, 100, 200], dtype=np.uint8)
print("\nb:\t\t", b)
print("negative of b:\t", -b)
.. parsed-literal::
a: array([10, -1, 1], dtype=int8)
negative of a: array([-10, 1, -1], dtype=int8)
b: array([0, 100, 200], dtype=uint8)
negative of b: array([0, 156, 56], dtype=uint8)
pos
~~~
This function takes a single argument, and simply returns a copy of the
array.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([10, -1, 1], dtype=np.int8)
print("a:\t\t", a)
print("positive of a:\t", +a)
.. parsed-literal::
a: array([10, -1, 1], dtype=int8)
positive of a: array([10, -1, 1], dtype=int8)
Binary operators
----------------
``ulab`` implements the ``+``, ``-``, ``*``, ``/``, ``**``, ``<``,
``>``, ``<=``, ``>=``, ``==``, ``!=``, ``+=``, ``-=``, ``*=``, ``/=``,
``**=`` binary operators that work element-wise. Broadcasting is
available, meaning that the two operands do not even have to have the
same shape. If the lengths along the respective axes are equal, or one
of them is 1, or the axis is missing, the element-wise operation can
still be carried out. A thorough explanation of broadcasting can be
found under https://numpy.org/doc/stable/user/basics.broadcasting.html.
**WARNING**: note that relational operators (``<``, ``>``, ``<=``,
``>=``, ``==``, ``!=``) should have the ``ndarray`` on their left hand
side, when compared to scalars. This means that the following works
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3])
print(a > 2)
.. parsed-literal::
array([False, False, True], dtype=bool)
while the equivalent statement, ``2 < a``, will raise a ``TypeError``
exception:
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3])
print(2 < a)
.. parsed-literal::
Traceback (most recent call last):
File "/dev/shm/micropython.py", line 5, in <module>
TypeError: unsupported types for __lt__: 'int', 'ndarray'
**WARNING:** ``circuitpython`` users should use the ``equal``, and
``not_equal`` operators instead of ``==``, and ``!=``. See the section
on `array comparison <#Comparison-of-arrays>`__ for details.
Upcasting
~~~~~~~~~
Binary operations require special attention, because two arrays with
different typecodes can be the operands of an operation, in which case
it is not trivial, what the typecode of the result is. This decision on
the result’s typecode is called upcasting. Since the number of typecodes
in ``ulab`` is significantly smaller than in ``numpy``, we have to
define new upcasting rules. Where possible, I followed ``numpy``\ ’s
conventions.
``ulab`` observes the following upcasting rules:
1. Operations on two ``ndarray``\ s of the same ``dtype`` preserve their
``dtype``, even when the results overflow.
2. if either of the operands is a float, the result is automatically a
float
3. When one of the operands is a scalar, it will internally be turned
into a single-element ``ndarray`` with the *smallest* possible
``dtype``. Thus, e.g., if the scalar is 123, it will be converted
into an array of ``dtype`` ``uint8``, while -1000 will be converted
into ``int16``. An ``mp_obj_float``, will always be promoted to
``dtype`` ``float``. Other micropython types (e.g., lists, tuples,
etc.) raise a ``TypeError`` exception.
4.
============== =============== =========== ============
left hand side right hand side ulab result numpy result
============== =============== =========== ============
``uint8`` ``int8`` ``int16`` ``int16``
``uint8`` ``int16`` ``int16`` ``int16``
``uint8`` ``uint16`` ``uint16`` ``uint16``
``int8`` ``int16`` ``int16`` ``int16``
``int8`` ``uint16`` ``uint16`` ``int32``
``uint16`` ``int16`` ``float`` ``int32``
============== =============== =========== ============
Note that the last two operations are promoted to ``int32`` in
``numpy``.
**WARNING:** Due to the lower number of available data types, the
upcasting rules of ``ulab`` are slightly different to those of
``numpy``. Watch out for this, when porting code!
Upcasting can be seen in action in the following snippet:
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3, 4], dtype=np.uint8)
b = np.array([1, 2, 3, 4], dtype=np.int8)
print("a:\t", a)
print("b:\t", b)
print("a+b:\t", a+b)
c = np.array([1, 2, 3, 4], dtype=np.float)
print("\na:\t", a)
print("c:\t", c)
print("a*c:\t", a*c)
.. parsed-literal::
a: array([1, 2, 3, 4], dtype=uint8)
b: array([1, 2, 3, 4], dtype=int8)
a+b: array([2, 4, 6, 8], dtype=int16)
a: array([1, 2, 3, 4], dtype=uint8)
c: array([1.0, 2.0, 3.0, 4.0], dtype=float64)
a*c: array([1.0, 4.0, 9.0, 16.0], dtype=float64)
Benchmarks
~~~~~~~~~~
The following snippet compares the performance of binary operations to a
possible implementation in python. For the time measurement, we will
take the following snippet from the micropython manual:
.. code::
# code to be run in micropython
import utime
def timeit(f, *args, **kwargs):
func_name = str(f).split(' ')[1]
def new_func(*args, **kwargs):
t = utime.ticks_us()
result = f(*args, **kwargs)
print('execution time: ', utime.ticks_diff(utime.ticks_us(), t), ' us')
return result
return new_func
.. parsed-literal::
.. code::
# code to be run in micropython
from ulab import numpy as np
@timeit
def py_add(a, b):
return [a[i]+b[i] for i in range(1000)]
@timeit
def py_multiply(a, b):
return [a[i]*b[i] for i in range(1000)]
@timeit
def ulab_add(a, b):
return a + b
@timeit
def ulab_multiply(a, b):
return a * b
a = [0.0]*1000
b = range(1000)
print('python add:')
py_add(a, b)
print('\npython multiply:')
py_multiply(a, b)
a = np.linspace(0, 10, num=1000)
b = np.ones(1000)
print('\nulab add:')
ulab_add(a, b)
print('\nulab multiply:')
ulab_multiply(a, b)
.. parsed-literal::
python add:
execution time: 10051 us
python multiply:
execution time: 14175 us
ulab add:
execution time: 222 us
ulab multiply:
execution time: 213 us
The python implementation above is not perfect, and certainly, there is
much room for improvement. However, the factor of 50 difference in
execution time is very spectacular. This is nothing but a consequence of
the fact that the ``ulab`` functions run ``C`` code, with very little
python overhead. The factor of 50 appears to be quite universal: the FFT
routine obeys similar scaling (see `Speed of FFTs <#Speed-of-FFTs>`__),
and this number came up with font rendering, too: `fast font rendering
on graphical
displays <https://forum.micropython.org/viewtopic.php?f=15&t=5815&p=33362&hilit=ufont#p33383>`__.
Comparison operators
--------------------
The smaller than, greater than, smaller or equal, and greater or equal
operators return a vector of Booleans indicating the positions
(``True``), where the condition is satisfied.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=np.uint8)
print(a < 5)
.. parsed-literal::
array([True, True, True, True, False, False, False, False], dtype=bool)
**WARNING**: at the moment, due to ``micropython``\ ’s implementation
details, the ``ndarray`` must be on the left hand side of the relational
operators.
That is, while ``a < 5`` and ``5 > a`` have the same meaning, the
following code will not work:
.. code::
# code to be run in micropython
import ulab as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=np.uint8)
print(5 > a)
.. parsed-literal::
Traceback (most recent call last):
File "/dev/shm/micropython.py", line 5, in <module>
TypeError: unsupported types for __gt__: 'int', 'ndarray'
Iterating over arrays
---------------------
``ndarray``\ s are iterable, which means that their elements can also be
accessed as can the elements of a list, tuple, etc. If the array is
one-dimensional, the iterator returns scalars, otherwise a new
reduced-dimensional *view* is created and returned.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([1, 2, 3, 4, 5], dtype=np.uint8)
b = np.array([range(5), range(10, 15, 1), range(20, 25, 1), range(30, 35, 1)], dtype=np.uint8)
print("a:\t", a)
for i, _a in enumerate(a):
print("element %d in a:"%i, _a)
print("\nb:\t", b)
for i, _b in enumerate(b):
print("element %d in b:"%i, _b)
.. parsed-literal::
a: array([1, 2, 3, 4, 5], dtype=uint8)
element 0 in a: 1
element 1 in a: 2
element 2 in a: 3
element 3 in a: 4
element 4 in a: 5
b: array([[0, 1, 2, 3, 4],
[10, 11, 12, 13, 14],
[20, 21, 22, 23, 24],
[30, 31, 32, 33, 34]], dtype=uint8)
element 0 in b: array([0, 1, 2, 3, 4], dtype=uint8)
element 1 in b: array([10, 11, 12, 13, 14], dtype=uint8)
element 2 in b: array([20, 21, 22, 23, 24], dtype=uint8)
element 3 in b: array([30, 31, 32, 33, 34], dtype=uint8)
Slicing and indexing
--------------------
Views vs. copies
~~~~~~~~~~~~~~~~
``numpy`` has a very important concept called *views*, which is a
powerful extension of ``python``\ ’s own notion of slicing. Slices are
special python objects of the form
.. code:: python
slice = start:end:stop
where ``start``, ``end``, and ``stop`` are (not necessarily
non-negative) integers. Not all of these three numbers must be specified
in an index, in fact, all three of them can be missing. The interpreter
takes care of filling in the missing values. (Note that slices cannot be
defined in this way, only there, where an index is expected.) For a good
explanation on how slices work in python, you can read the stackoverflow
question
https://stackoverflow.com/questions/509211/understanding-slice-notation.
In order to see what slicing does, let us take the string
``a = '012345679'``! We can extract every second character by creating
the slice ``::2``, which is equivalent to ``0:len(a):2``, i.e.,
increments the character pointer by 2 starting from 0, and traversing
the string up to the very end.
.. code::
# code to be run in CPython
string = '0123456789'
string[::2]
.. parsed-literal::
'02468'
Now, we can do the same with numerical arrays.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(10), dtype=np.uint8)
print('a:\t', a)
print('a[::2]:\t', a[::2])
.. parsed-literal::
a: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint8)
a[::2]: array([0, 2, 4, 6, 8], dtype=uint8)
This looks similar to ``string`` above, but there is a very important
difference that is not so obvious. Namely, ``string[::2]`` produces a
partial copy of ``string``, while ``a[::2]`` only produces a *view* of
``a``. What this means is that ``a``, and ``a[::2]`` share their data,
and the only difference between the two is, how the data are read out.
In other words, internally, ``a[::2]`` has the same data pointer as
``a``. We can easily convince ourselves that this is indeed the case by
calling the `ndinfo <#The_ndinfo_function>`__ function: the *data
pointer* entry is the same in the two printouts.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(10), dtype=np.uint8)
print('a: ', a, '\n')
np.ndinfo(a)
print('\n' + '='*20)
print('a[::2]: ', a[::2], '\n')
np.ndinfo(a[::2])
.. parsed-literal::
a: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint8)
class: ndarray
shape: (10,)
strides: (1,)
itemsize: 1
data pointer: 0x7ff6c6193220
type: uint8
====================
a[::2]: array([0, 2, 4, 6, 8], dtype=uint8)
class: ndarray
shape: (5,)
strides: (2,)
itemsize: 1
data pointer: 0x7ff6c6193220
type: uint8
If you are still a bit confused about the meaning of *views*, the
section `Slicing and assigning to
slices <#Slicing-and-assigning-to-slices>`__ should clarify the issue.
Indexing
~~~~~~~~
The simplest form of indexing is specifying a single integer between the
square brackets as in
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(10), dtype=np.uint8)
print("a: ", a)
print("the first, and last element of a:\n", a[0], a[-1])
print("the second, and last but one element of a:\n", a[1], a[-2])
.. parsed-literal::
a: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint8)
the first, and last element of a:
0 9
the second, and last but one element of a:
1 8
Indexing can be applied to higher-dimensional tensors, too. When the
length of the indexing sequences is smaller than the number of
dimensions, a new *view* is returned, otherwise, we get a single number.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(9), dtype=np.uint8).reshape((3, 3))
print("a:\n", a)
print("a[0]:\n", a[0])
print("a[1,1]: ", a[1,1])
.. parsed-literal::
a:
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]], dtype=uint8)
a[0]:
array([[0, 1, 2]], dtype=uint8)
a[1,1]: 4
Indices can also be a list of Booleans. By using a Boolean list, we can
select those elements of an array that satisfy a specific condition. At
the moment, such indexing is defined for row vectors only; when the rank
of the tensor is higher than 1, the function raises a
``NotImplementedError`` exception, though this will be rectified in a
future version of ``ulab``.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(9), dtype=np.float)
print("a:\t", a)
print("a < 5:\t", a[a < 5])
.. parsed-literal::
a: array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], dtype=float)
a < 5: array([0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
Indexing with Boolean arrays can take more complicated expressions. This
is a very concise way of comparing two vectors, e.g.:
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(9), dtype=np.uint8)
b = np.array([4, 4, 4, 3, 3, 3, 13, 13, 13], dtype=np.uint8)
print("a:\t", a)
print("\na**2:\t", a*a)
print("\nb:\t", b)
print("\n100*sin(b):\t", np.sin(b)*100.0)
print("\na[a*a > np.sin(b)*100.0]:\t", a[a*a > np.sin(b)*100.0])
.. parsed-literal::
a: array([0, 1, 2, 3, 4, 5, 6, 7, 8], dtype=uint8)
a**2: array([0, 1, 4, 9, 16, 25, 36, 49, 64], dtype=uint16)
b: array([4, 4, 4, 3, 3, 3, 13, 13, 13], dtype=uint8)
100*sin(b): array([-75.68024953079282, -75.68024953079282, -75.68024953079282, 14.11200080598672, 14.11200080598672, 14.11200080598672, 42.01670368266409, 42.01670368266409, 42.01670368266409], dtype=float)
a[a*a > np.sin(b)*100.0]: array([0, 1, 2, 4, 5, 7, 8], dtype=uint8)
Boolean indices can also be used in assignments, if the array is
one-dimensional. The following example replaces the data in an array,
wherever some condition is fulfilled.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(9), dtype=np.uint8)
b = np.array(range(9)) + 12
print(a[b < 15])
a[b < 15] = 123
print(a)
.. parsed-literal::
array([0, 1, 2], dtype=uint8)
array([123, 123, 123, 3, 4, 5, 6, 7, 8], dtype=uint8)
On the right hand side of the assignment we can even have another array.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array(range(9), dtype=np.uint8)
b = np.array(range(9)) + 12
print(a[b < 15], b[b < 15])
a[b < 15] = b[b < 15]
print(a)
.. parsed-literal::
array([0, 1, 2], dtype=uint8) array([12.0, 13.0, 14.0], dtype=float)
array([12, 13, 14, 3, 4, 5, 6, 7, 8], dtype=uint8)
Slicing and assigning to slices
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can also generate sub-arrays by specifying slices as the index of an
array. Slices are special python objects of the form
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.uint8)
print('a:\n', a)
# the first row
print('\na[0]:\n', a[0])
# the first two elements of the first row
print('\na[0,:2]:\n', a[0,:2])
# the zeroth element in each row (also known as the zeroth column)
print('\na[:,0]:\n', a[:,0])
# the last row
print('\na[-1]:\n', a[-1])
# the last two rows backwards
print('\na[-1:-3:-1]:\n', a[-1:-3:-1])
.. parsed-literal::
a:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]], dtype=uint8)
a[0]:
array([[1, 2, 3]], dtype=uint8)
a[0,:2]:
array([[1, 2]], dtype=uint8)
a[:,0]:
array([[1],
[4],
[7]], dtype=uint8)
a[-1]:
array([[7, 8, 9]], dtype=uint8)
a[-1:-3:-1]:
array([[7, 8, 9],
[4, 5, 6]], dtype=uint8)
Assignment to slices can be done for the whole slice, per row, and per
column. A couple of examples should make these statements clearer:
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.zeros((3, 3), dtype=np.uint8)
print('a:\n', a)
# assigning to the whole row
a[0] = 1
print('\na[0] = 1\n', a)
a = np.zeros((3, 3), dtype=np.uint8)
# assigning to a column
a[:,2] = 3.0
print('\na[:,0]:\n', a)
.. parsed-literal::
a:
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]], dtype=uint8)
a[0] = 1
array([[1, 1, 1],
[0, 0, 0],
[0, 0, 0]], dtype=uint8)
a[:,0]:
array([[0, 0, 3],
[0, 0, 3],
[0, 0, 3]], dtype=uint8)
Now, you should notice that we re-set the array ``a`` after the first
assignment. Do you care to see what happens, if we do not do that? Well,
here are the results:
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.zeros((3, 3), dtype=np.uint8)
b = a[:,:]
# assign 1 to the first row
b[0] = 1
# assigning to the last column
b[:,2] = 3
print('a: ', a)
.. parsed-literal::
a: array([[1, 1, 3],
[0, 0, 3],
[0, 0, 3]], dtype=uint8)
Note that both assignments involved ``b``, and not ``a``, yet, when we
print out ``a``, its entries are updated. This proves our earlier
statement about the behaviour of *views*: in the statement
``b = a[:,:]`` we simply created a *view* of ``a``, and not a *deep*
copy of it, meaning that whenever we modify ``b``, we actually modify
``a``, because the underlying data container of ``a`` and ``b`` are
shared between the two object. Having a single data container for two
seemingly different objects provides an extremely powerful way of
manipulating sub-sets of numerical data.
If you want to work on a *copy* of your data, you can use the ``.copy``
method of the ``ndarray``. The following snippet should drive the point
home:
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.zeros((3, 3), dtype=np.uint8)
b = a.copy()
# get the address of the underlying data pointer
np.ndinfo(a)
print()
np.ndinfo(b)
# assign 1 to the first row of b, and do not touch a
b[0] = 1
print()
print('a: ', a)
print('='*20)
print('b: ', b)
.. parsed-literal::
class: ndarray
shape: (3, 3)
strides: (3, 1)
itemsize: 1
data pointer: 0x7ff737ea3220
type: uint8
class: ndarray
shape: (3, 3)
strides: (3, 1)
itemsize: 1
data pointer: 0x7ff737ea3340
type: uint8
a: array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]], dtype=uint8)
====================
b: array([[1, 1, 1],
[0, 0, 0],
[0, 0, 0]], dtype=uint8)
The ``.copy`` method can also be applied to views: below, ``a[0]`` is a
*view* of ``a``, out of which we create a *deep copy* called ``b``. This
is a row vector now. We can then do whatever we want to with ``b``, and
that leaves ``a`` unchanged.
.. code::
# code to be run in micropython
from ulab import numpy as np
a = np.zeros((3, 3), dtype=np.uint8)
b = a[0].copy()
print('b: ', b)
print('='*20)
# assign 1 to the first entry of b, and do not touch a
b[0] = 1
print('a: ', a)
print('='*20)
print('b: ', b)
.. parsed-literal::
b: array([0, 0, 0], dtype=uint8)
====================
a: array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]], dtype=uint8)
====================
b: array([1, 0, 0], dtype=uint8)
The fact that the underlying data of a view is the same as that of the
original array has another important consequence, namely, that the
creation of a view is cheap. Both in terms of RAM, and execution time. A
view is really nothing but a short header with a data array that already
exists, and is filled up. Hence, creating the view requires only the
creation of its header. This operation is fast, and uses virtually no
RAM.
|