PythonSTB commited on
Commit
7c48c91
·
verified ·
1 Parent(s): ddc552c

Delete numpy/Test_NumPy.py

Browse files
Files changed (1) hide show
  1. numpy/Test_NumPy.py +0 -468
numpy/Test_NumPy.py DELETED
@@ -1,468 +0,0 @@
1
- """
2
- On-device verification for the cross-compiled numpy wheel (OpenBLAS).
3
-
4
- Run after installing:
5
- pip install numpy-2.5.2-cp312-cp312-linux_<ABI>.whl
6
- where <ABI> = aarch64 (real device) or x86_64 (emulator)
7
- (this Android build uses the "linux" platform tag for numpy)
8
-
9
- Usage:
10
- python Test_NumPy.py [--quick]
11
-
12
- Exit code 0 = everything required PASSed.
13
- Sections marked [SKIP] are optional (e.g. need Pillow installed).
14
-
15
- Generated by RIMI
16
- """
17
- import os
18
- import sys
19
- import tempfile
20
-
21
- RESULTS = []
22
-
23
-
24
- def test(name, fn):
25
- try:
26
- fn()
27
- RESULTS.append((name, "PASS", None))
28
- except NotImplementedError as exc:
29
- RESULTS.append((name, "SKIP", str(exc)))
30
- except Exception as exc:
31
- RESULTS.append((name, "FAIL", "%s: %s" % (type(exc).__name__, exc)))
32
- print(" ! %s -> %s: %s" % (name, type(exc).__name__, exc))
33
-
34
-
35
- def section(title):
36
- print("=" * 60)
37
- print(title)
38
- print("=" * 60)
39
-
40
-
41
- WORKDIR = None
42
-
43
-
44
- def workdir():
45
- global WORKDIR
46
- if WORKDIR is None:
47
- candidates = [os.environ.get("TMPDIR") or "", tempfile.gettempdir(),
48
- "/storage/emulated/0/Download", os.getcwd()]
49
- for base in candidates:
50
- if not base:
51
- continue
52
- try:
53
- d = os.path.join(base, "test_numpy_tmp")
54
- os.makedirs(d, exist_ok=True)
55
- with open(os.path.join(d, "_probe"), "w") as fh:
56
- fh.write("ok")
57
- WORKDIR = d
58
- break
59
- except OSError:
60
- continue
61
- if WORKDIR is None:
62
- WORKDIR = "."
63
- return WORKDIR
64
-
65
-
66
- # ---------------------------------------------------------------------------
67
- # 1. import / version
68
- # ---------------------------------------------------------------------------
69
- def import_numpy():
70
- import numpy as np
71
- print(" numpy", np.__version__)
72
- assert np.__version__.split(".")[0] == "2", np.__version__
73
- assert callable(np.show_config)
74
-
75
-
76
- def array_basics():
77
- import numpy as np
78
- a = np.array([[1, 2, 3], [4, 5, 6]])
79
- assert a.shape == (2, 3)
80
- assert a.ndim == 2
81
- assert a.size == 6
82
- assert a.dtype == np.dtype("int64")
83
- assert a.itemsize == 8
84
- assert a.nbytes == 48
85
-
86
-
87
- # ---------------------------------------------------------------------------
88
- # 2. array creation
89
- # ---------------------------------------------------------------------------
90
- def creation():
91
- import numpy as np
92
- assert np.array([1, 2, 3]).tolist() == [1, 2, 3]
93
- assert np.zeros((2, 2)).sum() == 0
94
- assert np.ones((2, 2)).sum() == 4
95
- assert np.full((2,), 7.5).tolist() == [7.5, 7.5]
96
- assert np.eye(3).shape == (3, 3)
97
- assert np.arange(5).tolist() == [0, 1, 2, 3, 4]
98
- assert np.linspace(0, 1, 5).shape == (5,)
99
- assert len(np.logspace(1, 3, 3)) == 3
100
-
101
-
102
- def random_rng():
103
- import numpy as np
104
- rng = np.random.default_rng(42) # seeded -> reproducible
105
- r1 = np.random.default_rng(42)
106
- r2 = np.random.default_rng(42)
107
- assert (r1.random(5) == r2.random(5)).all() # same seed, same stream
108
- assert rng.random((3, 3)).shape == (3, 3)
109
- assert rng.integers(0, 10, size=(2, 5)).shape == (2, 5)
110
- assert rng.normal(0, 1, size=(4,)).shape == (4,)
111
-
112
-
113
- # ---------------------------------------------------------------------------
114
- # 3. dtypes / casting
115
- # ---------------------------------------------------------------------------
116
- def dtypes():
117
- import numpy as np
118
- assert np.array([1, 2, 3], dtype=np.uint8).dtype == np.dtype("uint8")
119
- assert np.array([1.0, 2.0]).astype(np.float32).dtype == np.dtype("float32")
120
- assert np.array([1, 2, 3]).astype("f4").dtype == np.dtype("float32")
121
- for s in ("i1", "i2", "i4", "i8", "u1", "u2", "u4", "u8", "f4", "f8"):
122
- assert np.dtype(s)
123
-
124
-
125
- def overflow():
126
- import numpy as np
127
- # uint8 arithmetic wraps around
128
- assert (np.array([200], np.uint8) + np.array([100], np.uint8))[0] == 44
129
- # int division floors, true division gives float
130
- assert np.array([5]) // 2 == np.array([2])
131
- assert np.array([5]) / 2 == np.array([2.5])
132
-
133
-
134
- # ---------------------------------------------------------------------------
135
- # 4. indexing / slicing / masking
136
- # ---------------------------------------------------------------------------
137
- def indexing():
138
- import numpy as np
139
- a = np.arange(12).reshape(3, 4)
140
- assert a[0].tolist() == [0, 1, 2, 3]
141
- assert a[0, 2] == 2
142
- assert a[:, 1].tolist() == [1, 5, 9]
143
- assert a[1:, :2].tolist() == [[4, 5], [8, 9]]
144
- assert a[-1].tolist() == [8, 9, 10, 11]
145
- assert a[::2].tolist() == [[0, 1, 2, 3], [8, 9, 10, 11]]
146
-
147
-
148
- def masking():
149
- import numpy as np
150
- a = np.arange(12).reshape(3, 4)
151
- assert (a[a > 5] > 5).all()
152
- assert len(a[(a > 2) & (a < 8)]) == 5
153
- assert (a[a % 2 == 0] % 2 == 0).all()
154
- m = a.copy()
155
- m[m < 5] = 0
156
- assert m.min() == 0
157
- m[:, 0] = -1
158
- assert (m[:, 0] == -1).all()
159
-
160
-
161
- def fancy_indexing():
162
- import numpy as np
163
- a = np.arange(12).reshape(3, 4)
164
- assert a[[0, 2]].shape == (2, 4)
165
- assert a[:, np.array([3, 1])].shape == (3, 2)
166
-
167
-
168
- # ---------------------------------------------------------------------------
169
- # 5. shapes / broadcasting
170
- # ---------------------------------------------------------------------------
171
- def reshaping():
172
- import numpy as np
173
- a = np.arange(24)
174
- assert a.reshape(4, 6).shape == (4, 6)
175
- assert a.reshape(2, 3, 4).shape == (2, 3, 4)
176
- assert a.reshape(-1, 6).shape == (4, 6)
177
- assert a.ravel().shape == (24,)
178
- assert a.flatten().shape == (24,)
179
- assert a.reshape(4, 6).T.shape == (6, 4)
180
- v = np.array([1, 2, 3])
181
- assert v[np.newaxis, :].shape == (1, 3)
182
- assert v[:, np.newaxis].shape == (3, 1)
183
-
184
-
185
- def broadcasting():
186
- import numpy as np
187
- m = np.ones((3, 4))
188
- assert (m + 1 == 2).all()
189
- assert (m * np.array([10, 20, 30, 40])).shape == (3, 4)
190
- assert (m + np.array([[1], [2], [3]])).shape == (3, 4)
191
- # (3,1) * (1,4) -> (3,4)
192
- out = np.array([[1], [2], [3]]) * np.array([[1, 2, 3, 4]])
193
- assert out.shape == (3, 4)
194
-
195
-
196
- # ---------------------------------------------------------------------------
197
- # 6. math / reductions
198
- # ---------------------------------------------------------------------------
199
- def elementwise():
200
- import numpy as np
201
- a = np.array([1., 2., 3., 4.])
202
- assert (a + 1).tolist() == [2., 3., 4., 5.]
203
- assert (a ** 2).tolist() == [1., 4., 9., 16.]
204
- assert np.sqrt(np.array([4., 9.])).tolist() == [2., 3.]
205
- assert np.clip(a, 1.5, 3.5).tolist() == [1.5, 2., 3., 3.5]
206
- assert np.maximum(a, 2).tolist() == [2., 2., 3., 4.]
207
-
208
-
209
- def reductions():
210
- import numpy as np
211
- a = np.array([1., 2., 3., 4.])
212
- assert a.sum() == 10
213
- assert a.mean() == 2.5
214
- assert a.min() == 1 and a.max() == 4
215
- assert a.prod() == 24
216
- assert a.argmax() == 3 and a.argmin() == 0
217
- assert np.median(a) == 2.5
218
- assert np.percentile(a, 50) == 2.5
219
- m = np.arange(6).reshape(2, 3)
220
- assert m.sum(axis=0).tolist() == [3, 5, 7]
221
- assert m.sum(axis=1).tolist() == [3, 12]
222
-
223
-
224
- def comparisons():
225
- import numpy as np
226
- a = np.array([1., 2., 3., 4.])
227
- assert (a > 2).tolist() == [False, False, True, True]
228
- assert bool(np.any(a > 2)) is True
229
- assert bool(np.all(a > 2)) is False
230
- assert np.count_nonzero(a > 2) == 2
231
-
232
-
233
- # ---------------------------------------------------------------------------
234
- # 7. linear algebra (OpenBLAS accelerated)
235
- # ---------------------------------------------------------------------------
236
- def matmul():
237
- import numpy as np
238
- a = np.array([[1., 2.], [3., 4.]])
239
- b = np.array([[5., 6.], [7., 8.]])
240
- assert (a @ b).tolist() == [[19., 22.], [43., 50.]]
241
- assert np.matmul(a, b).tolist() == (a @ b).tolist()
242
- assert a.dot(b).tolist() == (a @ b).tolist()
243
-
244
-
245
- def linalg():
246
- import numpy as np
247
- a = np.array([[4., 2.], [1., 3.]])
248
- inv = np.linalg.inv(a)
249
- ident = inv @ a
250
- assert np.allclose(ident, np.eye(2), atol=1e-10)
251
- assert abs(np.linalg.det(a) - 10.0) < 1e-10
252
- x = np.linalg.solve(a, np.array([6., 4.]))
253
- assert np.allclose(a @ x, [6., 4.])
254
- assert np.linalg.norm(np.array([3., 4.])) == 5.0
255
- w, v = np.linalg.eig(a)
256
- assert w.shape == (2,)
257
- assert v.shape == (2, 2)
258
-
259
-
260
- def point_transform():
261
- import numpy as np
262
- M = np.array([[1., 0., 10.], [0., 1., 20.], [0., 0., 1.]])
263
- p = np.array([5., 6., 1.])
264
- out = M @ p
265
- assert out.tolist() == [15., 26., 1.]
266
-
267
-
268
- # ---------------------------------------------------------------------------
269
- # 8. stacking / splitting
270
- # ---------------------------------------------------------------------------
271
- def stacking():
272
- import numpy as np
273
- a = np.array([1, 2, 3])
274
- b = np.array([4, 5, 6])
275
- assert np.concatenate((a, b)).tolist() == [1, 2, 3, 4, 5, 6]
276
- assert np.stack((a, b)).shape == (2, 3)
277
- assert np.vstack((a, b)).shape == (2, 3)
278
- assert np.hstack((a, b)).shape == (6,)
279
- m1 = np.ones((2, 2))
280
- m2 = np.zeros((2, 2))
281
- assert np.vstack((m1, m2)).shape == (4, 2)
282
- assert np.hstack((m1, m2)).shape == (2, 4)
283
-
284
-
285
- def splitting():
286
- import numpy as np
287
- x = np.arange(10)
288
- parts = np.split(x, 2)
289
- assert len(parts) == 2 and parts[0].tolist() == [0, 1, 2, 3, 4]
290
- assert len(np.array_split(x, 3)) == 3
291
- m = np.ones((4, 4))
292
- assert len(np.hsplit(m, 2)) == 2
293
- assert len(np.vsplit(m, 2)) == 2
294
-
295
-
296
- # ---------------------------------------------------------------------------
297
- # 9. save / load files
298
- # ---------------------------------------------------------------------------
299
- def save_load_npy():
300
- import numpy as np
301
- a = np.arange(12).reshape(3, 4)
302
- p = os.path.join(workdir(), "a.npy")
303
- np.save(p, a)
304
- b = np.load(p)
305
- assert (b == a).all()
306
-
307
-
308
- def save_load_npz():
309
- import numpy as np
310
- a = np.arange(12).reshape(3, 4)
311
- p = os.path.join(workdir(), "data.npz")
312
- np.savez(p, x=a, y=a * 2)
313
- d = np.load(p)
314
- assert (d["x"] == a).all()
315
- assert (d["y"] == a * 2).all()
316
- d.close()
317
-
318
-
319
- def save_load_text():
320
- import numpy as np
321
- a = np.arange(12).reshape(3, 4)
322
- p = os.path.join(workdir(), "a.csv")
323
- np.savetxt(p, a, delimiter=",")
324
- c = np.loadtxt(p, delimiter=",")
325
- assert c.dtype == np.float64
326
- assert c.shape == (3, 4)
327
-
328
-
329
- def save_load_binary():
330
- import numpy as np
331
- a = np.arange(12).reshape(3, 4)
332
- p = os.path.join(workdir(), "a.bin")
333
- a.tofile(p)
334
- b = np.fromfile(p, dtype=np.int64)
335
- assert b.tolist() == list(range(12))
336
-
337
-
338
- # ---------------------------------------------------------------------------
339
- # 11. terminal printing
340
- # ---------------------------------------------------------------------------
341
- def printing():
342
- import numpy as np
343
- a = np.arange(12).reshape(3, 4)
344
- a.tolist() # nested python lists
345
- prev = np.get_printoptions()
346
- np.set_printoptions(precision=2, threshold=20, edgeitems=3, linewidth=120,
347
- suppress=True)
348
- print(a)
349
- np.set_printoptions(**prev)
350
-
351
-
352
- # ---------------------------------------------------------------------------
353
- # 12. everyday snippets
354
- # ---------------------------------------------------------------------------
355
- def snippets():
356
- import numpy as np
357
- x = np.array([3., 1., 2., 0.])
358
- n = (x - x.min()) / (x.max() - x.min())
359
- assert n.min() == 0 and n.max() == 1
360
- z = (x - x.mean()) / x.std()
361
- assert abs(z.mean()) < 1e-12
362
- cats = np.array([0, 2, 1, 2, 0])
363
- onehot = np.eye(3)[cats]
364
- assert onehot.shape == (5, 3)
365
- assert np.diag(np.arange(9).reshape(3, 3)).tolist() == [0, 4, 8]
366
- rng = np.random.default_rng(7)
367
- values, edges = np.histogram(rng.normal(size=1000), bins=20)
368
- assert len(values) == 20 and len(edges) == 21
369
- m = rng.random((5, 8))
370
- assert m.argmax(axis=1).shape == (5,)
371
- signal = np.array([1., 2., 3., 2., 1.])
372
- kernel = np.ones(3) / 3
373
- smooth = np.convolve(signal, kernel, mode="same")
374
- assert smooth.shape == signal.shape
375
-
376
-
377
- def elapsed_time():
378
- import numpy as np
379
- import time
380
- t0 = time.perf_counter()
381
- big = np.arange(1_000_000)
382
- out = big * 2
383
- elapsed = time.perf_counter() - t0
384
- assert out.shape == big.shape
385
- print(" %.4f s for 1M element multiply" % elapsed)
386
-
387
-
388
- # ---------------------------------------------------------------------------
389
- def main():
390
- quick = "--quick" in sys.argv
391
-
392
- section("1. numpy import / version")
393
- test("import numpy (2.x)", import_numpy)
394
- test("array basics (shape/ndim/size/dtype)", array_basics)
395
-
396
- section("2. array creation")
397
- test("creation helpers", creation)
398
- test("default_rng seeded random", random_rng)
399
-
400
- section("3. dtypes / casting")
401
- test("dtypes and casting", dtypes)
402
- test("uint8 overflow / division rules", overflow)
403
-
404
- section("4. indexing / masking")
405
- test("indexing and slicing", indexing)
406
- test("boolean masking + assignment", masking)
407
- test("fancy indexing", fancy_indexing)
408
-
409
- section("5. shapes / broadcasting")
410
- test("reshape / ravel / T / newaxis", reshaping)
411
- test("broadcasting rules", broadcasting)
412
-
413
- section("6. math / reductions")
414
- test("element-wise ufuncs", elementwise)
415
- test("reductions + axes", reductions)
416
- test("comparisons / any / all", comparisons)
417
-
418
- section("7. linear algebra")
419
- test("matrix multiply @", matmul)
420
- test("inv/det/solve/eig/norm", linalg)
421
- test("homography point transform", point_transform)
422
-
423
- section("8. stacking / splitting")
424
- test("concatenate / stack / vstack / hstack", stacking)
425
- test("split / array_split / hsplit / vsplit", splitting)
426
-
427
- section("9. save / load files")
428
- test("npy roundtrip", save_load_npy)
429
- test("npz roundtrip", save_load_npz)
430
- test("savetxt / loadtxt", save_load_text)
431
- test("tofile / fromfile", save_load_binary)
432
-
433
- section("10. terminal printing")
434
- test("print options + tolist", printing)
435
-
436
- section("11. everyday snippets")
437
- test("normalize / zscore / one-hot / histogram", snippets)
438
- test("large-array perf sanity", elapsed_time)
439
-
440
- print()
441
- print("=" * 60)
442
- print("SUMMARY")
443
- print("=" * 60)
444
- fails = 0
445
- skips = 0
446
- for name, status, why in RESULTS:
447
- mark = " OK" if status == "PASS" else (" SKIP" if status == "SKIP" else "FAIL")
448
- print("%s %s" % (mark, name))
449
- if why:
450
- print(" -> %s" % why)
451
- if status == "FAIL":
452
- fails += 1
453
- elif status == "SKIP":
454
- skips += 1
455
- print()
456
- passed = len(RESULTS) - fails - skips
457
- print("passed=%d skipped=%d failed=%d" % (passed, skips, fails))
458
- if fails:
459
- print("RESULT: FAILED")
460
- elif skips and not quick:
461
- print("RESULT: PASSED (with informational skips)")
462
- else:
463
- print("RESULT: PASSED")
464
- sys.exit(1 if fails else 0)
465
-
466
-
467
- if __name__ == "__main__":
468
- main()