forked from data-apis/array-api-tests
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_special_cases.py
More file actions
1626 lines (1339 loc) · 56.9 KB
/
Copy pathtest_special_cases.py
File metadata and controls
1626 lines (1339 loc) · 56.9 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
"""
Tests for special cases.
Most test cases for special casing are built on runtime via the parametrized
tests test_unary/test_binary/test_iop. Most of this file consists of utility
classes and functions, all bought together to create the test cases (pytest
params), to finally be run through generalised test logic.
TODO: test integer arrays for relevant special cases
"""
# We use __future__ for forward reference type hints - this will work for even py3.8.0
# See https://stackoverflow.com/a/33533514/5193926
from __future__ import annotations
import inspect
import math
import operator
import os
import re
from dataclasses import dataclass, field
from decimal import ROUND_HALF_EVEN, Decimal
from enum import Enum, auto
from typing import Any, Callable, Dict, List, Optional, Protocol, Tuple, Literal
from warnings import warn, filterwarnings, catch_warnings
import pytest
from hypothesis import given, note, settings, assume
from hypothesis import strategies as st
from hypothesis.errors import NonInteractiveExampleWarning
from array_api_tests.typing import Array, DataType
from . import dtype_helpers as dh
from . import hypothesis_helpers as hh
from . import pytest_helpers as ph
from . import xp, xps
from .stubs import category_to_funcs
UnaryCheck = Callable[[float], bool]
BinaryCheck = Callable[[float, float], bool]
def make_strict_eq(v: float) -> UnaryCheck:
if math.isnan(v):
return math.isnan
if v == 0:
if ph.is_pos_zero(v):
return ph.is_pos_zero
else:
return ph.is_neg_zero
def strict_eq(i: float) -> bool:
return i == v
return strict_eq
def make_strict_neq(v: float) -> UnaryCheck:
strict_eq = make_strict_eq(v)
def strict_neq(i: float) -> bool:
return not strict_eq(i)
return strict_neq
def make_rough_eq(v: float) -> UnaryCheck:
assert math.isfinite(v) # sanity check
def rough_eq(i: float) -> bool:
return math.isclose(i, v, abs_tol=0.01)
return rough_eq
def make_gt(v: float) -> UnaryCheck:
assert not math.isnan(v) # sanity check
def gt(i: float) -> bool:
return i > v
return gt
def make_lt(v: float) -> UnaryCheck:
assert not math.isnan(v) # sanity check
def lt(i: float) -> bool:
return i < v
return lt
def make_or(cond1: UnaryCheck, cond2: UnaryCheck) -> UnaryCheck:
def or_(i: float) -> bool:
return cond1(i) or cond2(i)
return or_
def make_and(cond1: UnaryCheck, cond2: UnaryCheck) -> UnaryCheck:
def and_(i: float) -> bool:
return cond1(i) and cond2(i)
return and_
def make_not_cond(cond: UnaryCheck) -> UnaryCheck:
def not_cond(i: float) -> bool:
return not cond(i)
return not_cond
def absify_cond(cond: UnaryCheck) -> UnaryCheck:
def abs_cond(i: float) -> bool:
return cond(abs(i))
return abs_cond
repr_to_value = {
"NaN": float("nan"),
"infinity": float("inf"),
"0": 0.0,
"1": 1.0,
"False": 0.0,
"True": 1.0,
}
r_value = re.compile(r"([+-]?)(.+)")
r_pi = re.compile(r"(\d?)π(?:/(\d))?")
@dataclass
class ParseError(ValueError):
value: str
def parse_value(value_str: str) -> float:
"""
Parses a value string to return a float, e.g.
>>> parse_value('1')
1.
>>> parse_value('-infinity')
-float('inf')
>>> parse_value('3π/4')
2.356194490192345
"""
m = r_value.match(value_str)
if m is None:
raise ParseError(value_str)
if pi_m := r_pi.match(m.group(2)):
value = math.pi
if numerator := pi_m.group(1):
value *= int(numerator)
if denominator := pi_m.group(2):
value /= int(denominator)
else:
try:
value = repr_to_value[m.group(2)]
except KeyError as e:
raise ParseError(value_str) from e
if sign := m.group(1):
if sign == "-":
value *= -1
return value
r_code = re.compile(r"``([^\s]+)``")
r_approx_value = re.compile(
rf"an implementation-dependent approximation to {r_code.pattern}"
)
r_not = re.compile("not (.+)")
r_equal_to = re.compile(f"equal to {r_code.pattern}")
r_array_element = re.compile(r"``([+-]?)x([12])_i``")
r_either_code = re.compile(f"either {r_code.pattern} or {r_code.pattern}")
r_gt = re.compile(f"greater than {r_code.pattern}")
r_lt = re.compile(f"less than {r_code.pattern}")
class FromDtypeFunc(Protocol):
"""
Type hint for functions that return an elements strategy for arrays of the
given dtype, e.g. xps.from_dtype().
"""
def __call__(self, dtype: DataType, **kw) -> st.SearchStrategy[float]:
...
@dataclass
class BoundFromDtype(FromDtypeFunc):
"""
A xps.from_dtype()-like callable with bounded kwargs, filters and base function.
We can bound:
1. Keyword arguments that xps.from_dtype() can use, e.g.
>>> from_dtype = BoundFromDtype(kwargs={'min_value': 0, 'allow_infinity': False})
>>> strategy = from_dtype(xp.float64)
is equivalent to
>>> strategy = xps.from_dtype(xp.float64, min_value=0, allow_infinity=False)
i.e. a strategy that generates finite floats above 0
2. Functions that filter the elements strategy that xps.from_dtype() returns, e.g.
>>> from_dtype = BoundFromDtype(filter=lambda i: i != 0)
>>> strategy = from_dtype(xp.float64)
is equivalent to
>>> strategy = xps.from_dtype(xp.float64).filter(lambda i: i != 0)
i.e. a strategy that generates any float except +0 and -0
3. The underlying function that returns an elements strategy from a dtype, e.g.
>>> from_dtype = BoundFromDtype(
... from_dtype=lambda d: st.integers(
... math.ceil(xp.finfo(d).min), math.floor(xp.finfo(d).max)
... )
... )
>>> strategy = from_dtype(xp.float64)
is equivalent to
>>> strategy = st.integers(
... math.ceil(xp.finfo(xp.float64).min), math.floor(xp.finfo(xp.float64).max)
... )
i.e. a strategy that generates integers (within the dtype's range)
This is useful to avoid translating special case conditions into either a
dict, filter or "base func", and instead allows us to generalise these three
components into a callable equivalent of xps.from_dtype().
Additionally, BoundFromDtype instances can be added together. This allows us
to keep parsing each condition individually - so we don't need to duplicate
complicated parsing code - as ultimately we can represent (and subsequently
test for) special cases which have more than one condition per array, e.g.
"If x1_i is greater than 0 and x1_i is not 42, ..."
could be translated as
>>> gt_0_from_dtype = BoundFromDtype(kwargs={'min_value': 0})
>>> not_42_from_dtype = BoundFromDtype(filter=lambda i: i != 42)
>>> gt_0_from_dtype + not_42_from_dtype
BoundFromDtype(kwargs={'min_value': 0}, filter=<lambda>(i))
"""
kwargs: Dict[str, Any] = field(default_factory=dict)
filter_: Optional[Callable[[Array], bool]] = None
base_func: Optional[FromDtypeFunc] = None
def __call__(self, dtype: DataType, **kw) -> st.SearchStrategy[float]:
assert len(kw) == 0 # sanity check
from_dtype = self.base_func or hh.from_dtype
strat = from_dtype(dtype, **self.kwargs)
if self.filter_ is not None:
strat = strat.filter(self.filter_)
return strat
def __add__(self, other: BoundFromDtype) -> BoundFromDtype:
for k in self.kwargs.keys():
if k in other.kwargs.keys():
assert self.kwargs[k] == other.kwargs[k] # sanity check
kwargs = {**self.kwargs, **other.kwargs}
if self.filter_ is not None and other.filter_ is not None:
filter_ = lambda i: self.filter_(i) and other.filter_(i)
else:
if self.filter_ is not None:
filter_ = self.filter_
elif other.filter_ is not None:
filter_ = other.filter_
else:
filter_ = None
# sanity check
assert not (self.base_func is not None and other.base_func is not None)
if self.base_func is not None:
base_func = self.base_func
elif other.base_func is not None:
base_func = other.base_func
else:
base_func = None
return BoundFromDtype(kwargs, filter_, base_func)
def wrap_strat_as_from_dtype(strat: st.SearchStrategy[float]) -> FromDtypeFunc:
"""
Wraps an elements strategy as a xps.from_dtype()-like function
"""
def from_dtype(dtype: DataType, **kw) -> st.SearchStrategy[float]:
assert len(kw) == 0 # sanity check
return strat
return from_dtype
def parse_cond(cond_str: str) -> Tuple[UnaryCheck, str, BoundFromDtype]:
"""
Parses a Sphinx-formatted condition string to return:
1. A function which takes an input and returns True if it meets the
condition, otherwise False.
2. A string template for expressing the condition.
3. A xps.from_dtype()-like function which returns a strategy that generates
elements that meet the condition.
e.g.
>>> cond, expr_template, from_dtype = parse_cond('greater than ``0``')
>>> cond(42)
True
>>> cond(-123)
False
>>> expr_template.replace('{}', 'x_i')
'x_i > 0'
>>> strategy = from_dtype(xp.float64)
>>> for _ in range(5):
... print(strategy.example())
1.
0.1
1.7976931348623155e+179
inf
124.978
"""
# We first identify whether the condition starts with "not". If so, we note
# this but parse the condition as if it was not negated.
if m := r_not.match(cond_str):
cond_str = m.group(1)
not_cond = True
else:
not_cond = False
# We parse the condition to identify the condition function, expression
# template, and xps.from_dtype()-like condition strategy.
kwargs = {}
filter_ = None
from_dtype = None # type: ignore
if m := r_code.match(cond_str):
value = parse_value(m.group(1))
cond = make_strict_eq(value)
expr_template = "{} is " + m.group(1)
from_dtype = wrap_strat_as_from_dtype(st.just(value))
elif m := r_either_code.match(cond_str):
v1 = parse_value(m.group(1))
v2 = parse_value(m.group(2))
cond = make_or(make_strict_eq(v1), make_strict_eq(v2))
expr_template = "({} is " + m.group(1) + " or {} == " + m.group(2) + ")"
from_dtype = wrap_strat_as_from_dtype(st.sampled_from([v1, v2]))
elif m := r_equal_to.match(cond_str):
value = parse_value(m.group(1))
if math.isnan(value):
raise ParseError(cond_str)
cond = lambda i: i == value
expr_template = "{} == " + m.group(1)
elif m := r_gt.match(cond_str):
value = parse_value(m.group(1))
cond = make_gt(value)
expr_template = "{} > " + m.group(1)
kwargs = {"min_value": value, "exclude_min": True}
elif m := r_lt.match(cond_str):
value = parse_value(m.group(1))
cond = make_lt(value)
expr_template = "{} < " + m.group(1)
kwargs = {"max_value": value, "exclude_max": True}
elif cond_str in ["finite", "a finite number"]:
cond = math.isfinite
expr_template = "isfinite({})"
kwargs = {"allow_nan": False, "allow_infinity": False}
elif cond_str in "a positive (i.e., greater than ``0``) finite number":
cond = lambda i: math.isfinite(i) and i > 0
expr_template = "isfinite({}) and {} > 0"
kwargs = {
"allow_nan": False,
"allow_infinity": False,
"min_value": 0,
"exclude_min": True,
}
elif cond_str == "a negative (i.e., less than ``0``) finite number":
cond = lambda i: math.isfinite(i) and i < 0
expr_template = "isfinite({}) and {} < 0"
kwargs = {
"allow_nan": False,
"allow_infinity": False,
"max_value": 0,
"exclude_max": True,
}
elif cond_str == "positive":
cond = lambda i: math.copysign(1, i) == 1
expr_template = "copysign(1, {}) == 1"
# We assume (positive) zero is special cased seperately
kwargs = {"min_value": 0, "exclude_min": True}
elif cond_str == "negative":
cond = lambda i: math.copysign(1, i) == -1
expr_template = "copysign(1, {}) == -1"
# We assume (negative) zero is special cased seperately
kwargs = {"max_value": 0, "exclude_max": True}
elif "nonzero finite" in cond_str:
cond = lambda i: math.isfinite(i) and i != 0
expr_template = "isfinite({}) and {} != 0"
kwargs = {"allow_nan": False, "allow_infinity": False}
filter_ = lambda n: n != 0
elif cond_str == "an integer value":
cond = lambda i: i.is_integer()
expr_template = "{}.is_integer()"
from_dtype = integers_from_dtype # type: ignore
elif cond_str == "an odd integer value":
cond = lambda i: i.is_integer() and i % 2 == 1
expr_template = "{}.is_integer() and {} % 2 == 1"
if not_cond:
expr_template = f"({expr_template})"
def from_dtype(dtype: DataType, **kw) -> st.SearchStrategy[float]:
return integers_from_dtype(dtype, **kw).filter(lambda n: n % 2 == 1)
else:
raise ParseError(cond_str)
if not_cond:
# We handle negated conitions by simply negating the condition function
# and using it as a filter for xps.from_dtype() (or an equivalent).
cond = make_not_cond(cond)
expr_template = f"not {expr_template}"
filter_ = cond
return cond, expr_template, BoundFromDtype(filter_=filter_)
else:
return cond, expr_template, BoundFromDtype(kwargs, filter_, from_dtype)
def parse_result(result_str: str) -> Tuple[UnaryCheck, str]:
"""
Parses a Sphinx-formatted result string to return:
1. A function which takes an input and returns True if it is the expected
result (or meets the condition of the expected result), otherwise False.
2. A string that expresses the result.
e.g.
>>> check_result, expr = parse_result('``42``')
>>> check_result(7)
False
>>> check_result(42)
True
>>> expr
'42'
"""
if m := r_code.match(result_str):
value = parse_value(m.group(1))
check_result = make_strict_eq(value) # type: ignore
expr = m.group(1)
elif m := r_approx_value.match(result_str):
value = parse_value(m.group(1))
check_result = make_rough_eq(value) # type: ignore
repr_ = m.group(1).replace("π", "pi") # for pytest param names
expr = f"roughly {repr_}"
elif "positive" in result_str:
def check_result(result: float) -> bool:
if math.isnan(result):
# The sign of NaN is out-of-scope
return True
return math.copysign(1, result) == 1
expr = "positive sign"
elif "negative" in result_str:
def check_result(result: float) -> bool:
if math.isnan(result):
# The sign of NaN is out-of-scope
return True
return math.copysign(1, result) == -1
expr = "negative sign"
else:
raise ParseError(result_str)
return check_result, expr
def parse_complex_value(value_str: str) -> complex:
"""
Parses a complex value string to return a complex number, e.g.
>>> parse_complex_value('+0 + 0j')
0j
>>> parse_complex_value('NaN + NaN j')
(nan+nanj)
>>> parse_complex_value('0 + NaN j')
nanj
>>> parse_complex_value('+0 + πj/2')
1.5707963267948966j
>>> parse_complex_value('+infinity + 3πj/4')
(inf+2.356194490192345j)
Handles formats: "A + Bj", "A + B j", "A + πj/N", "A + Nπj/M"
"""
m = r_complex_value.match(value_str)
if m is None:
raise ParseError(value_str)
# Parse real part with its sign
real_sign = m.group(1) if m.group(1) else "+"
real_val_str = m.group(2)
real_val = parse_value(real_sign + real_val_str)
# Parse imaginary part with its sign
imag_sign = m.group(3)
# Group 4 is πj form (e.g., "πj/2"), group 5 is plain form (e.g., "NaN")
if m.group(4): # πj form
imag_val_str_raw = m.group(4)
# Remove 'j' to get coefficient: "πj/2" -> "π/2"
imag_val_str = imag_val_str_raw.replace('j', '')
else: # plain form
imag_val_str_raw = m.group(5)
# Strip trailing 'j' if present: "0j" -> "0"
imag_val_str = imag_val_str_raw[:-1] if imag_val_str_raw.endswith('j') else imag_val_str_raw
imag_val = parse_value(imag_sign + imag_val_str)
return complex(real_val, imag_val)
def make_strict_eq_complex(v: complex) -> Callable[[complex], bool]:
"""
Creates a checker for complex values that respects sign of zero and NaN.
"""
real_check = make_strict_eq(v.real)
imag_check = make_strict_eq(v.imag)
def strict_eq_complex(z: complex) -> bool:
return real_check(z.real) and imag_check(z.imag)
return strict_eq_complex
def parse_complex_cond(
a_cond_str: str, b_cond_str: str
) -> Tuple[Callable[[complex], bool], str, FromDtypeFunc]:
"""
Parses complex condition strings for real (a) and imaginary (b) parts.
Returns:
- cond: Function that checks if a complex number meets the condition
- expr: String expression for the condition
- from_dtype: Strategy generator for complex numbers meeting the condition
"""
# Parse conditions for real and imaginary parts separately
a_cond, a_expr_template, a_from_dtype = parse_cond(a_cond_str)
b_cond, b_expr_template, b_from_dtype = parse_cond(b_cond_str)
# Create compound condition
def complex_cond(z: complex) -> bool:
return a_cond(z.real) and b_cond(z.imag)
# Create expression
a_expr = a_expr_template.replace("{}", "real(x_i)")
b_expr = b_expr_template.replace("{}", "imag(x_i)")
expr = f"{a_expr} and {b_expr}"
# Create strategy that generates complex numbers
def complex_from_dtype(dtype: DataType, **kw) -> st.SearchStrategy[complex]:
assert len(kw) == 0 # sanity check
# For complex dtype, we need to get the corresponding float dtype
# complex64 -> float32, complex128 -> float64
if hasattr(dtype, 'name'):
if 'complex64' in str(dtype):
float_dtype = xp.float32
elif 'complex128' in str(dtype):
float_dtype = xp.float64
else:
# Fallback to float64
float_dtype = xp.float64
else:
float_dtype = xp.float64
real_strat = a_from_dtype(float_dtype)
imag_strat = b_from_dtype(float_dtype)
return st.builds(complex, real_strat, imag_strat)
return complex_cond, expr, complex_from_dtype
def _check_component_with_tolerance(actual: float, expected: float, allow_any_sign: bool) -> bool:
"""
Helper to check if actual matches expected, with optional sign flexibility and tolerance.
"""
if allow_any_sign and not math.isnan(expected):
return abs(actual) == abs(expected) or math.isclose(abs(actual), abs(expected), abs_tol=0.01)
elif not math.isnan(expected):
check_fn = make_strict_eq(expected) if expected == 0 or math.isinf(expected) else make_rough_eq(expected)
return check_fn(actual)
else:
return math.isnan(actual)
def parse_complex_result(result_str: str) -> Tuple[Callable[[complex], bool], str]:
"""
Parses a complex result string to return a checker and expression.
Handles cases like:
- "``+0 + 0j``" - exact complex value
- "``0 + NaN j`` (sign of the real component is unspecified)"
- "``+0 + πj/2``" - with π expressions (uses approximate equality)
"""
# Check for unspecified sign notes
unspecified_real_sign = "sign of the real component is unspecified" in result_str
unspecified_imag_sign = "sign of the imaginary component is unspecified" in result_str
# Extract the complex value from backticks - need to handle spaces in complex values
# Pattern: ``...`` where ... can contain spaces (for complex values like "0 + NaN j")
m = re.search(r"``([^`]+)``", result_str)
if m:
value_str = m.group(1)
# Check if the value contains π expressions (for approximate comparison)
has_pi = 'π' in value_str
try:
expected = parse_complex_value(value_str)
except ParseError:
raise ParseError(result_str)
# Create checker based on whether signs are unspecified and whether π is involved
if has_pi:
# Use approximate equality for both real and imaginary parts if they involve π
def check_result(z: complex) -> bool:
real_match = _check_component_with_tolerance(z.real, expected.real, unspecified_real_sign)
imag_match = _check_component_with_tolerance(z.imag, expected.imag, unspecified_imag_sign)
return real_match and imag_match
elif unspecified_real_sign and not math.isnan(expected.real):
# Allow any sign for real part
def check_result(z: complex) -> bool:
imag_check = make_strict_eq(expected.imag)
return abs(z.real) == abs(expected.real) and imag_check(z.imag)
elif unspecified_imag_sign and not math.isnan(expected.imag):
# Allow any sign for imaginary part
def check_result(z: complex) -> bool:
real_check = make_strict_eq(expected.real)
return real_check(z.real) and abs(z.imag) == abs(expected.imag)
elif unspecified_real_sign and unspecified_imag_sign:
# Allow any sign for both parts
def check_result(z: complex) -> bool:
return abs(z.real) == abs(expected.real) and abs(z.imag) == abs(expected.imag)
else:
# Exact match including signs
check_result = make_strict_eq_complex(expected)
expr = value_str
return check_result, expr
else:
raise ParseError(result_str)
class Case(Protocol):
cond_expr: str
result_expr: str
raw_case: Optional[str]
def cond(self, *args) -> bool:
...
def check_result(self, *args) -> bool:
...
def __str__(self) -> str:
return f"{self.cond_expr} -> {self.result_expr}"
def __repr__(self) -> str:
return f"{self.__class__.__name__}(<{self}>)"
r_case_block = re.compile(
r"\*\*Special [Cc]ases\*\*\n+((?:(.*\n)+))\n+\s*"
r"(?:.+\n--+)?(?:\.\. versionchanged.*)?"
)
r_case = re.compile(r"\s+-\s*(.*)\.")
class UnaryCond(Protocol):
def __call__(self, i: float) -> bool:
...
class UnaryResultCheck(Protocol):
def __call__(self, i: float, result: float) -> bool:
...
@dataclass(repr=False)
class UnaryCase(Case):
cond_expr: str
result_expr: str
cond_from_dtype: FromDtypeFunc
cond: UnaryCheck
check_result: UnaryResultCheck
raw_case: Optional[str] = field(default=None)
is_complex: bool = field(default=False)
r_unary_case = re.compile("If ``x_i`` is (.+), the result is (.+)")
r_already_int_case = re.compile(
"If ``x_i`` is already integer-valued, the result is ``x_i``"
)
r_even_round_halves_case = re.compile(
"If two integers are equally close to ``x_i``, "
"the result is the even integer closest to ``x_i``"
)
r_nan_signbit = re.compile(
"If ``x_i`` is ``NaN`` and the sign bit of ``x_i`` is ``(.+)``, "
"the result is ``(.+)``"
)
# Regex patterns for complex special cases
r_complex_marker = re.compile(
r"For complex floating-point operands, let ``a = real\(x_i\)``, ``b = imag\(x_i\)``"
)
r_complex_case = re.compile(r"If ``a`` is (.+) and ``b`` is (.+), the result is (.+)")
# Matches complex values like "+0 + 0j", "NaN + NaN j", "infinity + NaN j", "πj/2", "3πj/4"
# Two formats: 1) πj/N expressions where j is part of the coefficient, 2) plain values followed by j
r_complex_value = re.compile(
r"([+-]?)([^\s]+)\s*([+-])\s*(?:(\d*πj(?:/\d+)?)|([^\s]+))\s*j?"
)
def integers_from_dtype(dtype: DataType, **kw) -> st.SearchStrategy[float]:
"""
Returns a strategy that generates float-casted integers within the bounds of dtype.
"""
for k in kw.keys():
# sanity check
assert k in ["min_value", "max_value", "exclude_min", "exclude_max"]
m, M = dh.dtype_ranges[dtype]
if "min_value" in kw.keys():
m = kw["min_value"]
if "exclude_min" in kw.keys():
m += 1
if "max_value" in kw.keys():
M = kw["max_value"]
if "exclude_max" in kw.keys():
M -= 1
return st.integers(math.ceil(m), math.floor(M)).map(float)
def trailing_halves_from_dtype(dtype: DataType) -> st.SearchStrategy[float]:
"""
Returns a strategy that generates floats that end with .5 and are within the
bounds of dtype.
"""
# We bound our base integers strategy to a range of values which should be
# able to represent a decimal 5 when .5 is added or subtracted.
if dtype == xp.float32:
abs_max = 10**4
else:
abs_max = 10**16
return st.sampled_from([0.5, -0.5]).flatmap(
lambda half: st.integers(-abs_max, abs_max).map(lambda n: n + half)
)
already_int_case = UnaryCase(
cond_expr="x_i.is_integer()",
cond=lambda i: i.is_integer(),
cond_from_dtype=integers_from_dtype,
result_expr="x_i",
check_result=lambda i, result: i == result,
)
even_round_halves_case = UnaryCase(
cond_expr="modf(i)[0] == 0.5",
cond=lambda i: math.modf(i)[0] == 0.5,
cond_from_dtype=trailing_halves_from_dtype,
result_expr="Decimal(i).to_integral_exact(ROUND_HALF_EVEN)",
check_result=lambda i, result: (
result == float(Decimal(i).to_integral_exact(ROUND_HALF_EVEN))
),
)
def make_nan_signbit_case(signbit: Literal[0, 1], expected: bool) -> UnaryCase:
if signbit:
sign = -1
nan_expr = "-NaN"
float_arg = "-nan"
else:
sign = 1
nan_expr = "+NaN"
float_arg = "nan"
return UnaryCase(
cond_expr=f"x_i is {nan_expr}",
cond=lambda i: math.isnan(i) and math.copysign(1, i) == sign,
cond_from_dtype=lambda _: st.just(float(float_arg)),
result_expr=str(expected),
check_result=lambda _, result: result == float(expected),
)
def make_unary_check_result(check_just_result: UnaryCheck) -> UnaryResultCheck:
def check_result(i: float, result: float) -> bool:
return check_just_result(result)
return check_result
def make_complex_unary_check_result(check_fn: Callable[[complex], bool]) -> UnaryResultCheck:
"""Wraps a complex check function for use in UnaryCase."""
def check_result(in_value, out_value):
# in_value is complex, out_value is complex
return check_fn(out_value)
return check_result
def parse_unary_case_block(case_block: str, func_name: str, record_list: Optional[List[str]] = None) -> List[UnaryCase]:
"""
Parses a Sphinx-formatted docstring of a unary function to return a list of
codified unary cases, e.g.
>>> def sqrt(x):
... '''
... Calculates the square root
...
... **Special Cases**
...
... For floating-point operands,
...
... - If ``x_i`` is less than ``0``, the result is ``NaN``.
... - If ``x_i`` is ``NaN``, the result is ``NaN``.
... - If ``x_i`` is ``+0``, the result is ``+0``.
... - If ``x_i`` is ``-0``, the result is ``-0``.
... - If ``x_i`` is ``+infinity``, the result is ``+infinity``.
...
... Parameters
... ----------
... x: array
... input array
...
... Returns
... -------
... out: array
... an array containing the square root of each element in ``x``
... '''
...
>>> case_block = r_case_block.search(sqrt.__doc__).group(1)
>>> unary_cases = parse_unary_case_block(case_block, 'sqrt')
>>> for case in unary_cases:
... print(repr(case))
UnaryCase(<x_i < 0 -> NaN>)
UnaryCase(<x_i == NaN -> NaN>)
UnaryCase(<x_i == +0 -> +0>)
UnaryCase(<x_i == -0 -> -0>)
UnaryCase(<x_i == +infinity -> +infinity>)
>>> lt_0_case = unary_cases[0]
>>> lt_0_case.cond(-123)
True
>>> lt_0_case.check_result(-123, float('nan'))
True
"""
cases = []
# Check if the case block contains complex cases by looking for the marker
in_complex_section = r_complex_marker.search(case_block) is not None
for case_m in r_case.finditer(case_block):
case_str = case_m.group(1)
# Record this special case if a record list is provided
if record_list is not None:
record_list.append(f"{func_name}: {case_str}.")
# Try to parse complex cases if we're in the complex section
if in_complex_section and (m := r_complex_case.search(case_str)):
try:
a_cond_str = m.group(1)
b_cond_str = m.group(2)
result_str = m.group(3)
# Skip cases with complex expressions like "cis(b)"
if "cis" in result_str or "*" in result_str:
warn(f"case for {func_name} not machine-readable: '{case_str}'")
continue
# Parse the complex condition and result
complex_cond, cond_expr, complex_from_dtype = parse_complex_cond(
a_cond_str, b_cond_str
)
_check_result, result_expr = parse_complex_result(result_str)
check_result = make_complex_unary_check_result(_check_result)
case = UnaryCase(
cond_expr=cond_expr,
cond=complex_cond,
cond_from_dtype=complex_from_dtype,
result_expr=result_expr,
check_result=check_result,
raw_case=case_str,
is_complex=True,
)
cases.append(case)
except ParseError as e:
warn(f"case for {func_name} not machine-readable: '{e.value}'")
continue
# Parse regular (real-valued) cases
if r_already_int_case.search(case_str):
cases.append(already_int_case)
elif r_even_round_halves_case.search(case_str):
cases.append(even_round_halves_case)
elif m := r_nan_signbit.search(case_str):
signbit = parse_value(m.group(1))
expected = bool(parse_value(m.group(2)))
cases.append(make_nan_signbit_case(signbit, expected))
elif m := r_unary_case.search(case_str):
try:
cond, cond_expr_template, cond_from_dtype = parse_cond(m.group(1))
_check_result, result_expr = parse_result(m.group(2))
except ParseError as e:
warn(f"case for {func_name} not machine-readable: '{e.value}'")
continue
cond_expr = cond_expr_template.replace("{}", "x_i")
# Do not define check_result in this function's body - see
# parse_binary_case comment.
check_result = make_unary_check_result(_check_result)
case = UnaryCase(
cond_expr=cond_expr,
cond=cond,
cond_from_dtype=cond_from_dtype,
result_expr=result_expr,
check_result=check_result,
raw_case=case_str,
)
cases.append(case)
else:
if not r_remaining_case.search(case_str):
warn(f"case for {func_name} not machine-readable: '{case_str}'")
return cases
class BinaryCond(Protocol):
def __call__(self, i1: float, i2: float) -> bool:
...
class BinaryResultCheck(Protocol):
def __call__(self, i1: float, i2: float, result: float) -> bool:
...
@dataclass(repr=False)
class BinaryCase(Case):
cond_expr: str
result_expr: str
x1_cond_from_dtype: FromDtypeFunc
x2_cond_from_dtype: FromDtypeFunc
cond: BinaryCond
check_result: BinaryResultCheck
raw_case: Optional[str] = field(default=None)
r_binary_case = re.compile("If (.+), the result (.+)")
r_remaining_case = re.compile("In the remaining cases.+")
r_cond_sep = re.compile(r"(?<!``x1_i``),? and |(?<!i\.e\.), ")
r_cond = re.compile("(.+) (?:is|have) (.+)")
r_input_is_array_element = re.compile(
f"{r_array_element.pattern} is {r_array_element.pattern}"
)
r_both_inputs_are_value = re.compile("are both (.+)")
r_element = re.compile("x([12])_i")
r_input = re.compile(rf"``{r_element.pattern}``")
r_abs_input = re.compile(rf"``abs\({r_element.pattern}\)``")
r_and_input = re.compile(f"{r_input.pattern} and {r_input.pattern}")
r_or_input = re.compile(f"either {r_input.pattern} or {r_input.pattern}")
r_result = re.compile(r"(?:is|has a) (.+)")
class BinaryCondArg(Enum):
FIRST = auto()
SECOND = auto()
BOTH = auto()
EITHER = auto()
@classmethod
def from_x_no(cls, string):
if string == "1":
return cls.FIRST
elif string == "2":