-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
test_dataarray.py
2547 lines (2091 loc) · 104 KB
/
test_dataarray.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 absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import pandas as pd
import pickle
import pytest
from copy import deepcopy
from textwrap import dedent
from distutils.version import LooseVersion
import xarray as xr
from xarray import (align, broadcast, Dataset, DataArray,
IndexVariable, Variable)
from xarray.core.pycompat import iteritems, OrderedDict
from xarray.core.common import full_like
from xarray.tests import (
TestCase, ReturnItem, source_ndarray, unittest, requires_dask,
assert_identical, assert_equal,
assert_allclose, assert_array_equal)
class TestDataArray(TestCase):
def setUp(self):
self.attrs = {'attr1': 'value1', 'attr2': 2929}
self.x = np.random.random((10, 20))
self.v = Variable(['x', 'y'], self.x)
self.va = Variable(['x', 'y'], self.x, self.attrs)
self.ds = Dataset({'foo': self.v})
self.dv = self.ds['foo']
self.mindex = pd.MultiIndex.from_product([['a', 'b'], [1, 2]],
names=('level_1', 'level_2'))
self.mda = DataArray([0, 1, 2, 3], coords={'x': self.mindex}, dims='x')
def test_repr(self):
v = Variable(['time', 'x'], [[1, 2, 3], [4, 5, 6]], {'foo': 'bar'})
coords = OrderedDict([('x', np.arange(3, dtype=np.int64)),
('other', np.int64(0))])
data_array = DataArray(v, coords, name='my_variable')
expected = dedent("""\
<xarray.DataArray 'my_variable' (time: 2, x: 3)>
array([[1, 2, 3],
[4, 5, 6]])
Coordinates:
* x (x) int64 0 1 2
other int64 0
Dimensions without coordinates: time
Attributes:
foo: bar""")
self.assertEqual(expected, repr(data_array))
def test_repr_multiindex(self):
expected = dedent("""\
<xarray.DataArray (x: 4)>
array([0, 1, 2, 3])
Coordinates:
* x (x) MultiIndex
- level_1 (x) object 'a' 'a' 'b' 'b'
- level_2 (x) int64 1 2 1 2""")
self.assertEqual(expected, repr(self.mda))
def test_properties(self):
self.assertVariableEqual(self.dv.variable, self.v)
self.assertArrayEqual(self.dv.values, self.v.values)
for attr in ['dims', 'dtype', 'shape', 'size', 'nbytes', 'ndim', 'attrs']:
self.assertEqual(getattr(self.dv, attr), getattr(self.v, attr))
self.assertEqual(len(self.dv), len(self.v))
self.assertVariableEqual(self.dv.variable, self.v)
self.assertItemsEqual(list(self.dv.coords), list(self.ds.coords))
for k, v in iteritems(self.dv.coords):
self.assertArrayEqual(v, self.ds.coords[k])
with self.assertRaises(AttributeError):
self.dv.dataset
self.assertIsInstance(self.ds['x'].to_index(), pd.Index)
with self.assertRaisesRegexp(ValueError, 'must be 1-dimensional'):
self.ds['foo'].to_index()
with self.assertRaises(AttributeError):
self.dv.variable = self.v
def test_data_property(self):
array = DataArray(np.zeros((3, 4)))
actual = array.copy()
actual.values = np.ones((3, 4))
self.assertArrayEqual(np.ones((3, 4)), actual.values)
actual.data = 2 * np.ones((3, 4))
self.assertArrayEqual(2 * np.ones((3, 4)), actual.data)
self.assertArrayEqual(actual.data, actual.values)
def test_indexes(self):
array = DataArray(np.zeros((2, 3)),
[('x', [0, 1]), ('y', ['a', 'b', 'c'])])
expected = OrderedDict([('x', pd.Index([0, 1])),
('y', pd.Index(['a', 'b', 'c']))])
assert array.indexes.keys() == expected.keys()
for k in expected:
assert array.indexes[k].equals(expected[k])
def test_get_index(self):
array = DataArray(np.zeros((2, 3)), coords={'x': ['a', 'b']},
dims=['x', 'y'])
assert array.get_index('x').equals(pd.Index(['a', 'b']))
assert array.get_index('y').equals(pd.Index([0, 1, 2]))
with self.assertRaises(KeyError):
array.get_index('z')
def test_struct_array_dims(self):
"""
This test checks subraction of two DataArrays for the case
when dimension is a structured array.
"""
# GH837, GH861
# checking array subraction when dims are the same
p_data = np.array([('John', 180), ('Stacy', 150), ('Dick', 200)],
dtype=[('name', '|S256'), ('height', object)])
p_data_1 = np.array([('John', 180), ('Stacy', 150), ('Dick', 200)],
dtype=[('name', '|S256'), ('height', object)])
p_data_2 = np.array([('John', 180), ('Dick', 200)],
dtype=[('name', '|S256'), ('height', object)])
weights_0 = DataArray([80, 56, 120], dims=['participant'],
coords={'participant': p_data})
weights_1 = DataArray([81, 52, 115], dims=['participant'],
coords={'participant': p_data_1})
actual = weights_1 - weights_0
expected = DataArray([1, -4, -5], dims=['participant'],
coords={'participant': p_data})
self.assertDataArrayIdentical(actual, expected)
# checking array subraction when dims are not the same
p_data_1 = np.array([('John', 180), ('Stacy', 151), ('Dick', 200)],
dtype=[('name', '|S256'), ('height', object)])
weights_1 = DataArray([81, 52, 115], dims=['participant'],
coords={'participant': p_data_1})
actual = weights_1 - weights_0
expected = DataArray([1, -5], dims=['participant'],
coords={'participant': p_data_2})
self.assertDataArrayIdentical(actual, expected)
# checking array subraction when dims are not the same and one
# is np.nan
p_data_1 = np.array([('John', 180), ('Stacy', np.nan), ('Dick', 200)],
dtype=[('name', '|S256'), ('height', object)])
weights_1 = DataArray([81, 52, 115], dims=['participant'],
coords={'participant': p_data_1})
actual = weights_1 - weights_0
expected = DataArray([1, -5], dims=['participant'],
coords={'participant': p_data_2})
self.assertDataArrayIdentical(actual, expected)
def test_name(self):
arr = self.dv
self.assertEqual(arr.name, 'foo')
copied = arr.copy()
arr.name = 'bar'
self.assertEqual(arr.name, 'bar')
self.assertDataArrayEqual(copied, arr)
actual = DataArray(IndexVariable('x', [3]))
actual.name = 'y'
expected = DataArray([3], [('x', [3])], name='y')
self.assertDataArrayIdentical(actual, expected)
def test_dims(self):
arr = self.dv
self.assertEqual(arr.dims, ('x', 'y'))
with self.assertRaisesRegexp(AttributeError, 'you cannot assign'):
arr.dims = ('w', 'z')
def test_sizes(self):
array = DataArray(np.zeros((3, 4)), dims=['x', 'y'])
self.assertEqual(array.sizes, {'x': 3, 'y': 4})
self.assertEqual(tuple(array.sizes), array.dims)
with self.assertRaises(TypeError):
array.sizes['foo'] = 5
def test_encoding(self):
expected = {'foo': 'bar'}
self.dv.encoding['foo'] = 'bar'
self.assertEquals(expected, self.dv.encoding)
expected = {'baz': 0}
self.dv.encoding = expected
self.assertEquals(expected, self.dv.encoding)
self.assertIsNot(expected, self.dv.encoding)
def test_constructor(self):
data = np.random.random((2, 3))
actual = DataArray(data)
expected = Dataset({None: (['dim_0', 'dim_1'], data)})[None]
self.assertDataArrayIdentical(expected, actual)
actual = DataArray(data, [['a', 'b'], [-1, -2, -3]])
expected = Dataset({None: (['dim_0', 'dim_1'], data),
'dim_0': ('dim_0', ['a', 'b']),
'dim_1': ('dim_1', [-1, -2, -3])})[None]
self.assertDataArrayIdentical(expected, actual)
actual = DataArray(data, [pd.Index(['a', 'b'], name='x'),
pd.Index([-1, -2, -3], name='y')])
expected = Dataset({None: (['x', 'y'], data),
'x': ('x', ['a', 'b']),
'y': ('y', [-1, -2, -3])})[None]
self.assertDataArrayIdentical(expected, actual)
coords = [['a', 'b'], [-1, -2, -3]]
actual = DataArray(data, coords, ['x', 'y'])
self.assertDataArrayIdentical(expected, actual)
coords = [pd.Index(['a', 'b'], name='A'),
pd.Index([-1, -2, -3], name='B')]
actual = DataArray(data, coords, ['x', 'y'])
self.assertDataArrayIdentical(expected, actual)
coords = {'x': ['a', 'b'], 'y': [-1, -2, -3]}
actual = DataArray(data, coords, ['x', 'y'])
self.assertDataArrayIdentical(expected, actual)
coords = [('x', ['a', 'b']), ('y', [-1, -2, -3])]
actual = DataArray(data, coords)
self.assertDataArrayIdentical(expected, actual)
expected = Dataset({None: (['x', 'y'], data),
'x': ('x', ['a', 'b'])})[None]
actual = DataArray(data, {'x': ['a', 'b']}, ['x', 'y'])
self.assertDataArrayIdentical(expected, actual)
actual = DataArray(data, dims=['x', 'y'])
expected = Dataset({None: (['x', 'y'], data)})[None]
self.assertDataArrayIdentical(expected, actual)
actual = DataArray(data, dims=['x', 'y'], name='foo')
expected = Dataset({'foo': (['x', 'y'], data)})['foo']
self.assertDataArrayIdentical(expected, actual)
actual = DataArray(data, name='foo')
expected = Dataset({'foo': (['dim_0', 'dim_1'], data)})['foo']
self.assertDataArrayIdentical(expected, actual)
actual = DataArray(data, dims=['x', 'y'], attrs={'bar': 2})
expected = Dataset({None: (['x', 'y'], data, {'bar': 2})})[None]
self.assertDataArrayIdentical(expected, actual)
actual = DataArray(data, dims=['x', 'y'], encoding={'bar': 2})
expected = Dataset({None: (['x', 'y'], data, {}, {'bar': 2})})[None]
self.assertDataArrayIdentical(expected, actual)
def test_constructor_invalid(self):
data = np.random.randn(3, 2)
with self.assertRaisesRegexp(ValueError, 'coords is not dict-like'):
DataArray(data, [[0, 1, 2]], ['x', 'y'])
with self.assertRaisesRegexp(ValueError, 'not a subset of the .* dim'):
DataArray(data, {'x': [0, 1, 2]}, ['a', 'b'])
with self.assertRaisesRegexp(ValueError, 'not a subset of the .* dim'):
DataArray(data, {'x': [0, 1, 2]})
with self.assertRaisesRegexp(TypeError, 'is not a string'):
DataArray(data, dims=['x', None])
with self.assertRaisesRegexp(ValueError, 'conflicting sizes for dim'):
DataArray([1, 2, 3], coords=[('x', [0, 1])])
with self.assertRaisesRegexp(ValueError, 'conflicting sizes for dim'):
DataArray([1, 2], coords={'x': [0, 1], 'y': ('x', [1])}, dims='x')
with self.assertRaisesRegexp(ValueError, 'conflicting MultiIndex'):
DataArray(np.random.rand(4, 4),
[('x', self.mindex), ('y', self.mindex)])
with self.assertRaisesRegexp(ValueError, 'conflicting MultiIndex'):
DataArray(np.random.rand(4, 4),
[('x', self.mindex), ('level_1', range(4))])
def test_constructor_from_self_described(self):
data = [[-0.1, 21], [0, 2]]
expected = DataArray(data,
coords={'x': ['a', 'b'], 'y': [-1, -2]},
dims=['x', 'y'], name='foobar',
attrs={'bar': 2}, encoding={'foo': 3})
actual = DataArray(expected)
self.assertDataArrayIdentical(expected, actual)
actual = DataArray(expected.values, actual.coords)
self.assertDataArrayEqual(expected, actual)
frame = pd.DataFrame(data, index=pd.Index(['a', 'b'], name='x'),
columns=pd.Index([-1, -2], name='y'))
actual = DataArray(frame)
self.assertDataArrayEqual(expected, actual)
series = pd.Series(data[0], index=pd.Index([-1, -2], name='y'))
actual = DataArray(series)
self.assertDataArrayEqual(expected[0].reset_coords('x', drop=True),
actual)
panel = pd.Panel({0: frame})
actual = DataArray(panel)
expected = DataArray([data], expected.coords, ['dim_0', 'x', 'y'])
expected['dim_0'] = [0]
self.assertDataArrayIdentical(expected, actual)
expected = DataArray(data,
coords={'x': ['a', 'b'], 'y': [-1, -2],
'a': 0, 'z': ('x', [-0.5, 0.5])},
dims=['x', 'y'])
actual = DataArray(expected)
self.assertDataArrayIdentical(expected, actual)
actual = DataArray(expected.values, expected.coords)
self.assertDataArrayIdentical(expected, actual)
expected = Dataset({'foo': ('foo', ['a', 'b'])})['foo']
actual = DataArray(pd.Index(['a', 'b'], name='foo'))
self.assertDataArrayIdentical(expected, actual)
actual = DataArray(IndexVariable('foo', ['a', 'b']))
self.assertDataArrayIdentical(expected, actual)
def test_constructor_from_0d(self):
expected = Dataset({None: ([], 0)})[None]
actual = DataArray(0)
self.assertDataArrayIdentical(expected, actual)
def test_equals_and_identical(self):
orig = DataArray(np.arange(5.0), {'a': 42}, dims='x')
expected = orig
actual = orig.copy()
self.assertTrue(expected.equals(actual))
self.assertTrue(expected.identical(actual))
actual = expected.rename('baz')
self.assertTrue(expected.equals(actual))
self.assertFalse(expected.identical(actual))
actual = expected.rename({'x': 'xxx'})
self.assertFalse(expected.equals(actual))
self.assertFalse(expected.identical(actual))
actual = expected.copy()
actual.attrs['foo'] = 'bar'
self.assertTrue(expected.equals(actual))
self.assertFalse(expected.identical(actual))
actual = expected.copy()
actual['x'] = ('x', -np.arange(5))
self.assertFalse(expected.equals(actual))
self.assertFalse(expected.identical(actual))
actual = expected.reset_coords(drop=True)
self.assertFalse(expected.equals(actual))
self.assertFalse(expected.identical(actual))
actual = orig.copy()
actual[0] = np.nan
expected = actual.copy()
self.assertTrue(expected.equals(actual))
self.assertTrue(expected.identical(actual))
actual[:] = np.nan
self.assertFalse(expected.equals(actual))
self.assertFalse(expected.identical(actual))
actual = expected.copy()
actual['a'] = 100000
self.assertFalse(expected.equals(actual))
self.assertFalse(expected.identical(actual))
def test_equals_failures(self):
orig = DataArray(np.arange(5.0), {'a': 42}, dims='x')
self.assertFalse(orig.equals(np.arange(5)))
self.assertFalse(orig.identical(123))
self.assertFalse(orig.broadcast_equals({1: 2}))
def test_broadcast_equals(self):
a = DataArray([0, 0], {'y': 0}, dims='x')
b = DataArray([0, 0], {'y': ('x', [0, 0])}, dims='x')
self.assertTrue(a.broadcast_equals(b))
self.assertTrue(b.broadcast_equals(a))
self.assertFalse(a.equals(b))
self.assertFalse(a.identical(b))
c = DataArray([0], coords={'x': 0}, dims='y')
self.assertFalse(a.broadcast_equals(c))
self.assertFalse(c.broadcast_equals(a))
def test_getitem(self):
# strings pull out dataarrays
self.assertDataArrayIdentical(self.dv, self.ds['foo'])
x = self.dv['x']
y = self.dv['y']
self.assertDataArrayIdentical(self.ds['x'], x)
self.assertDataArrayIdentical(self.ds['y'], y)
I = ReturnItem()
for i in [I[:], I[...], I[x.values], I[x.variable], I[x], I[x, y],
I[x.values > -1], I[x.variable > -1], I[x > -1],
I[x > -1, y > -1]]:
self.assertVariableEqual(self.dv, self.dv[i])
for i in [I[0], I[:, 0], I[:3, :2],
I[x.values[:3]], I[x.variable[:3]], I[x[:3]], I[x[:3], y[:4]],
I[x.values > 3], I[x.variable > 3], I[x > 3], I[x > 3, y > 3]]:
assert_array_equal(self.v[i], self.dv[i])
def test_getitem_dict(self):
actual = self.dv[{'x': slice(3), 'y': 0}]
expected = self.dv.isel(x=slice(3), y=0)
self.assertDataArrayIdentical(expected, actual)
def test_getitem_coords(self):
orig = DataArray([[10], [20]],
{'x': [1, 2], 'y': [3], 'z': 4,
'x2': ('x', ['a', 'b']),
'y2': ('y', ['c']),
'xy': (['y', 'x'], [['d', 'e']])},
dims=['x', 'y'])
self.assertDataArrayIdentical(orig, orig[:])
self.assertDataArrayIdentical(orig, orig[:, :])
self.assertDataArrayIdentical(orig, orig[...])
self.assertDataArrayIdentical(orig, orig[:2, :1])
self.assertDataArrayIdentical(orig, orig[[0, 1], [0]])
actual = orig[0, 0]
expected = DataArray(
10, {'x': 1, 'y': 3, 'z': 4, 'x2': 'a', 'y2': 'c', 'xy': 'd'})
self.assertDataArrayIdentical(expected, actual)
actual = orig[0, :]
expected = DataArray(
[10], {'x': 1, 'y': [3], 'z': 4, 'x2': 'a', 'y2': ('y', ['c']),
'xy': ('y', ['d'])},
dims='y')
self.assertDataArrayIdentical(expected, actual)
actual = orig[:, 0]
expected = DataArray(
[10, 20], {'x': [1, 2], 'y': 3, 'z': 4, 'x2': ('x', ['a', 'b']),
'y2': 'c', 'xy': ('x', ['d', 'e'])},
dims='x')
self.assertDataArrayIdentical(expected, actual)
def test_attr_sources_multiindex(self):
# make sure attr-style access for multi-index levels
# returns DataArray objects
self.assertIsInstance(self.mda.level_1, DataArray)
def test_pickle(self):
data = DataArray(np.random.random((3, 3)), dims=('id', 'time'))
roundtripped = pickle.loads(pickle.dumps(data))
self.assertDataArrayIdentical(data, roundtripped)
@requires_dask
def test_chunk(self):
unblocked = DataArray(np.ones((3, 4)))
self.assertIsNone(unblocked.chunks)
blocked = unblocked.chunk()
self.assertEqual(blocked.chunks, ((3,), (4,)))
blocked = unblocked.chunk(chunks=((2, 1), (2, 2)))
self.assertEqual(blocked.chunks, ((2, 1), (2, 2)))
blocked = unblocked.chunk(chunks=(3, 3))
self.assertEqual(blocked.chunks, ((3,), (3, 1)))
self.assertIsNone(blocked.load().chunks)
def test_isel(self):
self.assertDataArrayIdentical(self.dv[0], self.dv.isel(x=0))
self.assertDataArrayIdentical(self.dv, self.dv.isel(x=slice(None)))
self.assertDataArrayIdentical(self.dv[:3], self.dv.isel(x=slice(3)))
self.assertDataArrayIdentical(self.dv[:3, :5],
self.dv.isel(x=slice(3), y=slice(5)))
def test_sel(self):
self.ds['x'] = ('x', np.array(list('abcdefghij')))
da = self.ds['foo']
self.assertDataArrayIdentical(da, da.sel(x=slice(None)))
self.assertDataArrayIdentical(da[1], da.sel(x='b'))
self.assertDataArrayIdentical(da[:3], da.sel(x=slice('c')))
self.assertDataArrayIdentical(da[:3], da.sel(x=['a', 'b', 'c']))
self.assertDataArrayIdentical(da[:, :4], da.sel(y=(self.ds['y'] < 4)))
# verify that indexing with a dataarray works
b = DataArray('b')
self.assertDataArrayIdentical(da[1], da.sel(x=b))
self.assertDataArrayIdentical(da[[1]], da.sel(x=slice(b, b)))
def test_sel_no_index(self):
array = DataArray(np.arange(10), dims='x')
self.assertDataArrayIdentical(array[0], array.sel(x=0))
self.assertDataArrayIdentical(array[:5], array.sel(x=slice(5)))
self.assertDataArrayIdentical(array[[0, -1]], array.sel(x=[0, -1]))
self.assertDataArrayIdentical(
array[array < 5], array.sel(x=(array < 5)))
def test_sel_method(self):
data = DataArray(np.random.randn(3, 4),
[('x', [0, 1, 2]), ('y', list('abcd'))])
expected = data.sel(y=['a', 'b'])
actual = data.sel(y=['ab', 'ba'], method='pad')
self.assertDataArrayIdentical(expected, actual)
if pd.__version__ >= '0.17':
expected = data.sel(x=[1, 2])
actual = data.sel(x=[0.9, 1.9], method='backfill', tolerance=1)
self.assertDataArrayIdentical(expected, actual)
else:
with self.assertRaisesRegexp(TypeError, 'tolerance'):
data.sel(x=[0.9, 1.9], method='backfill', tolerance=1)
def test_sel_drop(self):
data = DataArray([1, 2, 3], [('x', [0, 1, 2])])
expected = DataArray(1)
selected = data.sel(x=0, drop=True)
self.assertDataArrayIdentical(expected, selected)
expected = DataArray(1, {'x': 0})
selected = data.sel(x=0, drop=False)
self.assertDataArrayIdentical(expected, selected)
data = DataArray([1, 2, 3], dims=['x'])
expected = DataArray(1)
selected = data.sel(x=0, drop=True)
self.assertDataArrayIdentical(expected, selected)
def test_isel_drop(self):
data = DataArray([1, 2, 3], [('x', [0, 1, 2])])
expected = DataArray(1)
selected = data.isel(x=0, drop=True)
self.assertDataArrayIdentical(expected, selected)
expected = DataArray(1, {'x': 0})
selected = data.isel(x=0, drop=False)
self.assertDataArrayIdentical(expected, selected)
def test_isel_points(self):
shape = (10, 5, 6)
np_array = np.random.random(shape)
da = DataArray(np_array, dims=['time', 'y', 'x'],
coords={'time': np.arange(0, 100, 10)})
y = [1, 3]
x = [3, 0]
expected = da.values[:, y, x]
actual = da.isel_points(y=y, x=x, dim='test_coord')
assert actual.coords['test_coord'].shape == (len(y), )
assert list(actual.coords) == ['time']
assert actual.dims == ('test_coord', 'time')
actual = da.isel_points(y=y, x=x)
assert 'points' in actual.dims
# Note that because xarray always concatenates along the first
# dimension, We must transpose the result to match the numpy style of
# concatenation.
np.testing.assert_equal(actual.T, expected)
# a few corner cases
da.isel_points(time=[1, 2], x=[2, 2], y=[3, 4])
np.testing.assert_allclose(
da.isel_points(time=[1], x=[2], y=[4]).values.squeeze(),
np_array[1, 4, 2].squeeze())
da.isel_points(time=[1, 2])
y = [-1, 0]
x = [-2, 2]
expected = da.values[:, y, x]
actual = da.isel_points(x=x, y=y).values
np.testing.assert_equal(actual.T, expected)
# test that the order of the indexers doesn't matter
self.assertDataArrayIdentical(
da.isel_points(y=y, x=x),
da.isel_points(x=x, y=y))
# make sure we're raising errors in the right places
with self.assertRaisesRegexp(ValueError,
'All indexers must be the same length'):
da.isel_points(y=[1, 2], x=[1, 2, 3])
with self.assertRaisesRegexp(ValueError,
'dimension bad_key does not exist'):
da.isel_points(bad_key=[1, 2])
with self.assertRaisesRegexp(TypeError, 'Indexers must be integers'):
da.isel_points(y=[1.5, 2.2])
with self.assertRaisesRegexp(TypeError, 'Indexers must be integers'):
da.isel_points(x=[1, 2, 3], y=slice(3))
with self.assertRaisesRegexp(ValueError,
'Indexers must be 1 dimensional'):
da.isel_points(y=1, x=2)
with self.assertRaisesRegexp(ValueError,
'Existing dimension names are not'):
da.isel_points(y=[1, 2], x=[1, 2], dim='x')
# using non string dims
actual = da.isel_points(y=[1, 2], x=[1, 2], dim=['A', 'B'])
assert 'points' in actual.coords
def test_loc(self):
self.ds['x'] = ('x', np.array(list('abcdefghij')))
da = self.ds['foo']
self.assertDataArrayIdentical(da[:3], da.loc[:'c'])
self.assertDataArrayIdentical(da[1], da.loc['b'])
self.assertDataArrayIdentical(da[1], da.loc[{'x': 'b'}])
self.assertDataArrayIdentical(da[1], da.loc['b', ...])
self.assertDataArrayIdentical(da[:3], da.loc[['a', 'b', 'c']])
self.assertDataArrayIdentical(da[:3, :4],
da.loc[['a', 'b', 'c'], np.arange(4)])
self.assertDataArrayIdentical(da[:, :4], da.loc[:, self.ds['y'] < 4])
da.loc['a':'j'] = 0
self.assertTrue(np.all(da.values == 0))
da.loc[{'x': slice('a', 'j')}] = 2
self.assertTrue(np.all(da.values == 2))
def test_loc_single_boolean(self):
data = DataArray([0, 1], coords=[[True, False]])
self.assertEqual(data.loc[True], 0)
self.assertEqual(data.loc[False], 1)
def test_selection_multiindex(self):
mindex = pd.MultiIndex.from_product([['a', 'b'], [1, 2], [-1, -2]],
names=('one', 'two', 'three'))
mdata = DataArray(range(8), [('x', mindex)])
def test_sel(lab_indexer, pos_indexer, replaced_idx=False,
renamed_dim=None):
da = mdata.sel(x=lab_indexer)
expected_da = mdata.isel(x=pos_indexer)
if not replaced_idx:
self.assertDataArrayIdentical(da, expected_da)
else:
if renamed_dim:
self.assertEqual(da.dims[0], renamed_dim)
da = da.rename({renamed_dim: 'x'})
self.assertVariableIdentical(da.variable, expected_da.variable)
self.assertVariableNotEqual(da['x'], expected_da['x'])
test_sel(('a', 1, -1), 0)
test_sel(('b', 2, -2), -1)
test_sel(('a', 1), [0, 1], replaced_idx=True, renamed_dim='three')
test_sel(('a',), range(4), replaced_idx=True)
test_sel('a', range(4), replaced_idx=True)
test_sel([('a', 1, -1), ('b', 2, -2)], [0, 7])
test_sel(slice('a', 'b'), range(8))
test_sel(slice(('a', 1), ('b', 1)), range(6))
test_sel({'one': 'a', 'two': 1, 'three': -1}, 0)
test_sel({'one': 'a', 'two': 1}, [0, 1], replaced_idx=True,
renamed_dim='three')
test_sel({'one': 'a'}, range(4), replaced_idx=True)
self.assertDataArrayIdentical(mdata.loc['a'], mdata.sel(x='a'))
self.assertDataArrayIdentical(mdata.loc[('a', 1), ...],
mdata.sel(x=('a', 1)))
self.assertDataArrayIdentical(mdata.loc[{'one': 'a'}, ...],
mdata.sel(x={'one': 'a'}))
with self.assertRaises(IndexError):
mdata.loc[('a', 1)]
self.assertDataArrayIdentical(mdata.sel(x={'one': 'a', 'two': 1}),
mdata.sel(one='a', two=1))
def test_virtual_default_coords(self):
array = DataArray(np.zeros((5,)), dims='x')
expected = DataArray(range(5), dims='x', name='x')
self.assertDataArrayIdentical(expected, array['x'])
self.assertDataArrayIdentical(expected, array.coords['x'])
def test_virtual_time_components(self):
dates = pd.date_range('2000-01-01', periods=10)
da = DataArray(np.arange(1, 11), [('time', dates)])
self.assertArrayEqual(da['time.dayofyear'], da.values)
self.assertArrayEqual(da.coords['time.dayofyear'], da.values)
def test_coords(self):
# use int64 to ensure repr() consistency on windows
coords = [IndexVariable('x', np.array([-1, -2], 'int64')),
IndexVariable('y', np.array([0, 1, 2], 'int64'))]
da = DataArray(np.random.randn(2, 3), coords, name='foo')
self.assertEquals(2, len(da.coords))
self.assertEqual(['x', 'y'], list(da.coords))
self.assertTrue(coords[0].identical(da.coords['x']))
self.assertTrue(coords[1].identical(da.coords['y']))
self.assertIn('x', da.coords)
self.assertNotIn(0, da.coords)
self.assertNotIn('foo', da.coords)
with self.assertRaises(KeyError):
da.coords[0]
with self.assertRaises(KeyError):
da.coords['foo']
expected = dedent("""\
Coordinates:
* x (x) int64 -1 -2
* y (y) int64 0 1 2""")
actual = repr(da.coords)
self.assertEquals(expected, actual)
del da.coords['x']
expected = DataArray(da.values, {'y': [0, 1, 2]}, dims=['x', 'y'],
name='foo')
self.assertDataArrayIdentical(da, expected)
with self.assertRaisesRegexp(ValueError, 'conflicting MultiIndex'):
self.mda['level_1'] = np.arange(4)
self.mda.coords['level_1'] = np.arange(4)
def test_coord_coords(self):
orig = DataArray([10, 20],
{'x': [1, 2], 'x2': ('x', ['a', 'b']), 'z': 4},
dims='x')
actual = orig.coords['x']
expected = DataArray([1, 2], {'z': 4, 'x2': ('x', ['a', 'b']),
'x': [1, 2]},
dims='x', name='x')
self.assertDataArrayIdentical(expected, actual)
del actual.coords['x2']
self.assertDataArrayIdentical(
expected.reset_coords('x2', drop=True), actual)
actual.coords['x3'] = ('x', ['a', 'b'])
expected = DataArray([1, 2], {'z': 4, 'x3': ('x', ['a', 'b']),
'x': [1, 2]},
dims='x', name='x')
self.assertDataArrayIdentical(expected, actual)
def test_reset_coords(self):
data = DataArray(np.zeros((3, 4)),
{'bar': ('x', ['a', 'b', 'c']),
'baz': ('y', range(4)),
'y': range(4)},
dims=['x', 'y'],
name='foo')
actual = data.reset_coords()
expected = Dataset({'foo': (['x', 'y'], np.zeros((3, 4))),
'bar': ('x', ['a', 'b', 'c']),
'baz': ('y', range(4)),
'y': range(4)})
self.assertDatasetIdentical(actual, expected)
actual = data.reset_coords(['bar', 'baz'])
self.assertDatasetIdentical(actual, expected)
actual = data.reset_coords('bar')
expected = Dataset({'foo': (['x', 'y'], np.zeros((3, 4))),
'bar': ('x', ['a', 'b', 'c'])},
{'baz': ('y', range(4)), 'y': range(4)})
self.assertDatasetIdentical(actual, expected)
actual = data.reset_coords(['bar'])
self.assertDatasetIdentical(actual, expected)
actual = data.reset_coords(drop=True)
expected = DataArray(np.zeros((3, 4)), coords={'y': range(4)},
dims=['x', 'y'], name='foo')
self.assertDataArrayIdentical(actual, expected)
actual = data.copy()
actual.reset_coords(drop=True, inplace=True)
self.assertDataArrayIdentical(actual, expected)
actual = data.reset_coords('bar', drop=True)
expected = DataArray(np.zeros((3, 4)),
{'baz': ('y', range(4)), 'y': range(4)},
dims=['x', 'y'], name='foo')
self.assertDataArrayIdentical(actual, expected)
with self.assertRaisesRegexp(ValueError, 'cannot reset coord'):
data.reset_coords(inplace=True)
with self.assertRaisesRegexp(ValueError, 'cannot be found'):
data.reset_coords('foo', drop=True)
with self.assertRaisesRegexp(ValueError, 'cannot be found'):
data.reset_coords('not_found')
with self.assertRaisesRegexp(ValueError, 'cannot remove index'):
data.reset_coords('y')
def test_assign_coords(self):
array = DataArray(10)
actual = array.assign_coords(c=42)
expected = DataArray(10, {'c': 42})
self.assertDataArrayIdentical(actual, expected)
array = DataArray([1, 2, 3, 4], {'c': ('x', [0, 0, 1, 1])}, dims='x')
actual = array.groupby('c').assign_coords(d=lambda a: a.mean())
expected = array.copy()
expected.coords['d'] = ('x', [1.5, 1.5, 3.5, 3.5])
self.assertDataArrayIdentical(actual, expected)
with self.assertRaisesRegexp(ValueError, 'conflicting MultiIndex'):
self.mda.assign_coords(level_1=range(4))
def test_coords_alignment(self):
lhs = DataArray([1, 2, 3], [('x', [0, 1, 2])])
rhs = DataArray([2, 3, 4], [('x', [1, 2, 3])])
lhs.coords['rhs'] = rhs
expected = DataArray([1, 2, 3],
coords={'rhs': ('x', [np.nan, 2, 3]),
'x': [0, 1, 2]},
dims='x')
self.assertDataArrayIdentical(lhs, expected)
def test_coords_replacement_alignment(self):
# regression test for GH725
arr = DataArray([0, 1, 2], dims=['abc'])
new_coord = DataArray([1, 2, 3], dims=['abc'], coords=[[1, 2, 3]])
arr['abc'] = new_coord
expected = DataArray([0, 1, 2], coords=[('abc', [1, 2, 3])])
self.assertDataArrayIdentical(arr, expected)
def test_coords_non_string(self):
arr = DataArray(0, coords={1: 2})
actual = arr.coords[1]
expected = DataArray(2, coords={1: 2}, name=1)
self.assertDataArrayIdentical(actual, expected)
def test_reindex_like(self):
foo = DataArray(np.random.randn(5, 6),
[('x', range(5)), ('y', range(6))])
bar = foo[:2, :2]
self.assertDataArrayIdentical(foo.reindex_like(bar), bar)
expected = foo.copy()
expected[:] = np.nan
expected[:2, :2] = bar
self.assertDataArrayIdentical(bar.reindex_like(foo), expected)
def test_reindex_like_no_index(self):
foo = DataArray(np.random.randn(5, 6), dims=['x', 'y'])
self.assertDatasetIdentical(foo, foo.reindex_like(foo))
bar = foo[:4]
with self.assertRaisesRegexp(
ValueError, 'different size for unlabeled'):
foo.reindex_like(bar)
def test_reindex_regressions(self):
# regression test for #279
expected = DataArray(np.random.randn(5), coords=[("time", range(5))])
time2 = DataArray(np.arange(5), dims="time2")
actual = expected.reindex(time=time2)
self.assertDataArrayIdentical(actual, expected)
# regression test for #736, reindex can not change complex nums dtype
x = np.array([1, 2, 3], dtype=np.complex)
x = DataArray(x, coords=[[0.1, 0.2, 0.3]])
y = DataArray([2, 5, 6, 7, 8], coords=[[-1.1, 0.21, 0.31, 0.41, 0.51]])
re_dtype = x.reindex_like(y, method='pad').dtype
self.assertEqual(x.dtype, re_dtype)
def test_reindex_method(self):
x = DataArray([10, 20], dims='y', coords={'y': [0, 1]})
y = [-0.1, 0.5, 1.1]
if pd.__version__ >= '0.17':
actual = x.reindex(y=y, method='backfill', tolerance=0.2)
expected = DataArray([10, np.nan, np.nan], coords=[('y', y)])
self.assertDataArrayIdentical(expected, actual)
alt = Dataset({'y': y})
actual = x.reindex_like(alt, method='backfill')
expected = DataArray([10, 20, np.nan], coords=[('y', y)])
self.assertDatasetIdentical(expected, actual)
def test_rename(self):
renamed = self.dv.rename('bar')
self.assertDatasetIdentical(
renamed.to_dataset(), self.ds.rename({'foo': 'bar'}))
self.assertEqual(renamed.name, 'bar')
renamed = self.dv.x.rename({'x': 'z'}).rename('z')
self.assertDatasetIdentical(
renamed, self.ds.rename({'x': 'z'}).z)
self.assertEqual(renamed.name, 'z')
self.assertEqual(renamed.dims, ('z',))
def test_swap_dims(self):
array = DataArray(np.random.randn(3), {'y': ('x', list('abc'))}, 'x')
expected = DataArray(array.values, {'y': list('abc')}, dims='y')
actual = array.swap_dims({'x': 'y'})
self.assertDataArrayIdentical(expected, actual)
def test_set_index(self):
indexes = [self.mindex.get_level_values(n) for n in self.mindex.names]
coords = {idx.name: ('x', idx) for idx in indexes}
array = DataArray(self.mda.values, coords=coords, dims='x')
expected = self.mda.copy()
level_3 = ('x', [1, 2, 3, 4])
array['level_3'] = level_3
expected['level_3'] = level_3
obj = array.set_index(x=self.mindex.names)
self.assertDataArrayIdentical(obj, expected)
obj = obj.set_index(x='level_3', append=True)
expected = array.set_index(x=['level_1', 'level_2', 'level_3'])
self.assertDataArrayIdentical(obj, expected)
array.set_index(x=['level_1', 'level_2', 'level_3'], inplace=True)
self.assertDataArrayIdentical(array, expected)
array2d = DataArray(np.random.rand(2, 2),
coords={'x': ('x', [0, 1]),
'level': ('y', [1, 2])},
dims=('x', 'y'))
with self.assertRaisesRegexp(ValueError, 'dimension mismatch'):
array2d.set_index(x='level')
def test_reset_index(self):
indexes = [self.mindex.get_level_values(n) for n in self.mindex.names]
coords = {idx.name: ('x', idx) for idx in indexes}
expected = DataArray(self.mda.values, coords=coords, dims='x')
obj = self.mda.reset_index('x')
self.assertDataArrayIdentical(obj, expected)
obj = self.mda.reset_index(self.mindex.names)
self.assertDataArrayIdentical(obj, expected)
obj = self.mda.reset_index(['x', 'level_1'])
self.assertDataArrayIdentical(obj, expected)
coords = {'x': ('x', self.mindex.droplevel('level_1')),
'level_1': ('x', self.mindex.get_level_values('level_1'))}
expected = DataArray(self.mda.values, coords=coords, dims='x')
obj = self.mda.reset_index(['level_1'])
self.assertDataArrayIdentical(obj, expected)
expected = DataArray(self.mda.values, dims='x')
obj = self.mda.reset_index('x', drop=True)
self.assertDataArrayIdentical(obj, expected)
array = self.mda.copy()
array.reset_index(['x'], drop=True, inplace=True)
self.assertDataArrayIdentical(array, expected)
# single index
array = DataArray([1, 2], coords={'x': ['a', 'b']}, dims='x')
expected = DataArray([1, 2], coords={'x_': ('x', ['a', 'b'])},
dims='x')
self.assertDataArrayIdentical(array.reset_index('x'), expected)
def test_reorder_levels(self):
midx = self.mindex.reorder_levels(['level_2', 'level_1'])
expected = DataArray(self.mda.values, coords={'x': midx}, dims='x')
obj = self.mda.reorder_levels(x=['level_2', 'level_1'])
self.assertDataArrayIdentical(obj, expected)
array = self.mda.copy()
array.reorder_levels(x=['level_2', 'level_1'], inplace=True)
self.assertDataArrayIdentical(array, expected)
array = DataArray([1, 2], dims='x')
with self.assertRaises(KeyError):
array.reorder_levels(x=['level_1', 'level_2'])
array['x'] = [0, 1]
with self.assertRaisesRegexp(ValueError, 'has no MultiIndex'):
array.reorder_levels(x=['level_1', 'level_2'])
def test_dataset_getitem(self):
dv = self.ds['foo']
self.assertDataArrayIdentical(dv, self.dv)
def test_array_interface(self):
self.assertArrayEqual(np.asarray(self.dv), self.x)
# test patched in methods
self.assertArrayEqual(self.dv.astype(float), self.v.astype(float))
assert_array_equal(self.dv.argsort(), self.v.argsort())
assert_array_equal(self.dv.clip(2, 3), self.v.clip(2, 3))
# test ufuncs
expected = deepcopy(self.ds)
expected['foo'][:] = np.sin(self.x)
self.assertDataArrayEqual(expected['foo'], np.sin(self.dv))
assert_array_equal(self.dv, np.maximum(self.v, self.dv))