-
-
Notifications
You must be signed in to change notification settings - Fork 9.5k
/
test_stringdtype.py
1579 lines (1318 loc) · 48.3 KB
/
test_stringdtype.py
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
import concurrent.futures
import itertools
import os
import pickle
import string
import sys
import tempfile
import numpy as np
import pytest
from numpy.dtypes import StringDType
from numpy._core.tests._natype import pd_NA
from numpy.testing import assert_array_equal, IS_WASM
@pytest.fixture
def string_list():
return ["abc", "def", "ghi" * 10, "A¢☃€ 😊" * 100, "Abc" * 1000, "DEF"]
@pytest.fixture
def random_string_list():
chars = list(string.ascii_letters + string.digits)
chars = np.array(chars, dtype="U1")
ret = np.random.choice(chars, size=100 * 10, replace=True)
return ret.view("U100")
@pytest.fixture(params=[True, False])
def coerce(request):
return request.param
@pytest.fixture(
params=["unset", None, pd_NA, np.nan, float("nan"), "__nan__"],
ids=["unset", "None", "pandas.NA", "np.nan", "float('nan')", "string nan"],
)
def na_object(request):
return request.param
@pytest.fixture()
def dtype(na_object, coerce):
# explicit is check for pd_NA because != with pd_NA returns pd_NA
if na_object is pd_NA or na_object != "unset":
return StringDType(na_object=na_object, coerce=coerce)
else:
return StringDType(coerce=coerce)
# second copy for cast tests to do a cartesian product over dtypes
@pytest.fixture(params=[True, False])
def coerce2(request):
return request.param
@pytest.fixture(
params=["unset", None, pd_NA, np.nan, float("nan"), "__nan__"],
ids=["unset", "None", "pandas.NA", "np.nan", "float('nan')", "string nan"],
)
def na_object2(request):
return request.param
@pytest.fixture()
def dtype2(na_object2, coerce2):
# explicit is check for pd_NA because != with pd_NA returns pd_NA
if na_object2 is pd_NA or na_object2 != "unset":
return StringDType(na_object=na_object2, coerce=coerce2)
else:
return StringDType(coerce=coerce2)
def test_dtype_creation():
hashes = set()
dt = StringDType()
assert not hasattr(dt, "na_object") and dt.coerce is True
hashes.add(hash(dt))
dt = StringDType(na_object=None)
assert dt.na_object is None and dt.coerce is True
hashes.add(hash(dt))
dt = StringDType(coerce=False)
assert not hasattr(dt, "na_object") and dt.coerce is False
hashes.add(hash(dt))
dt = StringDType(na_object=None, coerce=False)
assert dt.na_object is None and dt.coerce is False
hashes.add(hash(dt))
assert len(hashes) == 4
dt = np.dtype("T")
assert dt == StringDType()
assert dt.kind == "T"
assert dt.char == "T"
hashes.add(hash(dt))
assert len(hashes) == 4
def test_dtype_equality(dtype):
assert dtype == dtype
for ch in "SU":
assert dtype != np.dtype(ch)
assert dtype != np.dtype(f"{ch}8")
def test_dtype_repr(dtype):
if not hasattr(dtype, "na_object") and dtype.coerce:
assert repr(dtype) == "StringDType()"
elif dtype.coerce:
assert repr(dtype) == f"StringDType(na_object={repr(dtype.na_object)})"
elif not hasattr(dtype, "na_object"):
assert repr(dtype) == "StringDType(coerce=False)"
else:
assert (
repr(dtype)
== f"StringDType(na_object={repr(dtype.na_object)}, coerce=False)"
)
def test_create_with_na(dtype):
if not hasattr(dtype, "na_object"):
pytest.skip("does not have an na object")
na_val = dtype.na_object
string_list = ["hello", na_val, "world"]
arr = np.array(string_list, dtype=dtype)
assert str(arr) == "[" + " ".join([repr(s) for s in string_list]) + "]"
assert arr[1] is dtype.na_object
@pytest.mark.parametrize("i", list(range(5)))
def test_set_replace_na(i):
# Test strings of various lengths can be set to NaN and then replaced.
s_empty = ""
s_short = "0123456789"
s_medium = "abcdefghijklmnopqrstuvwxyz"
s_long = "-=+" * 100
strings = [s_medium, s_empty, s_short, s_medium, s_long]
a = np.array(strings, StringDType(na_object=np.nan))
for s in [a[i], s_medium+s_short, s_short, s_empty, s_long]:
a[i] = np.nan
assert np.isnan(a[i])
a[i] = s
assert a[i] == s
assert_array_equal(a, strings[:i] + [s] + strings[i+1:])
def test_null_roundtripping():
data = ["hello\0world", "ABC\0DEF\0\0"]
arr = np.array(data, dtype="T")
assert data[0] == arr[0]
assert data[1] == arr[1]
def test_string_too_large_error():
arr = np.array(["a", "b", "c"], dtype=StringDType())
with pytest.raises(MemoryError):
arr * (2**63 - 2)
@pytest.mark.parametrize(
"data",
[
["abc", "def", "ghi"],
["🤣", "📵", "😰"],
["🚜", "🙃", "😾"],
["😹", "🚠", "🚌"],
],
)
def test_array_creation_utf8(dtype, data):
arr = np.array(data, dtype=dtype)
assert str(arr) == "[" + " ".join(["'" + str(d) + "'" for d in data]) + "]"
assert arr.dtype == dtype
@pytest.mark.parametrize(
"data",
[
[1, 2, 3],
[b"abc", b"def", b"ghi"],
[object, object, object],
],
)
def test_scalars_string_conversion(data, dtype):
if dtype.coerce:
assert_array_equal(
np.array(data, dtype=dtype),
np.array([str(d) for d in data], dtype=dtype),
)
else:
with pytest.raises(ValueError):
np.array(data, dtype=dtype)
@pytest.mark.parametrize(
("strings"),
[
["this", "is", "an", "array"],
["€", "", "😊"],
["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"],
],
)
def test_self_casts(dtype, dtype2, strings):
if hasattr(dtype, "na_object"):
strings = strings + [dtype.na_object]
elif hasattr(dtype2, "na_object"):
strings = strings + [""]
arr = np.array(strings, dtype=dtype)
newarr = arr.astype(dtype2)
if hasattr(dtype, "na_object") and not hasattr(dtype2, "na_object"):
assert newarr[-1] == str(dtype.na_object)
with pytest.raises(TypeError):
arr.astype(dtype2, casting="safe")
elif hasattr(dtype, "na_object") and hasattr(dtype2, "na_object"):
assert newarr[-1] is dtype2.na_object
arr.astype(dtype2, casting="safe")
elif hasattr(dtype2, "na_object"):
assert newarr[-1] == ""
arr.astype(dtype2, casting="safe")
else:
arr.astype(dtype2, casting="safe")
if hasattr(dtype, "na_object") and hasattr(dtype2, "na_object"):
na1 = dtype.na_object
na2 = dtype2.na_object
if ((na1 is not na2 and
# check for pd_NA first because bool(pd_NA) is an error
((na1 is pd_NA or na2 is pd_NA) or
# the second check is a NaN check, spelled this way
# to avoid errors from math.isnan and np.isnan
(na1 != na2 and not (na1 != na1 and na2 != na2))))):
with pytest.raises(TypeError):
arr[:-1] == newarr[:-1]
return
assert_array_equal(arr[:-1], newarr[:-1])
@pytest.mark.parametrize(
("strings"),
[
["this", "is", "an", "array"],
["€", "", "😊"],
["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"],
],
)
class TestStringLikeCasts:
def test_unicode_casts(self, dtype, strings):
arr = np.array(strings, dtype=np.str_).astype(dtype)
expected = np.array(strings, dtype=dtype)
assert_array_equal(arr, expected)
arr_as_U8 = expected.astype("U8")
assert_array_equal(arr_as_U8, np.array(strings, dtype="U8"))
assert_array_equal(arr_as_U8.astype(dtype), arr)
arr_as_U3 = expected.astype("U3")
assert_array_equal(arr_as_U3, np.array(strings, dtype="U3"))
assert_array_equal(
arr_as_U3.astype(dtype),
np.array([s[:3] for s in strings], dtype=dtype),
)
def test_void_casts(self, dtype, strings):
sarr = np.array(strings, dtype=dtype)
utf8_bytes = [s.encode("utf-8") for s in strings]
void_dtype = f"V{max([len(s) for s in utf8_bytes])}"
varr = np.array(utf8_bytes, dtype=void_dtype)
assert_array_equal(varr, sarr.astype(void_dtype))
assert_array_equal(varr.astype(dtype), sarr)
def test_bytes_casts(self, dtype, strings):
sarr = np.array(strings, dtype=dtype)
try:
utf8_bytes = [s.encode("ascii") for s in strings]
bytes_dtype = f"S{max([len(s) for s in utf8_bytes])}"
barr = np.array(utf8_bytes, dtype=bytes_dtype)
assert_array_equal(barr, sarr.astype(bytes_dtype))
assert_array_equal(barr.astype(dtype), sarr)
except UnicodeEncodeError:
with pytest.raises(UnicodeEncodeError):
sarr.astype("S20")
def test_additional_unicode_cast(random_string_list, dtype):
arr = np.array(random_string_list, dtype=dtype)
# test that this short-circuits correctly
assert_array_equal(arr, arr.astype(arr.dtype))
# tests the casts via the comparison promoter
assert_array_equal(arr, arr.astype(random_string_list.dtype))
def test_insert_scalar(dtype, string_list):
"""Test that inserting a scalar works."""
arr = np.array(string_list, dtype=dtype)
scalar_instance = "what"
arr[1] = scalar_instance
assert_array_equal(
arr,
np.array(string_list[:1] + ["what"] + string_list[2:], dtype=dtype),
)
comparison_operators = [
np.equal,
np.not_equal,
np.greater,
np.greater_equal,
np.less,
np.less_equal,
]
@pytest.mark.parametrize("op", comparison_operators)
@pytest.mark.parametrize("o_dtype", [np.str_, object, StringDType()])
def test_comparisons(string_list, dtype, op, o_dtype):
sarr = np.array(string_list, dtype=dtype)
oarr = np.array(string_list, dtype=o_dtype)
# test that comparison operators work
res = op(sarr, sarr)
ores = op(oarr, oarr)
# test that promotion works as well
orres = op(sarr, oarr)
olres = op(oarr, sarr)
assert_array_equal(res, ores)
assert_array_equal(res, orres)
assert_array_equal(res, olres)
# test we get the correct answer for unequal length strings
sarr2 = np.array([s + "2" for s in string_list], dtype=dtype)
oarr2 = np.array([s + "2" for s in string_list], dtype=o_dtype)
res = op(sarr, sarr2)
ores = op(oarr, oarr2)
olres = op(oarr, sarr2)
orres = op(sarr, oarr2)
assert_array_equal(res, ores)
assert_array_equal(res, olres)
assert_array_equal(res, orres)
res = op(sarr2, sarr)
ores = op(oarr2, oarr)
olres = op(oarr2, sarr)
orres = op(sarr2, oarr)
assert_array_equal(res, ores)
assert_array_equal(res, olres)
assert_array_equal(res, orres)
def test_isnan(dtype, string_list):
if not hasattr(dtype, "na_object"):
pytest.skip("no na support")
sarr = np.array(string_list + [dtype.na_object], dtype=dtype)
is_nan = isinstance(dtype.na_object, float) and np.isnan(dtype.na_object)
bool_errors = 0
try:
bool(dtype.na_object)
except TypeError:
bool_errors = 1
if is_nan or bool_errors:
# isnan is only true when na_object is a NaN
assert_array_equal(
np.isnan(sarr),
np.array([0] * len(string_list) + [1], dtype=np.bool),
)
else:
assert not np.any(np.isnan(sarr))
def test_pickle(dtype, string_list):
arr = np.array(string_list, dtype=dtype)
with tempfile.NamedTemporaryFile("wb", delete=False) as f:
pickle.dump([arr, dtype], f)
with open(f.name, "rb") as f:
res = pickle.load(f)
assert_array_equal(res[0], arr)
assert res[1] == dtype
os.remove(f.name)
@pytest.mark.parametrize(
"strings",
[
["left", "right", "leftovers", "righty", "up", "down"],
[
"left" * 10,
"right" * 10,
"leftovers" * 10,
"righty" * 10,
"up" * 10,
],
["🤣🤣", "🤣", "📵", "😰"],
["🚜", "🙃", "😾"],
["😹", "🚠", "🚌"],
["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"],
],
)
def test_sort(dtype, strings):
"""Test that sorting matches python's internal sorting."""
def test_sort(strings, arr_sorted):
arr = np.array(strings, dtype=dtype)
np.random.default_rng().shuffle(arr)
na_object = getattr(arr.dtype, "na_object", "")
if na_object is None and None in strings:
with pytest.raises(
ValueError,
match="Cannot compare null that is not a nan-like value",
):
arr.sort()
else:
arr.sort()
assert np.array_equal(arr, arr_sorted, equal_nan=True)
# make a copy so we don't mutate the lists in the fixture
strings = strings.copy()
arr_sorted = np.array(sorted(strings), dtype=dtype)
test_sort(strings, arr_sorted)
if not hasattr(dtype, "na_object"):
return
# make sure NAs get sorted to the end of the array and string NAs get
# sorted like normal strings
strings.insert(0, dtype.na_object)
strings.insert(2, dtype.na_object)
# can't use append because doing that with NA converts
# the result to object dtype
if not isinstance(dtype.na_object, str):
arr_sorted = np.array(
arr_sorted.tolist() + [dtype.na_object, dtype.na_object],
dtype=dtype,
)
else:
arr_sorted = np.array(sorted(strings), dtype=dtype)
test_sort(strings, arr_sorted)
@pytest.mark.parametrize(
"strings",
[
["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"],
["A¢☃€ 😊", "", " ", " "],
["", "a", "😸", "ááðfáíóåéë"],
],
)
def test_nonzero(strings):
arr = np.array(strings, dtype="T")
is_nonzero = np.array([i for i, item in enumerate(arr) if len(item) != 0])
assert_array_equal(arr.nonzero()[0], is_nonzero)
def test_creation_functions():
assert_array_equal(np.zeros(3, dtype="T"), ["", "", ""])
assert_array_equal(np.empty(3, dtype="T"), ["", "", ""])
assert np.zeros(3, dtype="T")[0] == ""
assert np.empty(3, dtype="T")[0] == ""
def test_create_with_copy_none(string_list):
arr = np.array(string_list, dtype=StringDType())
# create another stringdtype array with an arena that has a different
# in-memory layout than the first array
arr_rev = np.array(string_list[::-1], dtype=StringDType())
# this should create a copy and the resulting array
# shouldn't share an allocator or arena with arr_rev, despite
# explicitly passing arr_rev.dtype
arr_copy = np.array(arr, copy=None, dtype=arr_rev.dtype)
np.testing.assert_array_equal(arr, arr_copy)
assert arr_copy.base is None
with pytest.raises(ValueError, match="Unable to avoid copy"):
np.array(arr, copy=False, dtype=arr_rev.dtype)
# because we're using arr's dtype instance, the view is safe
arr_view = np.array(arr, copy=None, dtype=arr.dtype)
np.testing.assert_array_equal(arr, arr)
np.testing.assert_array_equal(arr_view[::-1], arr_rev)
assert arr_view is arr
def test_astype_copy_false():
orig_dt = StringDType()
arr = np.array(["hello", "world"], dtype=StringDType())
assert not arr.astype(StringDType(coerce=False), copy=False).dtype.coerce
assert arr.astype(orig_dt, copy=False).dtype is orig_dt
@pytest.mark.parametrize(
"strings",
[
["left", "right", "leftovers", "righty", "up", "down"],
["🤣🤣", "🤣", "📵", "😰"],
["🚜", "🙃", "😾"],
["😹", "🚠", "🚌"],
["A¢☃€ 😊", " A☃€¢😊", "☃€😊 A¢", "😊☃A¢ €"],
],
)
def test_argmax(strings):
"""Test that argmax/argmin matches what python calculates."""
arr = np.array(strings, dtype="T")
assert np.argmax(arr) == strings.index(max(strings))
assert np.argmin(arr) == strings.index(min(strings))
@pytest.mark.parametrize(
"arrfunc,expected",
[
[np.sort, None],
[np.nonzero, (np.array([], dtype=np.int_),)],
[np.argmax, 0],
[np.argmin, 0],
],
)
def test_arrfuncs_zeros(arrfunc, expected):
arr = np.zeros(10, dtype="T")
result = arrfunc(arr)
if expected is None:
expected = arr
assert_array_equal(result, expected, strict=True)
@pytest.mark.parametrize(
("strings", "cast_answer", "any_answer", "all_answer"),
[
[["hello", "world"], [True, True], True, True],
[["", ""], [False, False], False, False],
[["hello", ""], [True, False], True, False],
[["", "world"], [False, True], True, False],
],
)
def test_cast_to_bool(strings, cast_answer, any_answer, all_answer):
sarr = np.array(strings, dtype="T")
assert_array_equal(sarr.astype("bool"), cast_answer)
assert np.any(sarr) == any_answer
assert np.all(sarr) == all_answer
@pytest.mark.parametrize(
("strings", "cast_answer"),
[
[[True, True], ["True", "True"]],
[[False, False], ["False", "False"]],
[[True, False], ["True", "False"]],
[[False, True], ["False", "True"]],
],
)
def test_cast_from_bool(strings, cast_answer):
barr = np.array(strings, dtype=bool)
assert_array_equal(barr.astype("T"), np.array(cast_answer, dtype="T"))
@pytest.mark.parametrize("bitsize", [8, 16, 32, 64])
@pytest.mark.parametrize("signed", [True, False])
def test_sized_integer_casts(bitsize, signed):
idtype = f"int{bitsize}"
if signed:
inp = [-(2**p - 1) for p in reversed(range(bitsize - 1))]
inp += [2**p - 1 for p in range(1, bitsize - 1)]
else:
idtype = "u" + idtype
inp = [2**p - 1 for p in range(bitsize)]
ainp = np.array(inp, dtype=idtype)
assert_array_equal(ainp, ainp.astype("T").astype(idtype))
# safe casting works
ainp.astype("T", casting="safe")
with pytest.raises(TypeError):
ainp.astype("T").astype(idtype, casting="safe")
oob = [str(2**bitsize), str(-(2**bitsize))]
with pytest.raises(OverflowError):
np.array(oob, dtype="T").astype(idtype)
with pytest.raises(ValueError):
np.array(["1", np.nan, "3"],
dtype=StringDType(na_object=np.nan)).astype(idtype)
@pytest.mark.parametrize("typename", ["byte", "short", "int", "longlong"])
@pytest.mark.parametrize("signed", ["", "u"])
def test_unsized_integer_casts(typename, signed):
idtype = f"{signed}{typename}"
inp = [1, 2, 3, 4]
ainp = np.array(inp, dtype=idtype)
assert_array_equal(ainp, ainp.astype("T").astype(idtype))
@pytest.mark.parametrize(
"typename",
[
pytest.param(
"longdouble",
marks=pytest.mark.xfail(
np.dtypes.LongDoubleDType() != np.dtypes.Float64DType(),
reason="numpy lacks an ld2a implementation",
strict=True,
),
),
"float64",
"float32",
"float16",
],
)
def test_float_casts(typename):
inp = [1.1, 2.8, -3.2, 2.7e4]
ainp = np.array(inp, dtype=typename)
assert_array_equal(ainp, ainp.astype("T").astype(typename))
inp = [0.1]
sres = np.array(inp, dtype=typename).astype("T")
res = sres.astype(typename)
assert_array_equal(np.array(inp, dtype=typename), res)
assert sres[0] == "0.1"
if typename == "longdouble":
# let's not worry about platform-dependent rounding of longdouble
return
fi = np.finfo(typename)
inp = [1e-324, fi.smallest_subnormal, -1e-324, -fi.smallest_subnormal]
eres = [0, fi.smallest_subnormal, -0, -fi.smallest_subnormal]
res = np.array(inp, dtype=typename).astype("T").astype(typename)
assert_array_equal(eres, res)
inp = [2e308, fi.max, -2e308, fi.min]
eres = [np.inf, fi.max, -np.inf, fi.min]
res = np.array(inp, dtype=typename).astype("T").astype(typename)
assert_array_equal(eres, res)
@pytest.mark.parametrize(
"typename",
[
"csingle",
"cdouble",
pytest.param(
"clongdouble",
marks=pytest.mark.xfail(
np.dtypes.CLongDoubleDType() != np.dtypes.Complex128DType(),
reason="numpy lacks an ld2a implementation",
strict=True,
),
),
],
)
def test_cfloat_casts(typename):
inp = [1.1 + 1.1j, 2.8 + 2.8j, -3.2 - 3.2j, 2.7e4 + 2.7e4j]
ainp = np.array(inp, dtype=typename)
assert_array_equal(ainp, ainp.astype("T").astype(typename))
inp = [0.1 + 0.1j]
sres = np.array(inp, dtype=typename).astype("T")
res = sres.astype(typename)
assert_array_equal(np.array(inp, dtype=typename), res)
assert sres[0] == "(0.1+0.1j)"
def test_take(string_list):
sarr = np.array(string_list, dtype="T")
res = sarr.take(np.arange(len(string_list)))
assert_array_equal(sarr, res)
# make sure it also works for out
out = np.empty(len(string_list), dtype="T")
out[0] = "hello"
res = sarr.take(np.arange(len(string_list)), out=out)
assert res is out
assert_array_equal(sarr, res)
@pytest.mark.parametrize("use_out", [True, False])
@pytest.mark.parametrize(
"ufunc_name,func",
[
("min", min),
("max", max),
],
)
def test_ufuncs_minmax(string_list, ufunc_name, func, use_out):
"""Test that the min/max ufuncs match Python builtin min/max behavior."""
arr = np.array(string_list, dtype="T")
uarr = np.array(string_list, dtype=str)
res = np.array(func(string_list), dtype="T")
assert_array_equal(getattr(arr, ufunc_name)(), res)
ufunc = getattr(np, ufunc_name + "imum")
if use_out:
res = ufunc(arr, arr, out=arr)
else:
res = ufunc(arr, arr)
assert_array_equal(uarr, res)
assert_array_equal(getattr(arr, ufunc_name)(), func(string_list))
def test_max_regression():
arr = np.array(['y', 'y', 'z'], dtype="T")
assert arr.max() == 'z'
@pytest.mark.parametrize("use_out", [True, False])
@pytest.mark.parametrize(
"other_strings",
[
["abc", "def" * 500, "ghi" * 16, "🤣" * 100, "📵", "😰"],
["🚜", "🙃", "😾", "😹", "🚠", "🚌"],
["🥦", "¨", "⨯", "∰ ", "⨌ ", "⎶ "],
],
)
def test_ufunc_add(dtype, string_list, other_strings, use_out):
arr1 = np.array(string_list, dtype=dtype)
arr2 = np.array(other_strings, dtype=dtype)
result = np.array([a + b for a, b in zip(arr1, arr2)], dtype=dtype)
if use_out:
res = np.add(arr1, arr2, out=arr1)
else:
res = np.add(arr1, arr2)
assert_array_equal(res, result)
if not hasattr(dtype, "na_object"):
return
is_nan = isinstance(dtype.na_object, float) and np.isnan(dtype.na_object)
is_str = isinstance(dtype.na_object, str)
bool_errors = 0
try:
bool(dtype.na_object)
except TypeError:
bool_errors = 1
arr1 = np.array([dtype.na_object] + string_list, dtype=dtype)
arr2 = np.array(other_strings + [dtype.na_object], dtype=dtype)
if is_nan or bool_errors or is_str:
res = np.add(arr1, arr2)
assert_array_equal(res[1:-1], arr1[1:-1] + arr2[1:-1])
if not is_str:
assert res[0] is dtype.na_object and res[-1] is dtype.na_object
else:
assert res[0] == dtype.na_object + arr2[0]
assert res[-1] == arr1[-1] + dtype.na_object
else:
with pytest.raises(ValueError):
np.add(arr1, arr2)
def test_ufunc_add_reduce(dtype):
values = ["a", "this is a long string", "c"]
arr = np.array(values, dtype=dtype)
out = np.empty((), dtype=dtype)
expected = np.array("".join(values), dtype=dtype)
assert_array_equal(np.add.reduce(arr), expected)
np.add.reduce(arr, out=out)
assert_array_equal(out, expected)
def test_add_promoter(string_list):
arr = np.array(string_list, dtype=StringDType())
lresult = np.array(["hello" + s for s in string_list], dtype=StringDType())
rresult = np.array([s + "hello" for s in string_list], dtype=StringDType())
for op in ["hello", np.str_("hello"), np.array(["hello"])]:
assert_array_equal(op + arr, lresult)
assert_array_equal(arr + op, rresult)
def test_add_promoter_reduce():
# Exact TypeError could change, but ensure StringDtype doesn't match
with pytest.raises(TypeError, match="the resolved dtypes are not"):
np.add.reduce(np.array(["a", "b"], dtype="U"))
# On the other hand, using `dtype=T` in the *ufunc* should work.
np.add.reduce(np.array(["a", "b"], dtype="U"), dtype=np.dtypes.StringDType)
def test_multiply_reduce():
# At the time of writing (NumPy 2.0) this is very limited (and rather
# ridiculous anyway). But it works and actually makes some sense...
# (NumPy does not allow non-scalar initial values)
repeats = np.array([2, 3, 4])
val = "school-🚌"
res = np.multiply.reduce(repeats, initial=val, dtype=np.dtypes.StringDType)
assert res == val * np.prod(repeats)
def test_multiply_two_string_raises():
arr = np.array(["hello", "world"], dtype="T")
with pytest.raises(np._core._exceptions._UFuncNoLoopError):
np.multiply(arr, arr)
@pytest.mark.parametrize("use_out", [True, False])
@pytest.mark.parametrize("other", [2, [2, 1, 3, 4, 1, 3]])
@pytest.mark.parametrize(
"other_dtype",
[
None,
"int8",
"int16",
"int32",
"int64",
"uint8",
"uint16",
"uint32",
"uint64",
"short",
"int",
"intp",
"long",
"longlong",
"ushort",
"uint",
"uintp",
"ulong",
"ulonglong",
],
)
def test_ufunc_multiply(dtype, string_list, other, other_dtype, use_out):
"""Test the two-argument ufuncs match python builtin behavior."""
arr = np.array(string_list, dtype=dtype)
if other_dtype is not None:
other_dtype = np.dtype(other_dtype)
try:
len(other)
result = [s * o for s, o in zip(string_list, other)]
other = np.array(other)
if other_dtype is not None:
other = other.astype(other_dtype)
except TypeError:
if other_dtype is not None:
other = other_dtype.type(other)
result = [s * other for s in string_list]
if use_out:
arr_cache = arr.copy()
lres = np.multiply(arr, other, out=arr)
assert_array_equal(lres, result)
arr[:] = arr_cache
assert lres is arr
arr *= other
assert_array_equal(arr, result)
arr[:] = arr_cache
rres = np.multiply(other, arr, out=arr)
assert rres is arr
assert_array_equal(rres, result)
else:
lres = arr * other
assert_array_equal(lres, result)
rres = other * arr
assert_array_equal(rres, result)
if not hasattr(dtype, "na_object"):
return
is_nan = np.isnan(np.array([dtype.na_object], dtype=dtype))[0]
is_str = isinstance(dtype.na_object, str)
bool_errors = 0
try:
bool(dtype.na_object)
except TypeError:
bool_errors = 1
arr = np.array(string_list + [dtype.na_object], dtype=dtype)
try:
len(other)
other = np.append(other, 3)
if other_dtype is not None:
other = other.astype(other_dtype)
except TypeError:
pass
if is_nan or bool_errors or is_str:
for res in [arr * other, other * arr]:
assert_array_equal(res[:-1], result)
if not is_str:
assert res[-1] is dtype.na_object
else:
try:
assert res[-1] == dtype.na_object * other[-1]
except (IndexError, TypeError):
assert res[-1] == dtype.na_object * other
else:
with pytest.raises(TypeError):
arr * other
with pytest.raises(TypeError):
other * arr
DATETIME_INPUT = [
np.datetime64("1923-04-14T12:43:12"),
np.datetime64("1994-06-21T14:43:15"),
np.datetime64("2001-10-15T04:10:32"),
np.datetime64("NaT"),
np.datetime64("1995-11-25T16:02:16"),
np.datetime64("2005-01-04T03:14:12"),
np.datetime64("2041-12-03T14:05:03"),
]
TIMEDELTA_INPUT = [
np.timedelta64(12358, "s"),
np.timedelta64(23, "s"),
np.timedelta64(74, "s"),
np.timedelta64("NaT"),
np.timedelta64(23, "s"),
np.timedelta64(73, "s"),
np.timedelta64(7, "s"),
]
@pytest.mark.parametrize(
"input_data, input_dtype",
[
(DATETIME_INPUT, "M8[s]"),
(TIMEDELTA_INPUT, "m8[s]")
]
)
def test_datetime_timedelta_cast(dtype, input_data, input_dtype):
a = np.array(input_data, dtype=input_dtype)
has_na = hasattr(dtype, "na_object")
is_str = isinstance(getattr(dtype, "na_object", None), str)
if not has_na or is_str:
a = np.delete(a, 3)
sa = a.astype(dtype)
ra = sa.astype(a.dtype)
if has_na and not is_str:
assert sa[3] is dtype.na_object
assert np.isnat(ra[3])
assert_array_equal(a, ra)
if has_na and not is_str:
# don't worry about comparing how NaT is converted
sa = np.delete(sa, 3)
a = np.delete(a, 3)
if input_dtype.startswith("M"):
assert_array_equal(sa, a.astype("U"))
else:
# The timedelta to unicode cast produces strings
# that aren't round-trippable and we don't want to
# reproduce that behavior in stringdtype
assert_array_equal(sa, a.astype("int64").astype("U"))
def test_nat_casts():
s = 'nat'
all_nats = itertools.product(*zip(s.upper(), s.lower()))
all_nats = list(map(''.join, all_nats))
NaT_dt = np.datetime64('NaT')
NaT_td = np.timedelta64('NaT')
for na_object in [np._NoValue, None, np.nan, 'nat', '']:
# numpy treats empty string and all case combinations of 'nat' as NaT
dtype = StringDType(na_object=na_object)
arr = np.array([''] + all_nats, dtype=dtype)
dt_array = arr.astype('M8[s]')
td_array = arr.astype('m8[s]')
assert_array_equal(dt_array, NaT_dt)
assert_array_equal(td_array, NaT_td)
if na_object is np._NoValue:
output_object = 'NaT'
else:
output_object = na_object
for arr in [dt_array, td_array]:
assert_array_equal(
arr.astype(dtype),
np.array([output_object]*arr.size, dtype=dtype))