-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathtest_dataset.py
7661 lines (6458 loc) · 279 KB
/
test_dataset.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
from __future__ import annotations
import pickle
import re
import sys
import warnings
from collections.abc import Hashable
from copy import copy, deepcopy
from io import StringIO
from textwrap import dedent
from typing import Any, Literal
import numpy as np
import pandas as pd
import pytest
from pandas.core.indexes.datetimes import DatetimeIndex
# remove once numpy 2.0 is the oldest supported version
try:
from numpy.exceptions import RankWarning
except ImportError:
from numpy import RankWarning # type: ignore[no-redef,attr-defined,unused-ignore]
import xarray as xr
from xarray import (
DataArray,
Dataset,
IndexVariable,
MergeError,
Variable,
align,
backends,
broadcast,
open_dataset,
set_options,
)
from xarray.coding.cftimeindex import CFTimeIndex
from xarray.core import dtypes, indexing, utils
from xarray.core.common import duck_array_ops, full_like
from xarray.core.coordinates import Coordinates, DatasetCoordinates
from xarray.core.indexes import Index, PandasIndex
from xarray.core.types import ArrayLike
from xarray.core.utils import is_scalar
from xarray.groupers import TimeResampler
from xarray.namedarray.pycompat import array_type, integer_types
from xarray.testing import _assert_internal_invariants
from xarray.tests import (
DuckArrayWrapper,
InaccessibleArray,
UnexpectedDataAccess,
assert_allclose,
assert_array_equal,
assert_equal,
assert_identical,
assert_no_warnings,
assert_writeable,
create_test_data,
has_cftime,
has_dask,
raise_if_dask_computes,
requires_bottleneck,
requires_cftime,
requires_cupy,
requires_dask,
requires_numexpr,
requires_pint,
requires_scipy,
requires_sparse,
source_ndarray,
)
try:
from pandas.errors import UndefinedVariableError
except ImportError:
# TODO: remove once we stop supporting pandas<1.4.3
from pandas.core.computation.ops import UndefinedVariableError
try:
import dask.array as da
except ImportError:
pass
# from numpy version 2.0 trapz is deprecated and renamed to trapezoid
# remove once numpy 2.0 is the oldest supported version
try:
from numpy import trapezoid # type: ignore[attr-defined,unused-ignore]
except ImportError:
from numpy import ( # type: ignore[arg-type,no-redef,attr-defined,unused-ignore]
trapz as trapezoid,
)
sparse_array_type = array_type("sparse")
pytestmark = [
pytest.mark.filterwarnings("error:Mean of empty slice"),
pytest.mark.filterwarnings("error:All-NaN (slice|axis) encountered"),
]
def create_append_test_data(seed=None) -> tuple[Dataset, Dataset, Dataset]:
rs = np.random.default_rng(seed)
lat = [2, 1, 0]
lon = [0, 1, 2]
nt1 = 3
nt2 = 2
time1 = pd.date_range("2000-01-01", periods=nt1)
time2 = pd.date_range("2000-02-01", periods=nt2)
string_var = np.array(["a", "bc", "def"], dtype=object)
string_var_to_append = np.array(["asdf", "asdfg"], dtype=object)
string_var_fixed_length = np.array(["aa", "bb", "cc"], dtype="|S2")
string_var_fixed_length_to_append = np.array(["dd", "ee"], dtype="|S2")
unicode_var = np.array(["áó", "áó", "áó"])
datetime_var = np.array(
["2019-01-01", "2019-01-02", "2019-01-03"], dtype="datetime64[s]"
)
datetime_var_to_append = np.array(
["2019-01-04", "2019-01-05"], dtype="datetime64[s]"
)
bool_var = np.array([True, False, True], dtype=bool)
bool_var_to_append = np.array([False, True], dtype=bool)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "Converting non-nanosecond")
ds = xr.Dataset(
data_vars={
"da": xr.DataArray(
rs.random((3, 3, nt1)),
coords=[lat, lon, time1],
dims=["lat", "lon", "time"],
),
"string_var": ("time", string_var),
"string_var_fixed_length": ("time", string_var_fixed_length),
"unicode_var": ("time", unicode_var),
"datetime_var": ("time", datetime_var),
"bool_var": ("time", bool_var),
}
)
ds_to_append = xr.Dataset(
data_vars={
"da": xr.DataArray(
rs.random((3, 3, nt2)),
coords=[lat, lon, time2],
dims=["lat", "lon", "time"],
),
"string_var": ("time", string_var_to_append),
"string_var_fixed_length": ("time", string_var_fixed_length_to_append),
"unicode_var": ("time", unicode_var[:nt2]),
"datetime_var": ("time", datetime_var_to_append),
"bool_var": ("time", bool_var_to_append),
}
)
ds_with_new_var = xr.Dataset(
data_vars={
"new_var": xr.DataArray(
rs.random((3, 3, nt1 + nt2)),
coords=[lat, lon, time1.append(time2)],
dims=["lat", "lon", "time"],
)
}
)
assert_writeable(ds)
assert_writeable(ds_to_append)
assert_writeable(ds_with_new_var)
return ds, ds_to_append, ds_with_new_var
def create_append_string_length_mismatch_test_data(dtype) -> tuple[Dataset, Dataset]:
def make_datasets(data, data_to_append) -> tuple[Dataset, Dataset]:
ds = xr.Dataset(
{"temperature": (["time"], data)},
coords={"time": [0, 1, 2]},
)
ds_to_append = xr.Dataset(
{"temperature": (["time"], data_to_append)}, coords={"time": [0, 1, 2]}
)
assert_writeable(ds)
assert_writeable(ds_to_append)
return ds, ds_to_append
u2_strings = ["ab", "cd", "ef"]
u5_strings = ["abc", "def", "ghijk"]
s2_strings = np.array(["aa", "bb", "cc"], dtype="|S2")
s3_strings = np.array(["aaa", "bbb", "ccc"], dtype="|S3")
if dtype == "U":
return make_datasets(u2_strings, u5_strings)
elif dtype == "S":
return make_datasets(s2_strings, s3_strings)
else:
raise ValueError(f"unsupported dtype {dtype}.")
def create_test_multiindex() -> Dataset:
mindex = pd.MultiIndex.from_product(
[["a", "b"], [1, 2]], names=("level_1", "level_2")
)
return Dataset({}, Coordinates.from_pandas_multiindex(mindex, "x"))
def create_test_stacked_array() -> tuple[DataArray, DataArray]:
x = DataArray(pd.Index(np.r_[:10], name="x"))
y = DataArray(pd.Index(np.r_[:20], name="y"))
a = x * y
b = x * y * y
return a, b
class InaccessibleVariableDataStore(backends.InMemoryDataStore):
"""
Store that does not allow any data access.
"""
def __init__(self):
super().__init__()
self._indexvars = set()
def store(self, variables, *args, **kwargs) -> None:
super().store(variables, *args, **kwargs)
for k, v in variables.items():
if isinstance(v, IndexVariable):
self._indexvars.add(k)
def get_variables(self):
def lazy_inaccessible(k, v):
if k in self._indexvars:
return v
data = indexing.LazilyIndexedArray(InaccessibleArray(v.values))
return Variable(v.dims, data, v.attrs)
return {k: lazy_inaccessible(k, v) for k, v in self._variables.items()}
class DuckBackendArrayWrapper(backends.common.BackendArray):
"""Mimic a BackendArray wrapper around DuckArrayWrapper"""
def __init__(self, array):
self.array = DuckArrayWrapper(array)
self.shape = array.shape
self.dtype = array.dtype
def get_array(self):
return self.array
def __getitem__(self, key):
return self.array[key.tuple]
class AccessibleAsDuckArrayDataStore(backends.InMemoryDataStore):
"""
Store that returns a duck array, not convertible to numpy array,
on read. Modeled after nVIDIA's kvikio.
"""
def __init__(self):
super().__init__()
self._indexvars = set()
def store(self, variables, *args, **kwargs) -> None:
super().store(variables, *args, **kwargs)
for k, v in variables.items():
if isinstance(v, IndexVariable):
self._indexvars.add(k)
def get_variables(self) -> dict[Any, xr.Variable]:
def lazy_accessible(k, v) -> xr.Variable:
if k in self._indexvars:
return v
data = indexing.LazilyIndexedArray(DuckBackendArrayWrapper(v.values))
return Variable(v.dims, data, v.attrs)
return {k: lazy_accessible(k, v) for k, v in self._variables.items()}
class TestDataset:
def test_repr(self) -> None:
data = create_test_data(seed=123)
data.attrs["foo"] = "bar"
# need to insert str dtype at runtime to handle different endianness
expected = dedent(
"""\
<xarray.Dataset> Size: 2kB
Dimensions: (dim2: 9, dim3: 10, time: 20, dim1: 8)
Coordinates:
* dim2 (dim2) float64 72B 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0
* dim3 (dim3) {} 40B 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j'
* time (time) datetime64[ns] 160B 2000-01-01 2000-01-02 ... 2000-01-20
numbers (dim3) int64 80B 0 1 2 0 0 1 1 2 2 3
Dimensions without coordinates: dim1
Data variables:
var1 (dim1, dim2) float64 576B -0.9891 -0.3678 1.288 ... -0.2116 0.364
var2 (dim1, dim2) float64 576B 0.953 1.52 1.704 ... 0.1347 -0.6423
var3 (dim3, dim1) float64 640B 0.4107 0.9941 0.1665 ... 0.716 1.555
Attributes:
foo: bar""".format(data["dim3"].dtype)
)
actual = "\n".join(x.rstrip() for x in repr(data).split("\n"))
assert expected == actual
with set_options(display_width=100):
max_len = max(map(len, repr(data).split("\n")))
assert 90 < max_len < 100
expected = dedent(
"""\
<xarray.Dataset> Size: 0B
Dimensions: ()
Data variables:
*empty*"""
)
actual = "\n".join(x.rstrip() for x in repr(Dataset()).split("\n"))
print(actual)
assert expected == actual
# verify that ... doesn't appear for scalar coordinates
data = Dataset({"foo": ("x", np.ones(10))}).mean()
expected = dedent(
"""\
<xarray.Dataset> Size: 8B
Dimensions: ()
Data variables:
foo float64 8B 1.0"""
)
actual = "\n".join(x.rstrip() for x in repr(data).split("\n"))
print(actual)
assert expected == actual
# verify long attributes are truncated
data = Dataset(attrs={"foo": "bar" * 1000})
assert len(repr(data)) < 1000
def test_repr_multiindex(self) -> None:
data = create_test_multiindex()
obj_size = np.dtype("O").itemsize
expected = dedent(
f"""\
<xarray.Dataset> Size: {8 * obj_size + 32}B
Dimensions: (x: 4)
Coordinates:
* x (x) object {4 * obj_size}B MultiIndex
* level_1 (x) object {4 * obj_size}B 'a' 'a' 'b' 'b'
* level_2 (x) int64 32B 1 2 1 2
Data variables:
*empty*"""
)
actual = "\n".join(x.rstrip() for x in repr(data).split("\n"))
print(actual)
assert expected == actual
# verify that long level names are not truncated
midx = pd.MultiIndex.from_product(
[["a", "b"], [1, 2]], names=("a_quite_long_level_name", "level_2")
)
midx_coords = Coordinates.from_pandas_multiindex(midx, "x")
data = Dataset({}, midx_coords)
expected = dedent(
f"""\
<xarray.Dataset> Size: {8 * obj_size + 32}B
Dimensions: (x: 4)
Coordinates:
* x (x) object {4 * obj_size}B MultiIndex
* a_quite_long_level_name (x) object {4 * obj_size}B 'a' 'a' 'b' 'b'
* level_2 (x) int64 32B 1 2 1 2
Data variables:
*empty*"""
)
actual = "\n".join(x.rstrip() for x in repr(data).split("\n"))
print(actual)
assert expected == actual
def test_repr_period_index(self) -> None:
data = create_test_data(seed=456)
data.coords["time"] = pd.period_range("2000-01-01", periods=20, freq="D")
# check that creating the repr doesn't raise an error #GH645
repr(data)
def test_unicode_data(self) -> None:
# regression test for GH834
data = Dataset({"foø": ["ba®"]}, attrs={"å": "∑"})
repr(data) # should not raise
byteorder = "<" if sys.byteorder == "little" else ">"
expected = dedent(
f"""\
<xarray.Dataset> Size: 12B
Dimensions: (foø: 1)
Coordinates:
* foø (foø) {byteorder}U3 12B {'ba®'!r}
Data variables:
*empty*
Attributes:
å: ∑"""
)
actual = str(data)
assert expected == actual
def test_repr_nep18(self) -> None:
class Array:
def __init__(self):
self.shape = (2,)
self.ndim = 1
self.dtype = np.dtype(np.float64)
def __array_function__(self, *args, **kwargs):
return NotImplemented
def __array_ufunc__(self, *args, **kwargs):
return NotImplemented
def __repr__(self):
return "Custom\nArray"
dataset = Dataset({"foo": ("x", Array())})
expected = dedent(
"""\
<xarray.Dataset> Size: 16B
Dimensions: (x: 2)
Dimensions without coordinates: x
Data variables:
foo (x) float64 16B Custom Array"""
)
assert expected == repr(dataset)
def test_info(self) -> None:
ds = create_test_data(seed=123)
ds = ds.drop_vars("dim3") # string type prints differently in PY2 vs PY3
ds.attrs["unicode_attr"] = "ba®"
ds.attrs["string_attr"] = "bar"
buf = StringIO()
ds.info(buf=buf)
expected = dedent(
"""\
xarray.Dataset {
dimensions:
\tdim2 = 9 ;
\ttime = 20 ;
\tdim1 = 8 ;
\tdim3 = 10 ;
variables:
\tfloat64 dim2(dim2) ;
\tdatetime64[ns] time(time) ;
\tfloat64 var1(dim1, dim2) ;
\t\tvar1:foo = variable ;
\tfloat64 var2(dim1, dim2) ;
\t\tvar2:foo = variable ;
\tfloat64 var3(dim3, dim1) ;
\t\tvar3:foo = variable ;
\tint64 numbers(dim3) ;
// global attributes:
\t:unicode_attr = ba® ;
\t:string_attr = bar ;
}"""
)
actual = buf.getvalue()
assert expected == actual
buf.close()
def test_constructor(self) -> None:
x1 = ("x", 2 * np.arange(100))
x2 = ("x", np.arange(1000))
z = (["x", "y"], np.arange(1000).reshape(100, 10))
with pytest.raises(ValueError, match=r"conflicting sizes"):
Dataset({"a": x1, "b": x2})
with pytest.raises(TypeError, match=r"tuple of form"):
Dataset({"x": (1, 2, 3, 4, 5, 6, 7)})
with pytest.raises(ValueError, match=r"already exists as a scalar"):
Dataset({"x": 0, "y": ("x", [1, 2, 3])})
# nD coordinate variable "x" sharing name with dimension
actual = Dataset({"a": x1, "x": z})
assert "x" not in actual.xindexes
_assert_internal_invariants(actual, check_default_indexes=True)
# verify handling of DataArrays
expected = Dataset({"x": x1, "z": z})
actual = Dataset({"z": expected["z"]})
assert_identical(expected, actual)
def test_constructor_1d(self) -> None:
expected = Dataset({"x": (["x"], 5.0 + np.arange(5))})
actual = Dataset({"x": 5.0 + np.arange(5)})
assert_identical(expected, actual)
actual = Dataset({"x": [5, 6, 7, 8, 9]})
assert_identical(expected, actual)
@pytest.mark.filterwarnings("ignore:Converting non-nanosecond")
def test_constructor_0d(self) -> None:
expected = Dataset({"x": ([], 1)})
for arg in [1, np.array(1), expected["x"]]:
actual = Dataset({"x": arg})
assert_identical(expected, actual)
class Arbitrary:
pass
d = pd.Timestamp("2000-01-01T12")
args = [
True,
None,
3.4,
np.nan,
"hello",
b"raw",
np.datetime64("2000-01-01"),
d,
d.to_pydatetime(),
Arbitrary(),
]
for arg in args:
print(arg)
expected = Dataset({"x": ([], arg)})
actual = Dataset({"x": arg})
assert_identical(expected, actual)
def test_constructor_auto_align(self) -> None:
a = DataArray([1, 2], [("x", [0, 1])])
b = DataArray([3, 4], [("x", [1, 2])])
# verify align uses outer join
expected = Dataset(
{"a": ("x", [1, 2, np.nan]), "b": ("x", [np.nan, 3, 4])}, {"x": [0, 1, 2]}
)
actual = Dataset({"a": a, "b": b})
assert_identical(expected, actual)
# regression test for GH346
assert isinstance(actual.variables["x"], IndexVariable)
# variable with different dimensions
c = ("y", [3, 4])
expected2 = expected.merge({"c": c})
actual = Dataset({"a": a, "b": b, "c": c})
assert_identical(expected2, actual)
# variable that is only aligned against the aligned variables
d = ("x", [3, 2, 1])
expected3 = expected.merge({"d": d})
actual = Dataset({"a": a, "b": b, "d": d})
assert_identical(expected3, actual)
e = ("x", [0, 0])
with pytest.raises(ValueError, match=r"conflicting sizes"):
Dataset({"a": a, "b": b, "e": e})
def test_constructor_pandas_sequence(self) -> None:
ds = self.make_example_math_dataset()
pandas_objs = {
var_name: ds[var_name].to_pandas() for var_name in ["foo", "bar"]
}
ds_based_on_pandas = Dataset(pandas_objs, ds.coords, attrs=ds.attrs)
del ds_based_on_pandas["x"]
assert_equal(ds, ds_based_on_pandas)
# reindex pandas obj, check align works
rearranged_index = reversed(pandas_objs["foo"].index)
pandas_objs["foo"] = pandas_objs["foo"].reindex(rearranged_index)
ds_based_on_pandas = Dataset(pandas_objs, ds.coords, attrs=ds.attrs)
del ds_based_on_pandas["x"]
assert_equal(ds, ds_based_on_pandas)
def test_constructor_pandas_single(self) -> None:
das = [
DataArray(np.random.rand(4), dims=["a"]), # series
DataArray(np.random.rand(4, 3), dims=["a", "b"]), # df
]
for a in das:
pandas_obj = a.to_pandas()
ds_based_on_pandas = Dataset(pandas_obj) # type: ignore[arg-type] # TODO: improve typing of __init__
for dim in ds_based_on_pandas.data_vars:
assert isinstance(dim, int)
assert_array_equal(ds_based_on_pandas[dim], pandas_obj[dim])
def test_constructor_compat(self) -> None:
data = {"x": DataArray(0, coords={"y": 1}), "y": ("z", [1, 1, 1])}
expected = Dataset({"x": 0}, {"y": ("z", [1, 1, 1])})
actual = Dataset(data)
assert_identical(expected, actual)
data = {"y": ("z", [1, 1, 1]), "x": DataArray(0, coords={"y": 1})}
actual = Dataset(data)
assert_identical(expected, actual)
original = Dataset(
{"a": (("x", "y"), np.ones((2, 3)))},
{"c": (("x", "y"), np.zeros((2, 3))), "x": [0, 1]},
)
expected = Dataset(
{"a": ("x", np.ones(2)), "b": ("y", np.ones(3))},
{"c": (("x", "y"), np.zeros((2, 3))), "x": [0, 1]},
)
actual = Dataset(
{"a": original["a"][:, 0], "b": original["a"][0].drop_vars("x")}
)
assert_identical(expected, actual)
data = {"x": DataArray(0, coords={"y": 3}), "y": ("z", [1, 1, 1])}
with pytest.raises(MergeError):
Dataset(data)
data = {"x": DataArray(0, coords={"y": 1}), "y": [1, 1]}
actual = Dataset(data)
expected = Dataset({"x": 0}, {"y": [1, 1]})
assert_identical(expected, actual)
def test_constructor_with_coords(self) -> None:
with pytest.raises(ValueError, match=r"found in both data_vars and"):
Dataset({"a": ("x", [1])}, {"a": ("x", [1])})
ds = Dataset({}, {"a": ("x", [1])})
assert not ds.data_vars
assert list(ds.coords.keys()) == ["a"]
mindex = pd.MultiIndex.from_product(
[["a", "b"], [1, 2]], names=("level_1", "level_2")
)
with pytest.raises(ValueError, match=r"conflicting MultiIndex"):
with pytest.warns(
FutureWarning,
match=".*`pandas.MultiIndex`.*no longer be implicitly promoted.*",
):
Dataset({}, {"x": mindex, "y": mindex})
Dataset({}, {"x": mindex, "level_1": range(4)})
def test_constructor_no_default_index(self) -> None:
# explicitly passing a Coordinates object skips the creation of default index
ds = Dataset(coords=Coordinates({"x": [1, 2, 3]}, indexes={}))
assert "x" in ds
assert "x" not in ds.xindexes
def test_constructor_multiindex(self) -> None:
midx = pd.MultiIndex.from_product([["a", "b"], [1, 2]], names=("one", "two"))
coords = Coordinates.from_pandas_multiindex(midx, "x")
ds = Dataset(coords=coords)
assert_identical(ds, coords.to_dataset())
with pytest.warns(
FutureWarning,
match=".*`pandas.MultiIndex`.*no longer be implicitly promoted.*",
):
Dataset(data_vars={"x": midx})
with pytest.warns(
FutureWarning,
match=".*`pandas.MultiIndex`.*no longer be implicitly promoted.*",
):
Dataset(coords={"x": midx})
def test_constructor_custom_index(self) -> None:
class CustomIndex(Index): ...
coords = Coordinates(
coords={"x": ("x", [1, 2, 3])}, indexes={"x": CustomIndex()}
)
ds = Dataset(coords=coords)
assert isinstance(ds.xindexes["x"], CustomIndex)
# test coordinate variables copied
assert ds.variables["x"] is not coords.variables["x"]
@pytest.mark.filterwarnings("ignore:return type")
def test_properties(self) -> None:
ds = create_test_data()
# dims / sizes
# These exact types aren't public API, but this makes sure we don't
# change them inadvertently:
assert isinstance(ds.dims, utils.Frozen)
# TODO change after deprecation cycle in GH #8500 is complete
assert isinstance(ds.dims.mapping, dict)
assert type(ds.dims.mapping) is dict
with pytest.warns(
FutureWarning,
match=" To access a mapping from dimension names to lengths, please use `Dataset.sizes`",
):
assert ds.dims == ds.sizes
assert ds.sizes == {"dim1": 8, "dim2": 9, "dim3": 10, "time": 20}
# dtypes
assert isinstance(ds.dtypes, utils.Frozen)
assert isinstance(ds.dtypes.mapping, dict)
assert ds.dtypes == {
"var1": np.dtype("float64"),
"var2": np.dtype("float64"),
"var3": np.dtype("float64"),
}
# data_vars
assert list(ds) == list(ds.data_vars)
assert list(ds.keys()) == list(ds.data_vars)
assert "aasldfjalskdfj" not in ds.variables
assert "dim1" in repr(ds.variables)
assert len(ds) == 3
assert bool(ds)
assert list(ds.data_vars) == ["var1", "var2", "var3"]
assert list(ds.data_vars.keys()) == ["var1", "var2", "var3"]
assert "var1" in ds.data_vars
assert "dim1" not in ds.data_vars
assert "numbers" not in ds.data_vars
assert len(ds.data_vars) == 3
# xindexes
assert set(ds.xindexes) == {"dim2", "dim3", "time"}
assert len(ds.xindexes) == 3
assert "dim2" in repr(ds.xindexes)
assert all(isinstance(idx, Index) for idx in ds.xindexes.values())
# indexes
assert set(ds.indexes) == {"dim2", "dim3", "time"}
assert len(ds.indexes) == 3
assert "dim2" in repr(ds.indexes)
assert all(isinstance(idx, pd.Index) for idx in ds.indexes.values())
# coords
assert list(ds.coords) == ["dim2", "dim3", "time", "numbers"]
assert "dim2" in ds.coords
assert "numbers" in ds.coords
assert "var1" not in ds.coords
assert "dim1" not in ds.coords
assert len(ds.coords) == 4
# nbytes
assert (
Dataset({"x": np.int64(1), "y": np.array([1, 2], dtype=np.float32)}).nbytes
== 16
)
def test_warn_ds_dims_deprecation(self) -> None:
# TODO remove after deprecation cycle in GH #8500 is complete
ds = create_test_data()
with pytest.warns(FutureWarning, match="return type"):
ds.dims["dim1"]
with pytest.warns(FutureWarning, match="return type"):
ds.dims.keys()
with pytest.warns(FutureWarning, match="return type"):
ds.dims.values()
with pytest.warns(FutureWarning, match="return type"):
ds.dims.items()
with assert_no_warnings():
len(ds.dims)
ds.dims.__iter__()
_ = "dim1" in ds.dims
def test_asarray(self) -> None:
ds = Dataset({"x": 0})
with pytest.raises(TypeError, match=r"cannot directly convert"):
np.asarray(ds)
def test_get_index(self) -> None:
ds = Dataset({"foo": (("x", "y"), np.zeros((2, 3)))}, coords={"x": ["a", "b"]})
assert ds.get_index("x").equals(pd.Index(["a", "b"]))
assert ds.get_index("y").equals(pd.Index([0, 1, 2]))
with pytest.raises(KeyError):
ds.get_index("z")
def test_attr_access(self) -> None:
ds = Dataset(
{"tmin": ("x", [42], {"units": "Celsius"})}, attrs={"title": "My test data"}
)
assert_identical(ds.tmin, ds["tmin"])
assert_identical(ds.tmin.x, ds.x)
assert ds.title == ds.attrs["title"]
assert ds.tmin.units == ds["tmin"].attrs["units"]
assert {"tmin", "title"} <= set(dir(ds))
assert "units" in set(dir(ds.tmin))
# should defer to variable of same name
ds.attrs["tmin"] = -999
assert ds.attrs["tmin"] == -999
assert_identical(ds.tmin, ds["tmin"])
def test_variable(self) -> None:
a = Dataset()
d = np.random.random((10, 3))
a["foo"] = (("time", "x"), d)
assert "foo" in a.variables
assert "foo" in a
a["bar"] = (("time", "x"), d)
# order of creation is preserved
assert list(a.variables) == ["foo", "bar"]
assert_array_equal(a["foo"].values, d)
# try to add variable with dim (10,3) with data that's (3,10)
with pytest.raises(ValueError):
a["qux"] = (("time", "x"), d.T)
def test_modify_inplace(self) -> None:
a = Dataset()
vec = np.random.random((10,))
attributes = {"foo": "bar"}
a["x"] = ("x", vec, attributes)
assert "x" in a.coords
assert isinstance(a.coords["x"].to_index(), pd.Index)
assert_identical(a.coords["x"].variable, a.variables["x"])
b = Dataset()
b["x"] = ("x", vec, attributes)
assert_identical(a["x"], b["x"])
assert a.sizes == b.sizes
# this should work
a["x"] = ("x", vec[:5])
a["z"] = ("x", np.arange(5))
with pytest.raises(ValueError):
# now it shouldn't, since there is a conflicting length
a["x"] = ("x", vec[:4])
arr = np.random.random((10, 1))
scal = np.array(0)
with pytest.raises(ValueError):
a["y"] = ("y", arr)
with pytest.raises(ValueError):
a["y"] = ("y", scal)
assert "y" not in a.dims
def test_coords_properties(self) -> None:
# use int64 for repr consistency on windows
data = Dataset(
{
"x": ("x", np.array([-1, -2], "int64")),
"y": ("y", np.array([0, 1, 2], "int64")),
"foo": (["x", "y"], np.random.randn(2, 3)),
},
{"a": ("x", np.array([4, 5], "int64")), "b": np.int64(-10)},
)
coords = data.coords
assert isinstance(coords, DatasetCoordinates)
# len
assert len(coords) == 4
# iter
assert list(coords) == ["x", "y", "a", "b"]
assert_identical(coords["x"].variable, data["x"].variable)
assert_identical(coords["y"].variable, data["y"].variable)
assert "x" in coords
assert "a" in coords
assert 0 not in coords
assert "foo" not in coords
with pytest.raises(KeyError):
coords["foo"]
with pytest.raises(KeyError):
coords[0]
# repr
expected = dedent(
"""\
Coordinates:
* x (x) int64 16B -1 -2
* y (y) int64 24B 0 1 2
a (x) int64 16B 4 5
b int64 8B -10"""
)
actual = repr(coords)
assert expected == actual
# dims
assert coords.sizes == {"x": 2, "y": 3}
# dtypes
assert coords.dtypes == {
"x": np.dtype("int64"),
"y": np.dtype("int64"),
"a": np.dtype("int64"),
"b": np.dtype("int64"),
}
def test_coords_modify(self) -> None:
data = Dataset(
{
"x": ("x", [-1, -2]),
"y": ("y", [0, 1, 2]),
"foo": (["x", "y"], np.random.randn(2, 3)),
},
{"a": ("x", [4, 5]), "b": -10},
)
actual = data.copy(deep=True)
actual.coords["x"] = ("x", ["a", "b"])
assert_array_equal(actual["x"], ["a", "b"])
actual = data.copy(deep=True)
actual.coords["z"] = ("z", ["a", "b"])
assert_array_equal(actual["z"], ["a", "b"])
actual = data.copy(deep=True)
with pytest.raises(ValueError, match=r"conflicting dimension sizes"):
actual.coords["x"] = ("x", [-1])
assert_identical(actual, data) # should not be modified
actual = data.copy()
del actual.coords["b"]
expected = data.reset_coords("b", drop=True)
assert_identical(expected, actual)
with pytest.raises(KeyError):
del data.coords["not_found"]
with pytest.raises(KeyError):
del data.coords["foo"]
actual = data.copy(deep=True)
actual.coords.update({"c": 11})
expected = data.merge({"c": 11}).set_coords("c")
assert_identical(expected, actual)
# regression test for GH3746
del actual.coords["x"]
assert "x" not in actual.xindexes
def test_update_index(self) -> None:
actual = Dataset(coords={"x": [1, 2, 3]})
actual["x"] = ["a", "b", "c"]
assert actual.xindexes["x"].to_pandas_index().equals(pd.Index(["a", "b", "c"]))
def test_coords_setitem_with_new_dimension(self) -> None:
actual = Dataset()
actual.coords["foo"] = ("x", [1, 2, 3])
expected = Dataset(coords={"foo": ("x", [1, 2, 3])})
assert_identical(expected, actual)
def test_coords_setitem_multiindex(self) -> None:
data = create_test_multiindex()
with pytest.raises(ValueError, match=r"cannot drop or update.*corrupt.*index "):
data.coords["level_1"] = range(4)
def test_coords_set(self) -> None:
one_coord = Dataset({"x": ("x", [0]), "yy": ("x", [1]), "zzz": ("x", [2])})
two_coords = Dataset({"zzz": ("x", [2])}, {"x": ("x", [0]), "yy": ("x", [1])})
all_coords = Dataset(
coords={"x": ("x", [0]), "yy": ("x", [1]), "zzz": ("x", [2])}
)
actual = one_coord.set_coords("x")
assert_identical(one_coord, actual)
actual = one_coord.set_coords(["x"])
assert_identical(one_coord, actual)
actual = one_coord.set_coords("yy")
assert_identical(two_coords, actual)
actual = one_coord.set_coords(["yy", "zzz"])
assert_identical(all_coords, actual)
actual = one_coord.reset_coords()
assert_identical(one_coord, actual)
actual = two_coords.reset_coords()
assert_identical(one_coord, actual)
actual = all_coords.reset_coords()
assert_identical(one_coord, actual)
actual = all_coords.reset_coords(["yy", "zzz"])
assert_identical(one_coord, actual)
actual = all_coords.reset_coords("zzz")
assert_identical(two_coords, actual)
with pytest.raises(ValueError, match=r"cannot remove index"):
one_coord.reset_coords("x")
actual = all_coords.reset_coords("zzz", drop=True)
expected = all_coords.drop_vars("zzz")
assert_identical(expected, actual)
expected = two_coords.drop_vars("zzz")
assert_identical(expected, actual)
def test_coords_to_dataset(self) -> None:
orig = Dataset({"foo": ("y", [-1, 0, 1])}, {"x": 10, "y": [2, 3, 4]})
expected = Dataset(coords={"x": 10, "y": [2, 3, 4]})
actual = orig.coords.to_dataset()
assert_identical(expected, actual)
def test_coords_merge(self) -> None:
orig_coords = Dataset(coords={"a": ("x", [1, 2]), "x": [0, 1]}).coords
other_coords = Dataset(coords={"b": ("x", ["a", "b"]), "x": [0, 1]}).coords
expected = Dataset(
coords={"a": ("x", [1, 2]), "b": ("x", ["a", "b"]), "x": [0, 1]}
)