-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_all.py
More file actions
2387 lines (1892 loc) · 101 KB
/
Copy pathtest_all.py
File metadata and controls
2387 lines (1892 loc) · 101 KB
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
"""
Bit-level alignment tests — ALL numpycpp C++ vs Python numpy APIs.
SINGLE entry point. Run with:
pytest tests/test_all.py -v
Alignment: BIT-LEVEL (最高级对齐).
Every test asserts bit-identical results between C++ and Python numpy.
No tolerance, no atol/rtol — raw IEEE 754 bits must match exactly.
Coverage:
- float64 + float32 (via dtype fixture)
- All core, linalg, einsum APIs
- bool / int / float dtypes
"""
import os
import importlib
import numpy as np
import pytest
# ============================================================================
# Bit-level assertion helpers
# ============================================================================
def check_bit_aligned(cpp_result, py_result, label=""):
"""Check bit-level alignment between C++ and Python numpy results."""
cpp = np.asarray(cpp_result)
py = np.asarray(py_result)
info = {"label": label, "pass": False,
"shape_match": cpp.shape == py.shape, "n_diff": 0, "error": None}
if not info["shape_match"]:
info["error"] = f"shape mismatch: C++ {cpp.shape} vs Python {py.shape}"
return info
# --- bit-level equality ---
# For floating-point arrays with the SAME dtype use uint bit-view comparison so
# NaN==NaN (same bits) passes. np.array_equal returns False for NaN (IEEE 754).
#
# When dtypes differ (some C++ functions return float64 for float32 input) we
# fall back to numpy's numeric comparison (float32 is upcast to float64).
_UINT_VIEW = {4: np.uint32, 8: np.uint64}
if cpp.dtype.kind == 'f' and cpp.dtype == py.dtype:
uint_t = _UINT_VIEW.get(cpp.itemsize)
if uint_t is not None:
cpp_u = np.ascontiguousarray(cpp).ravel().view(uint_t)
py_u = np.ascontiguousarray(py ).ravel().view(uint_t)
if np.array_equal(cpp_u, py_u):
info["pass"] = True
return info
diff_mask = (cpp_u != py_u).reshape(cpp.shape)
else:
if np.array_equal(cpp, py):
info["pass"] = True
return info
diff_mask = cpp != py
else:
if np.array_equal(cpp, py):
info["pass"] = True
return info
# cpp != py may return a scalar bool (Python/numpy) for incompatible shapes
# (old numpy behaviour). Normalise to an ndarray with cpp's shape.
diff_raw = np.asarray(cpp != py)
if diff_raw.shape != cpp.shape:
try:
diff_mask = diff_raw.reshape(cpp.shape)
except ValueError:
diff_mask = np.ones(cpp.shape, dtype=bool)
else:
diff_mask = diff_raw
# --- bit-level mismatch --- build hex diagnostic ---
info["n_diff"] = int(np.sum(diff_mask))
diff_indices = np.flatnonzero(diff_mask.ravel())
n_show = min(5, len(diff_indices))
err_lines = [f"BIT-LEVEL MISMATCH: {info['n_diff']}/{cpp.size} elements differ"]
for idx in diff_indices[:n_show]:
cpp_val, py_val = cpp.flat[idx], py.flat[idx]
if cpp.dtype == bool or np.issubdtype(cpp.dtype, np.integer):
err_lines.append(f" [{idx}] C++={cpp_val} vs numpy={py_val}")
else:
_EL_VIEW = {2: np.uint16, 4: np.uint32, 8: np.uint64}
_EL_FMT = {2: "04x", 4: "08x", 8: "016x"}
cpp_esz, py_esz = cpp.itemsize, py.itemsize
cpp_vdt, py_vdt = _EL_VIEW.get(cpp_esz), _EL_VIEW.get(py_esz)
cpp_fmt = _EL_FMT.get(cpp_esz, "016x")
py_fmt = _EL_FMT.get(py_esz, "016x")
cpp_hex = np.ascontiguousarray(cpp).view(cpp_vdt).flat[idx] if cpp_vdt else 0
py_hex = np.ascontiguousarray(py ).view(py_vdt ).flat[idx] if py_vdt else 0
if not cpp_vdt: cpp_fmt = ""
if not py_vdt: py_fmt = ""
cpp_str = f"C++={cpp_val:.16e} (0x{cpp_hex:{cpp_fmt}})" if cpp_fmt else f"C++={cpp_val:.16e}"
py_str = f"numpy={py_val:.16e} (0x{py_hex:{py_fmt}})" if py_fmt else f"numpy={py_val:.16e}"
err_lines.append(f" [{idx}] {cpp_str} vs {py_str}")
if len(diff_indices) > n_show:
err_lines.append(f" ... and {len(diff_indices) - n_show} more differing elements")
info["error"] = "\n".join(err_lines)
return info
def assert_bit_aligned(cpp_result, py_result, label=""):
"""Assert C++ and Python results are bit-level identical."""
info = check_bit_aligned(cpp_result, py_result, label=label)
if not info["pass"]:
raise AssertionError(info.get("error", "bit-level alignment failure"))
return info
def random_array(shape, dtype=np.float64, seed: int = 42):
"""Deterministic random array with controlled seed per shape."""
rng = np.random.RandomState(seed + hash(shape) % (2**31))
if np.issubdtype(dtype, np.floating):
return rng.randn(*shape).astype(dtype)
elif dtype == bool:
return rng.rand(*shape) > 0.5
else:
return rng.randint(0, 100, size=shape).astype(dtype)
def _dtype_val(v_f64, v_f32, dtype):
"""Return value cast to dtype."""
return v_f64 if dtype == np.float64 else dtype(v_f32)
# ============================================================================
# C++ module fixture (lazy import, session-scoped)
# ============================================================================
_cpp_module = None
_import_error = None
def _resolve_module_name() -> str:
cli_mod = getattr(pytest, "_numpycpp_module_name", None)
if cli_mod: return cli_mod
env = os.environ.get("NUMPYCPP_MODULE")
if env: return env
return "numpycpp"
def get_cpp_module():
"""Return the compiled numpycpp C++ module (lazy, cached)."""
global _cpp_module, _import_error
if _cpp_module is not None: return _cpp_module
if _import_error is not None: raise _import_error
modname = _resolve_module_name()
try:
_cpp_module = importlib.import_module(modname)
except ImportError as e:
_import_error = e
raise
return _cpp_module
@pytest.fixture(scope="session")
def cpp():
return get_cpp_module()
@pytest.fixture(params=[np.float64, np.float32], ids=["float64", "float32"])
def dtype(request):
return request.param
# ============================================================================
# 1. Data-driven element-wise unary math
# ============================================================================
# Each entry: (cpp_fn_name, np_fn, input_prep, sizes)
# input_prep: None → random_array directly; else callable: prep(a) → input
# sizes: list of (size, seed) tuples
#
# All functions (including transcendental) are bit-exact on EVERY architecture
# via numpy's own scalar math functions (npy_exp, npy_log, ...) resolved from
# _multiarray_umath.so by the SVML bridge. No AVX-512 required.
_UNARY_MATH = [
("sqrt", np.sqrt, lambda a: np.abs(a), [(100, 42), (10000, 7), (100000, 7)]),
("abs", np.abs, None, [(100, 42), (10000, 7), (100000, 7)]),
("exp", np.exp, None, [(100, 1), (1000, 7), (10000, 7), (100000, 7)]),
("log", np.log, lambda a: np.abs(a) + 0.1, [(100, 42), (1000, 7), (10000, 7), (100000, 7)]),
("sin", np.sin, None, [(100, 42), (1000, 7), (10000, 7), (100000, 7)]),
("cos", np.cos, None, [(100, 42), (1000, 7), (10000, 7), (100000, 7)]),
("tan", np.tan, lambda a: a * 0.5, [(100, 42), (1000, 7), (10000, 7), (100000, 7)]),
("cbrt", np.cbrt, None, [(100, 42), (1000, 7), (10000, 7), (100000, 7)]),
("expm1", np.expm1, lambda a: a * 2.0, [(100, 42), (1000, 7), (10000, 7), (100000, 7)]),
("log1p", np.log1p, lambda a: np.abs(a) + 0.1, [(100, 42), (1000, 7), (10000, 7), (100000, 7)]),
("log10", np.log10, lambda a: np.abs(a) + 0.1, [(100, 42), (1000, 7), (10000, 7), (100000, 7)]),
("log2", np.log2, lambda a: np.abs(a) + 0.1, [(100, 42), (1000, 7), (10000, 7), (100000, 7)]),
("arcsin", np.arcsin, lambda a: np.clip(a * 0.5, -1, 1), [(100, 42), (1000, 7), (10000, 7), (100000, 7)]),
("arccos", np.arccos, lambda a: np.clip(a * 0.5, -1, 1), [(100, 42), (1000, 7), (10000, 7), (100000, 7)]),
("arctan", np.arctan, None, [(100, 42), (1000, 7), (10000, 7), (100000, 7)]),
("round", np.round, lambda a: a * 100, [(100, 42), (10000, 7), (100000, 7)]),
("floor", np.floor, lambda a: a * 100, [(100, 42), (10000, 7), (100000, 7)]),
("ceil", np.ceil, lambda a: a * 100, [(100, 42), (10000, 7), (100000, 7)]),
("degrees", np.degrees, None, [(100, 42), (10000, 7), (100000, 7)]),
("radians", np.radians, None, [(100, 42), (10000, 7), (100000, 7)]),
("sign", np.sign, None, [(100, 42), (10000, 7), (100000, 7)]),
]
# Build parametrize tables at module level
_UNARY_ARGS = []
_UNARY_IDS = []
for fn, npf, prep, sizes in _UNARY_MATH:
for size, seed in sizes:
tag = f"{fn}_{size}"
if seed != 42: tag += f"_s{seed}"
_UNARY_IDS.append(tag)
_UNARY_ARGS.append(pytest.param(fn, npf, prep, size, seed, id=tag))
@pytest.mark.parametrize("fn_name, np_fn, prep, size, seed", _UNARY_ARGS)
def test_unary_math(fn_name, np_fn, prep, size, seed, cpp, dtype):
a = random_array((size,), seed=seed, dtype=dtype)
inp = prep(a) if prep else a
cpp_fn = getattr(cpp, fn_name)
assert_bit_aligned(cpp_fn(inp), np_fn(inp), fn_name)
# Special: sqrt and sign zero tests
def test_sqrt_zero(cpp, dtype):
a = np.zeros((5,), dtype=dtype)
assert_bit_aligned(cpp.sqrt(a), np.sqrt(a), "sqrt zero")
def test_sign_zero(cpp, dtype):
a = np.array([0.0, -0.0, 0.0], dtype=dtype)
assert_bit_aligned(cpp.sign(a), np.sign(a), "sign zero")
# Power
@pytest.mark.parametrize("expval,size,seed", [
(2.0, 10, 42), (3.0, 10, 42), (0.5, 10, 42), (-1.0, 10, 42), (0.0, 10, 42),
(2.0, 10000, 7), (3.0, 10000, 7), (0.5, 10000, 7), (-1.0, 10000, 7),
])
def test_power(expval, size, seed, cpp, dtype):
e = dtype(expval)
a = np.abs(random_array((size,), seed=seed, dtype=dtype)) + dtype(0.01)
assert_bit_aligned(cpp.power(a, e), np.power(a, e), f"power({expval})_{size}")
# Clip
@pytest.mark.parametrize("lo,hi,size", [
(0.0, 1.0, 20), (-1.0, 1.0, 20), (0.5, 0.5, 20), (-10.0, 10.0, 20),
(0.0, 1.0, 10000), (-100.0, 100.0, 10000),
])
def test_clip(lo, hi, size, cpp, dtype):
l, h = dtype(lo), dtype(hi)
a = random_array((size,), seed=(7 if size > 100 else 42), dtype=dtype)
assert_bit_aligned(cpp.clip(a, l, h), np.clip(a, l, h), f"clip({lo},{hi})_{size}")
# ============================================================================
# 2. Data-driven comparisons
# ============================================================================
_COMPARISONS = [
("greater", np.greater),
("less", np.less),
("greater_equal", np.greater_equal),
("less_equal", np.less_equal),
]
_COMP_ARGS = [(fn, npf, size, seed) for fn, npf in _COMPARISONS for size, seed in [(100, 42), (100000, 7)]]
_COMP_IDS = [f"{fn}_{size}" for fn, npf in _COMPARISONS for size, seed in [(100, 42), (100000, 7)]]
@pytest.mark.parametrize("fn_name, np_fn, size, seed", _COMP_ARGS, ids=_COMP_IDS)
def test_comparison(fn_name, np_fn, size, seed, cpp, dtype):
a = random_array((size,), seed=seed, dtype=dtype)
cpp_fn = getattr(cpp, fn_name)
assert_bit_aligned(cpp_fn(a, dtype(0.0)), np_fn(a, dtype(0.0)), fn_name)
def test_equal(cpp, dtype):
a = np.array([0.0, 1.0, 1.0, 0.0], dtype=dtype)
assert_bit_aligned(cpp.equal(a, dtype(1.0)), np.equal(a, dtype(1.0)), "equal")
def test_equal_large(cpp, dtype):
a = random_array((100000,), seed=7, dtype=dtype)
assert_bit_aligned(cpp.equal(a, dtype(0.0)), np.equal(a, dtype(0.0)), "equal large")
def test_not_equal_scalar(cpp, dtype):
a = np.array([0.0, 1.0, 0.0], dtype=dtype)
assert_bit_aligned(cpp.not_equal(a, dtype(0.0)), np.not_equal(a, dtype(0.0)), "not_equal scalar")
def test_not_equal_array(cpp, dtype):
a = random_array((100,), dtype=dtype)
b = random_array((100,), seed=99, dtype=dtype)
assert_bit_aligned(cpp.not_equal(a, b), np.not_equal(a, b), "not_equal array")
def test_not_equal_large(cpp, dtype):
a = random_array((100000,), seed=7, dtype=dtype)
b = random_array((100000,), seed=99, dtype=dtype)
assert_bit_aligned(cpp.not_equal(a, b), np.not_equal(a, b), "not_equal large")
# ============================================================================
# 3. Data-driven binary element-wise
# ============================================================================
def test_maximum_array(cpp, dtype):
a = random_array((100,), seed=1, dtype=dtype)
b = random_array((100,), seed=2, dtype=dtype)
assert_bit_aligned(cpp.maximum(a, b), np.maximum(a, b), "maximum(a,b)")
def test_maximum_scalar(cpp, dtype):
a = random_array((100,), dtype=dtype)
assert_bit_aligned(cpp.maximum(a, dtype(0.0)), np.maximum(a, dtype(0.0)), "maximum(a,0)")
def test_maximum_large(cpp, dtype):
a = random_array((100000,), seed=7, dtype=dtype)
b = random_array((100000,), seed=99, dtype=dtype)
assert_bit_aligned(cpp.maximum(a, b), np.maximum(a, b), "maximum large")
def test_minimum_array(cpp, dtype):
a = random_array((100,), seed=1, dtype=dtype)
b = random_array((100,), seed=2, dtype=dtype)
assert_bit_aligned(cpp.minimum(a, b), np.minimum(a, b), "minimum(a,b)")
def test_minimum_scalar(cpp, dtype):
a = random_array((100,), dtype=dtype)
assert_bit_aligned(cpp.minimum(a, dtype(0.0)), np.minimum(a, dtype(0.0)), "minimum(a,0)")
def test_minimum_large(cpp, dtype):
a = random_array((100000,), seed=7, dtype=dtype)
b = random_array((100000,), seed=99, dtype=dtype)
assert_bit_aligned(cpp.minimum(a, b), np.minimum(a, b), "minimum large")
def test_arctan2_array(cpp, dtype):
a = random_array((100,), dtype=dtype)
b = np.abs(random_array((100,), dtype=dtype)) + dtype(0.1)
assert_bit_aligned(cpp.arctan2(a, b), np.arctan2(a, b), "arctan2(a,b)")
def test_arctan2_scalar(cpp, dtype):
a = random_array((100,), dtype=dtype)
assert_bit_aligned(cpp.arctan2(a, dtype(1.0)), np.arctan2(a, dtype(1.0)), "arctan2(a,1)")
def test_arctan2_large(cpp, dtype):
a = random_array((10000,), seed=7, dtype=dtype)
b = np.abs(random_array((10000,), seed=99, dtype=dtype)) + dtype(0.1)
assert_bit_aligned(cpp.arctan2(a, b), np.arctan2(a, b), "arctan2 large")
# ============================================================================
# 4. Reductions
# ============================================================================
def test_sum_1d(cpp, dtype):
a = random_array((100,), dtype=dtype)
assert cpp.sum(a) == np.sum(a), "sum 1d"
def test_sum_2d(cpp, dtype):
a = random_array((5, 4), dtype=dtype)
assert cpp.sum(a) == np.sum(a), "sum 2d"
def test_sum_empty(cpp, dtype):
a = np.array([], dtype=dtype)
assert cpp.sum(a) == dtype(0), "sum empty"
def test_mean_1d(cpp, dtype):
a = random_array((100,), dtype=dtype)
assert_bit_aligned(np.float64(cpp.mean(a)), np.float64(np.mean(a)), "mean 1d")
def test_mean_empty(cpp, dtype):
assert np.float64(cpp.mean(np.array([], dtype=dtype))) == 0.0, "mean empty"
def test_max_1d(cpp, dtype):
a = random_array((100,), dtype=dtype)
assert cpp.max(a) == np.max(a), "max 1d"
def test_max_large(cpp, dtype):
a = random_array((100000,), seed=7, dtype=dtype)
assert cpp.max(a) == np.max(a), "max large"
def test_min_1d(cpp, dtype):
a = random_array((100,), dtype=dtype)
assert cpp.min(a) == np.min(a), "min 1d"
def test_min_large(cpp, dtype):
a = random_array((100000,), seed=7, dtype=dtype)
assert cpp.min(a) == np.min(a), "min large"
# ============================================================================
# 5. Statistical
# ============================================================================
def test_std_random(cpp, dtype):
a = random_array((100,), dtype=dtype)
cpp_r, py_r = cpp.std(a), np.std(a)
assert np.float64(cpp_r) == np.float64(py_r), f"std: {cpp_r} vs {py_r}"
def test_std_constant(cpp, dtype):
a = np.ones((50,), dtype=dtype) * dtype(3.0)
cpp_r, py_r = cpp.std(a), np.std(a)
assert np.float64(cpp_r) == np.float64(py_r), f"std constant: {cpp_r} vs {py_r}"
@pytest.mark.parametrize("size", [1000, 10000])
def test_std_large(size, cpp):
"""std large: float64 only — float32 ULP differences from summation order."""
a = random_array((size,), seed=7, dtype=np.float64)
cpp_r, py_r = cpp.std(a), np.std(a)
assert np.float64(cpp_r) == np.float64(py_r), f"std large {size}"
def test_var_random(cpp, dtype):
a = random_array((100,), dtype=dtype)
cpp_r, py_r = cpp.var(a), np.var(a)
assert np.float64(cpp_r) == np.float64(py_r), f"var: {cpp_r} vs {py_r}"
@pytest.mark.parametrize("size", [1000, 10000])
def test_var_large(size, cpp):
"""var large: float64 only — float32 ULP differences from summation order."""
a = random_array((size,), seed=7, dtype=np.float64)
cpp_r, py_r = cpp.var(a), np.var(a)
assert np.float64(cpp_r) == np.float64(py_r), f"var large {size}"
# ============================================================================
# 6. Array creation
# ============================================================================
def test_zeros_like(cpp, dtype):
a = random_array((3, 4), dtype=dtype)
assert_bit_aligned(cpp.zeros_like(a), np.zeros_like(a), "zeros_like")
@pytest.mark.parametrize("shape", [(1,), (5,), (2, 3), (4, 5, 6)])
def test_zeros_like_shapes(shape, cpp, dtype):
a = random_array(shape, dtype=dtype)
assert_bit_aligned(cpp.zeros_like(a), np.zeros_like(a), f"zeros_like{shape}")
def test_ones_like(cpp, dtype):
a = random_array((3, 4), dtype=dtype)
assert_bit_aligned(cpp.ones_like(a), np.ones_like(a), "ones_like")
@pytest.mark.parametrize("shape", [(1,), (5,), (2, 3), (1, 1, 1)])
def test_ones_like_shapes(shape, cpp, dtype):
a = random_array(shape, dtype=dtype)
assert_bit_aligned(cpp.ones_like(a), np.ones_like(a), f"ones_like{shape}")
@pytest.mark.parametrize("v_f64,v_f32", [(0.0, 0.0), (1.0, 1.0), (-3.14, -3.14), (42.0, 42.0), (1e10, 1e10)])
def test_full_like(v_f64, v_f32, cpp, dtype):
v = _dtype_val(v_f64, v_f32, dtype)
a = random_array((3, 4), dtype=dtype)
assert_bit_aligned(cpp.full_like(a, v), np.full_like(a, v), f"full_like({v})")
def test_empty_like_shape(cpp, dtype):
a = random_array((3, 4), dtype=dtype)
assert np.asarray(cpp.empty_like(a)).shape == a.shape, "empty_like shape"
@pytest.mark.parametrize("shape", [(5,), (3, 4), (2, 3, 4)])
def test_zeros(shape, cpp):
assert_bit_aligned(cpp.zeros(shape), np.zeros(shape), f"zeros{shape}")
@pytest.mark.parametrize("shape", [(5,), (3, 4), (2, 3, 4)])
def test_ones(shape, cpp):
assert_bit_aligned(cpp.ones(shape), np.ones(shape), f"ones{shape}")
@pytest.mark.parametrize("shape,fill_val", [((5,), 3.14), ((2, 3), -1.0), ((4,), 0.0)])
def test_full(shape, fill_val, cpp):
assert_bit_aligned(cpp.full(list(shape), fill_val),
np.full(shape, fill_val), f"full{shape}_{fill_val}")
# ============================================================================
# 7. Bool-specialized creation
# ============================================================================
@pytest.mark.parametrize("value", [True, False])
def test_full_like_bool(value, cpp):
a = random_array((3, 4))
assert_bit_aligned(cpp.full_like(a, value),
np.full_like(a, value, dtype=bool), f"full_like({value})")
def test_zeros_like_bool(cpp):
a = random_array((3, 4))
assert_bit_aligned(cpp.zeros_like(a, "bool"), np.zeros_like(a, dtype=bool), "zeros_like")
def test_ones_like_bool(cpp):
a = random_array((3, 4))
assert_bit_aligned(cpp.ones_like(a, "bool"), np.ones_like(a, dtype=bool), "ones_like")
# ============================================================================
# 7b. New creation routines: empty, arange, linspace, logspace, geomspace,
# eye, identity, diag
# ============================================================================
# -- empty -------------------------------------------------------------------
@pytest.mark.parametrize("shape", [(5,), (3, 4)])
def test_empty_shape(shape, cpp):
r = cpp.empty(list(shape))
assert r.shape == shape, f"empty{shape} shape"
assert r.dtype == np.float64, f"empty{shape} dtype"
# -- arange ------------------------------------------------------------------
@pytest.mark.parametrize("args,kwargs", [
((10,), {}),
((1, 10), {}),
((0, 10, 2), {}),
((0.5, 5.5, 0.5), {}),
((-3, 3, 1), {}),
])
def test_arange_f64(args, kwargs, cpp):
assert_bit_aligned(cpp.arange(*args, **kwargs), np.arange(*args, **kwargs),
f"arange{args}")
def test_arange_f32_inputs(cpp):
"""numpy 1.23: arange with float32 inputs returns float64."""
s, e, st = np.float32(0), np.float32(10), np.float32(1)
r = cpp.arange(s, e, st)
assert r.dtype == np.float64, "arange(f32 inputs) dtype should be float64"
assert_bit_aligned(r, np.arange(s, e, st), "arange f32 inputs")
def test_arange_single_arg(cpp):
assert_bit_aligned(cpp.arange(5.0), np.arange(5.0), "arange(5.0)")
# -- linspace ----------------------------------------------------------------
@pytest.mark.parametrize("start,stop,num,endpoint", [
(0.0, 1.0, 50, True),
(0.0, 1.0, 50, False),
(1.0, 10.0, 5, True),
(0.0, 0.0, 3, True), # degenerate: same start/stop
(0.0, 1.0, 1, True), # single point
(0.0, 1.0, 0, True), # empty
])
def test_linspace_f64(start, stop, num, endpoint, cpp):
assert_bit_aligned(cpp.linspace(start, stop, num, endpoint),
np.linspace(start, stop, num, endpoint=endpoint),
f"linspace({start},{stop},{num},ep={endpoint})")
def test_linspace_f32_inputs(cpp):
"""numpy 1.23: linspace with float32 inputs returns float64."""
s, e = np.float32(0), np.float32(1)
r = cpp.linspace(s, e, 10)
assert r.dtype == np.float64, "linspace(f32 inputs) dtype should be float64"
assert_bit_aligned(r, np.linspace(s, e, 10), "linspace f32 inputs")
# -- logspace ----------------------------------------------------------------
@pytest.mark.parametrize("start,stop,num,endpoint,base", [
(0.0, 2.0, 5, True, 10.0),
(0.0, 2.0, 5, False, 10.0),
(0.0, 1.0, 4, True, 2.0),
])
def test_logspace_f64(start, stop, num, endpoint, base, cpp):
assert_bit_aligned(cpp.logspace(start, stop, num, endpoint, base),
np.logspace(start, stop, num, endpoint=endpoint, base=base),
f"logspace({start},{stop},{num},ep={endpoint},base={base})")
def test_logspace_f32_inputs(cpp):
"""numpy 1.23: logspace with float32 inputs returns float64."""
s, e = np.float32(0), np.float32(2)
r = cpp.logspace(s, e, 5)
assert r.dtype == np.float64, "logspace(f32 inputs) dtype should be float64"
assert_bit_aligned(r, np.logspace(s, e, 5), "logspace f32 inputs")
# -- geomspace ---------------------------------------------------------------
@pytest.mark.parametrize("start,stop,num,endpoint", [
(1.0, 1000.0, 4, True),
(1.0, 1000.0, 4, False),
(1.0, 256.0, 9, True),
])
def test_geomspace_f64(start, stop, num, endpoint, cpp):
assert_bit_aligned(cpp.geomspace(start, stop, num, endpoint),
np.geomspace(start, stop, num, endpoint=endpoint),
f"geomspace({start},{stop},{num},ep={endpoint})")
def test_geomspace_f32_inputs(cpp):
"""numpy 1.23: geomspace with float32 inputs returns float64."""
s, e = np.float32(1), np.float32(1000)
r = cpp.geomspace(s, e, 4)
assert r.dtype == np.float64, "geomspace(f32 inputs) dtype should be float64"
assert_bit_aligned(r, np.geomspace(s, e, 4), "geomspace f32 inputs")
# -- eye ---------------------------------------------------------------------
@pytest.mark.parametrize("N,M,k", [
(3, -1, 0), # square, k=0
(3, -1, 1), # square, k=+1
(3, -1, -1), # square, k=-1
(3, 5, 0), # wide
(5, 3, 0), # tall
(4, 4, 2), # k beyond diagonal
])
def test_eye(N, M, k, cpp):
if M < 0:
r = cpp.eye(N, M, k)
e = np.eye(N, k=k)
else:
r = cpp.eye(N, M, k)
e = np.eye(N, M, k)
assert_bit_aligned(r, e, f"eye({N},{M},{k})")
def test_eye_default(cpp):
assert_bit_aligned(cpp.eye(4), np.eye(4), "eye(4)")
# -- identity ----------------------------------------------------------------
@pytest.mark.parametrize("n", [1, 3, 5])
def test_identity(n, cpp):
assert_bit_aligned(cpp.identity(n), np.identity(n), f"identity({n})")
# -- diag --------------------------------------------------------------------
def test_diag_vec_to_mat(cpp):
"""1-D → diagonal matrix, k=0"""
v = np.array([1.0, 2.0, 3.0])
assert_bit_aligned(cpp.diag(v), np.diag(v), "diag(vec,k=0)")
@pytest.mark.parametrize("k", [-2, -1, 1, 2])
def test_diag_vec_kdiag(k, cpp):
v = np.array([1.0, 2.0, 3.0])
assert_bit_aligned(cpp.diag(v, k), np.diag(v, k), f"diag(vec,k={k})")
def test_diag_mat_to_vec(cpp):
"""2-D → extract main diagonal"""
m = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]])
assert_bit_aligned(cpp.diag(m), np.diag(m), "diag(mat,k=0)")
@pytest.mark.parametrize("k", [-2, -1, 1, 2])
def test_diag_mat_kdiag(k, cpp):
m = np.arange(16.0).reshape(4, 4)
assert_bit_aligned(cpp.diag(m, k), np.diag(m, k), f"diag(mat,k={k})")
# ============================================================================
# 8. Astype conversions
# ============================================================================
def test_astype_int(cpp):
a = np.array([[1.7, 2.3], [-3.9, 0.5]], dtype=np.float64)
assert_bit_aligned(cpp.astype(a, "int"), a.astype(np.int32), "astype_int")
def test_astype_bool(cpp):
a = np.array([[0.0, 1.0, -1.0], [3.14, 0.0, 0.0]], dtype=np.float64)
assert_bit_aligned(cpp.astype(a, "bool"), a.astype(bool), "astype_bool")
def test_astype_bool_from_int(cpp):
a = np.array([[0, 1, -1], [42, 0, 0]], dtype=np.int32)
assert_bit_aligned(cpp.astype(a, "bool"), a.astype(bool), "astype_bool_from_int")
def test_astype_f64_to_f32(cpp):
a = np.array([1.5, 2.7, -3.1], dtype=np.float64)
assert_bit_aligned(cpp.astype(a, "float32"), a.astype(np.float32), "astype_f64_to_f32")
def test_astype_f32_to_f64(cpp):
a = np.array([1.5, 2.7, -3.1], dtype=np.float32)
assert_bit_aligned(cpp.astype(a, "float64"), a.astype(np.float64), "astype_f32_to_f64")
def test_astype_f64_to_int64(cpp):
a = np.array([1.5, 2.7, -3.1], dtype=np.float64)
assert_bit_aligned(cpp.astype(a, "int64"), a.astype(np.int64), "astype_f64_to_int64")
def test_astype_int_to_f64(cpp):
a = np.array([1, 2, -3], dtype=np.int32)
assert_bit_aligned(cpp.astype(a, "float64"), a.astype(np.float64), "astype_int_to_f64")
def test_astype_int_to_f32(cpp):
a = np.array([1, 2, -3], dtype=np.int32)
assert_bit_aligned(cpp.astype(a, "float32"), a.astype(np.float32), "astype_int_to_f32")
def test_astype_bool_to_f64(cpp):
a = np.array([True, False, True], dtype=bool)
assert_bit_aligned(cpp.astype(a, "float64"), a.astype(np.float64), "astype_bool_to_f64")
def test_astype_bool_to_int(cpp):
a = np.array([True, False, True, False], dtype=bool)
assert_bit_aligned(cpp.astype(a, "int"), a.astype(np.int32), "astype_bool_to_int")
def test_truncate_to_float32(cpp):
a = np.array([1.0 / 3.0, np.pi, np.sqrt(2.0)], dtype=np.float64)
py_r = a.astype(np.float32).astype(np.float64)
assert_bit_aligned(cpp.truncate_to_float32(a), py_r, "truncate_to_float32")
# ============================================================================
# 9. Logical & special values
# ============================================================================
def test_logical_and(cpp):
a = np.array([True, True, False, False])
b = np.array([True, False, True, False])
assert_bit_aligned(cpp.logical_and(a, b), np.logical_and(a, b), "logical_and")
def test_logical_or(cpp):
a = np.array([True, True, False, False])
b = np.array([True, False, True, False])
assert_bit_aligned(cpp.logical_or(a, b), np.logical_or(a, b), "logical_or")
def test_logical_not(cpp):
a = np.array([True, False, True])
assert_bit_aligned(cpp.logical_not(a), np.logical_not(a), "logical_not")
def test_logical_xor(cpp):
a = np.array([True, True, False, False])
b = np.array([True, False, True, False])
assert_bit_aligned(cpp.logical_xor(a, b), np.logical_xor(a, b), "logical_xor")
def test_any_true(cpp):
assert cpp.any(np.array([False, False, True, False])) == True, "any true"
def test_any_false(cpp):
assert cpp.any(np.array([False, False, False])) == False, "any false"
def test_all_true(cpp):
assert cpp.all(np.array([True, True, True])) == True, "all true"
def test_all_false(cpp):
assert cpp.all(np.array([True, False, True])) == False, "all false"
def test_isnan(cpp, dtype):
a = np.array([0.0, np.nan, 1.0, np.nan], dtype=dtype)
assert_bit_aligned(cpp.isnan(a), np.isnan(a), "isnan")
def test_isinf(cpp, dtype):
a = np.array([0.0, np.inf, -np.inf, 1.0], dtype=dtype)
assert_bit_aligned(cpp.isinf(a), np.isinf(a), "isinf")
def test_isfinite(cpp, dtype):
a = np.array([0.0, np.inf, np.nan, 1.0, -np.inf], dtype=dtype)
assert_bit_aligned(cpp.isfinite(a), np.isfinite(a), "isfinite")
# ============================================================================
# 10. Array manipulation
# ============================================================================
def test_diff_1d(cpp, dtype):
a = np.array([1.0, 3.0, 6.0, 10.0], dtype=dtype)
assert_bit_aligned(cpp.diff(a), np.diff(a), "diff 1d")
def test_diff_2d_axis0(cpp, dtype):
a = random_array((5, 4), dtype=dtype)
assert_bit_aligned(cpp.diff(a, 1, 0), np.diff(a, n=1, axis=0), "diff axis=0")
def test_diff_2d_axis1(cpp, dtype):
a = random_array((5, 4), dtype=dtype)
assert_bit_aligned(cpp.diff(a, 1, 1), np.diff(a, n=1, axis=1), "diff axis=1")
def test_diff_2d_axis_neg1(cpp, dtype):
a = random_array((5, 4), dtype=dtype)
assert_bit_aligned(cpp.diff(a, 1, -1), np.diff(a, n=1, axis=-1), "diff axis=-1")
def test_stack(cpp, dtype):
arrays = [random_array((3,), seed=i, dtype=dtype) for i in range(4)]
assert_bit_aligned(cpp.stack(arrays), np.stack(arrays), "stack")
def test_concatenate_1d(cpp, dtype):
arrays = [random_array((3,), seed=i, dtype=dtype) for i in range(3)]
assert_bit_aligned(cpp.concatenate(arrays), np.concatenate(arrays), "concatenate 1d")
def test_concatenate_2d_axis0(cpp, dtype):
arrays = [random_array((2, 3), seed=i, dtype=dtype) for i in range(3)]
assert_bit_aligned(cpp.concatenate(arrays, 0), np.concatenate(arrays, axis=0), "concatenate 2d axis=0")
# Verify default axis=0
assert_bit_aligned(cpp.concatenate(arrays), np.concatenate(arrays), "concatenate 2d default axis")
def test_concatenate_2d_axis1(cpp, dtype):
arrays = [random_array((3, 2), seed=i, dtype=dtype) for i in range(3)]
assert_bit_aligned(cpp.concatenate(arrays, 1), np.concatenate(arrays, axis=1), "concatenate 2d axis=1")
def test_concatenate_2d_axis_neg1(cpp, dtype):
arrays = [random_array((3, 2), seed=i, dtype=dtype) for i in range(3)]
assert_bit_aligned(cpp.concatenate(arrays, -1), np.concatenate(arrays, axis=-1), "concatenate 2d axis=-1")
def test_concatenate_3d_axis0(cpp, dtype):
arrays = [random_array((2, 3, 4), seed=i, dtype=dtype) for i in range(2)]
assert_bit_aligned(cpp.concatenate(arrays, 0), np.concatenate(arrays, axis=0), "concatenate 3d axis=0")
def test_concatenate_3d_axis1(cpp, dtype):
arrays = [random_array((3, 2, 4), seed=i, dtype=dtype) for i in range(2)]
assert_bit_aligned(cpp.concatenate(arrays, 1), np.concatenate(arrays, axis=1), "concatenate 3d axis=1")
def test_concatenate_3d_axis2(cpp, dtype):
arrays = [random_array((3, 4, 2), seed=i, dtype=dtype) for i in range(2)]
assert_bit_aligned(cpp.concatenate(arrays, 2), np.concatenate(arrays, axis=2), "concatenate 3d axis=2")
def test_concatenate_two_arrays(cpp, dtype):
arrays = [random_array((5,), seed=0, dtype=dtype), random_array((7,), seed=1, dtype=dtype)]
assert_bit_aligned(cpp.concatenate(arrays), np.concatenate(arrays), "concatenate two")
def test_concatenate_single(cpp, dtype):
arrays = [random_array((5,), dtype=dtype)]
assert_bit_aligned(cpp.concatenate(arrays), np.concatenate(arrays), "concatenate single")
def test_vstack(cpp, dtype):
arrays = [random_array((1, 3), seed=i, dtype=dtype) for i in range(4)]
assert_bit_aligned(cpp.vstack(arrays), np.vstack(arrays), "vstack")
def test_vstack_1d(cpp, dtype):
arrays = [random_array((3,), seed=i, dtype=dtype) for i in range(4)]
assert_bit_aligned(cpp.vstack(arrays), np.vstack(arrays), "vstack 1d")
def test_hstack(cpp, dtype):
arrays = [random_array((3,), seed=i, dtype=dtype) for i in range(3)]
assert_bit_aligned(cpp.hstack(arrays), np.hstack(arrays), "hstack 1d")
def test_hstack_2d(cpp, dtype):
arrays = [random_array((3, 2), seed=i, dtype=dtype) for i in range(3)]
assert_bit_aligned(cpp.hstack(arrays), np.hstack(arrays), "hstack 2d")
# -- Concatenate complex / edge-case tests ----------------------------------
def test_concatenate_4d_axis0(cpp, dtype):
arrays = [random_array((2, 3, 4, 5), seed=i, dtype=dtype) for i in range(2)]
assert_bit_aligned(cpp.concatenate(arrays, 0), np.concatenate(arrays, axis=0), "concatenate 4d axis=0")
def test_concatenate_4d_axis2(cpp, dtype):
arrays = [random_array((2, 3, 2, 5), seed=i, dtype=dtype) for i in range(2)]
assert_bit_aligned(cpp.concatenate(arrays, 2), np.concatenate(arrays, axis=2), "concatenate 4d axis=2")
def test_concatenate_4d_axis_neg2(cpp, dtype):
arrays = [random_array((2, 3, 2, 5), seed=i, dtype=dtype) for i in range(2)]
assert_bit_aligned(cpp.concatenate(arrays, -2), np.concatenate(arrays, axis=-2), "concatenate 4d axis=-2")
def test_concatenate_unequal_axis_sizes(cpp, dtype):
"""Concatenate arrays of different sizes along the concatenation axis."""
a = random_array((3, 2), seed=1, dtype=dtype)
b = random_array((3, 4), seed=2, dtype=dtype)
c = random_array((3, 1), seed=3, dtype=dtype)
assert_bit_aligned(cpp.concatenate([a, b, c], 1),
np.concatenate([a, b, c], axis=1), "concat unequal axis sizes")
def test_concatenate_many_arrays(cpp, dtype):
"""Concatenate 10 arrays along axis=0."""
arrays = [random_array((3,), seed=i, dtype=dtype) for i in range(10)]
assert_bit_aligned(cpp.concatenate(arrays), np.concatenate(arrays), "concat 10 arrays")
def test_concatenate_large_3d(cpp, dtype):
"""Large 3D concatenation along middle axis."""
arrays = [random_array((50, 20, 30), seed=i, dtype=dtype) for i in range(3)]
assert_bit_aligned(cpp.concatenate(arrays, 1), np.concatenate(arrays, axis=1), "concat large 3d axis=1")
def test_concatenate_large_2d_axis0(cpp, dtype):
"""Large 2D concatenation — 500 rows each, 4 arrays."""
arrays = [random_array((500, 10), seed=i, dtype=dtype) for i in range(4)]
assert_bit_aligned(cpp.concatenate(arrays, 0), np.concatenate(arrays, axis=0), "concat large 2d axis=0")
def test_concatenate_large_2d_axis1(cpp, dtype):
"""Large 2D concatenation — 500 cols each, 3 arrays."""
arrays = [random_array((10, 500), seed=i, dtype=dtype) for i in range(3)]
assert_bit_aligned(cpp.concatenate(arrays, 1), np.concatenate(arrays, axis=1), "concat large 2d axis=1")
def test_concatenate_identity(cpp, dtype):
"""Concatenating a single array returns identical copy."""
a = random_array((3, 4), seed=42, dtype=dtype)
assert_bit_aligned(cpp.concatenate([a], 0), np.concatenate([a], axis=0), "concat identity")
assert_bit_aligned(cpp.concatenate([a], 1), np.concatenate([a], axis=1), "concat identity axis=1")
def test_concatenate_zeros(cpp, dtype):
"""Concatenate arrays of zeros."""
a = np.zeros((2, 3), dtype=dtype)
b = np.zeros((2, 5), dtype=dtype)
assert_bit_aligned(cpp.concatenate([a, b], 1), np.concatenate([a, b], axis=1), "concat zeros")
def test_concatenate_ones(cpp, dtype):
"""Concatenate arrays of ones."""
a = np.ones((3, 2), dtype=dtype)
b = np.ones((5, 2), dtype=dtype)
assert_bit_aligned(cpp.concatenate([a, b], 0), np.concatenate([a, b], axis=0), "concat ones")
def test_concatenate_3d_axis_neg2(cpp, dtype):
"""3D concatenate along axis=-2 (middle axis)."""
arrays = [random_array((2, 3, 4), seed=i, dtype=dtype) for i in range(3)]
assert_bit_aligned(cpp.concatenate(arrays, -2), np.concatenate(arrays, axis=-2), "concat 3d axis=-2")
def test_concatenate_3d_axis_neg3(cpp, dtype):
"""3D concatenate along axis=-3 (first axis)."""
arrays = [random_array((2, 3, 4), seed=i, dtype=dtype) for i in range(2)]
assert_bit_aligned(cpp.concatenate(arrays, -3), np.concatenate(arrays, axis=-3), "concat 3d axis=-3")
def test_concatenate_5d(cpp, dtype):
"""5D concatenate along various axes."""
arrays = [random_array((2, 3, 2, 3, 2), seed=i, dtype=dtype) for i in range(2)]
assert_bit_aligned(cpp.concatenate(arrays, 0), np.concatenate(arrays, axis=0), "concat 5d axis=0")
assert_bit_aligned(cpp.concatenate(arrays, 2), np.concatenate(arrays, axis=2), "concat 5d axis=2")
assert_bit_aligned(cpp.concatenate(arrays, -1), np.concatenate(arrays, axis=-1), "concat 5d axis=-1")
def test_where_scalar(cpp, dtype):
cond = np.array([True, False, True, False, True])
assert_bit_aligned(cpp.where(cond, dtype(10.0), dtype(-1.0)),
np.where(cond, dtype(10.0), dtype(-1.0)), "where scalar")
def test_where_array(cpp, dtype):
cond = np.array([True, False, True, False])
x = np.array([1.0, 2.0, 3.0, 4.0], dtype=dtype)
y = np.array([-1.0, -2.0, -3.0, -4.0], dtype=dtype)
assert_bit_aligned(cpp.where(cond, x, y), np.where(cond, x, y), "where array")
def test_transpose_1d(cpp, dtype):
a = random_array((5,), dtype=dtype)
assert_bit_aligned(cpp.transpose(a), np.transpose(a), "transpose 1d")
def test_transpose_2d(cpp, dtype):
a = random_array((3, 5), dtype=dtype)
assert_bit_aligned(cpp.transpose(a), np.transpose(a), "transpose 2d")
def test_flatten(cpp, dtype):
a = random_array((3, 4), dtype=dtype)
assert_bit_aligned(cpp.flatten(a), a.flatten(), "flatten")
# Mean axis
def test_mean_axis0_2d(cpp, dtype):
a = random_array((4, 5), dtype=dtype)
assert_bit_aligned(cpp.mean(a, 0), np.mean(a, axis=0), "mean axis=0")
def test_mean_axis1_2d(cpp, dtype):
a = random_array((4, 5), dtype=dtype)
assert_bit_aligned(cpp.mean(a, 1), np.mean(a, axis=1), "mean axis=1")
def test_mean_axis_neg1_2d(cpp, dtype):
a = random_array((4, 5), dtype=dtype)
assert_bit_aligned(cpp.mean(a, -1), np.mean(a, axis=-1), "mean axis=-1")
def test_mean_axis0_3d(cpp, dtype):
a = random_array((3, 4, 5), dtype=dtype)
assert_bit_aligned(cpp.mean(a, 0), np.mean(a, axis=0), "mean 3d axis=0")
def test_mean_axis1_3d(cpp, dtype):
a = random_array((3, 4, 5), dtype=dtype)
assert_bit_aligned(cpp.mean(a, 1), np.mean(a, axis=1), "mean 3d axis=1")
def test_mean_axis2_3d(cpp, dtype):
a = random_array((3, 4, 5), dtype=dtype)
assert_bit_aligned(cpp.mean(a, 2), np.mean(a, axis=2), "mean 3d axis=2")
# ── issue #001: mean_axis pairwise_sum vs sequential (float32 ULP) ──────────
#
# Reported scenario: (4, 2) float32 polygon → mean(axis=0) → (2,) center.
# Root cause (original analysis): pairwise_sum used instead of sequential sum
# for small axis sizes. The fix is confirmed present: pairwise_sum already
# falls back to sequential accumulation for n < 8. These tests lock in
# bit-exact behaviour for the exact shapes and n ≥ 8 boundary cases that were
# previously uncovered.
def test_mean_axis_polygon_center_f32(cpp):
"""issue #001 — (4,2) float32 polygon center via mean(axis=0) → (2,)."""
poly = np.array([
[10.5, 20.3],
[30.7, 40.1],
[50.9, 60.2],
[70.4, 80.8],
], dtype=np.float32)
assert_bit_aligned(cpp.mean(poly, 0), np.mean(poly, axis=0),
"polygon center axis=0")
assert_bit_aligned(cpp.mean(poly, 1), np.mean(poly, axis=1),
"polygon row-mean axis=1")
def test_mean_axis_polygon_center_rounding_f32(cpp):
"""issue #001 — float32 values near rounding boundary, axis=0."""
# 2^23 = 8388608 exactly representable; +1 triggers ULP rounding in f32
v = np.float32(2**23)
poly = np.array([
[v, 1.0],
[v, 1.0],
[v, 1.0],
[1.0, v ],
], dtype=np.float32)
assert_bit_aligned(cpp.mean(poly, 0), np.mean(poly, axis=0),
"polygon rounding axis=0")
@pytest.mark.parametrize("n_axis", [8, 9, 16, 17, 100, 128, 129])
def test_mean_axis_large_fiber(cpp, dtype, n_axis):
"""issue #001 — mean_axis for axis sizes ≥ 8 (pairwise_sum medium / recursive path)."""
a = random_array((3, n_axis), dtype=dtype, seed=1001 + n_axis)
assert_bit_aligned(cpp.mean(a, 1), np.mean(a, axis=1),
f"mean (3,{n_axis}) axis=1")
b = random_array((n_axis, 3), dtype=dtype, seed=1001 + n_axis)
assert_bit_aligned(cpp.mean(b, 0), np.mean(b, axis=0),
f"mean ({n_axis},3) axis=0")
def test_mean_axis_n8_boundary_f32(cpp):
"""issue #001 — n=8 boundary with pairwise (stride=1) and sequential (stride>1) paths.
numpy's accumulation order depends on the axis memory stride:
stride == 1 (last/contiguous axis) → pairwise
stride > 1 (non-contiguous axis) → sequential