This file is indexed.

/usr/lib/python3/dist-packages/xarray/tests/test_variable.py is in python3-xarray 0.10.2-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
from __future__ import absolute_import, division, print_function

from collections import namedtuple
from copy import copy, deepcopy
from datetime import datetime, timedelta
from distutils.version import LooseVersion
from textwrap import dedent

import numpy as np
import pandas as pd
import pytest
import pytz

from xarray import Coordinate, Dataset, IndexVariable, Variable
from xarray.core import indexing
from xarray.core.common import full_like, ones_like, zeros_like
from xarray.core.indexing import (
    BasicIndexer, CopyOnWriteArray, DaskIndexingAdapter,
    LazilyOuterIndexedArray, MemoryCachedArray, NumpyIndexingAdapter,
    OuterIndexer, PandasIndexAdapter, VectorizedIndexer)
from xarray.core.pycompat import PY3, OrderedDict
from xarray.core.utils import NDArrayMixin
from xarray.core.variable import as_compatible_data, as_variable
from xarray.tests import requires_bottleneck

from . import (
    TestCase, assert_allclose, assert_array_equal, assert_equal,
    assert_identical, raises_regex, requires_dask, source_ndarray)


class VariableSubclassTestCases(object):
    def test_properties(self):
        data = 0.5 * np.arange(10)
        v = self.cls(['time'], data, {'foo': 'bar'})
        assert v.dims == ('time',)
        assert_array_equal(v.values, data)
        assert v.dtype == float
        assert v.shape == (10,)
        assert v.size == 10
        assert v.sizes == {'time': 10}
        assert v.nbytes == 80
        assert v.ndim == 1
        assert len(v) == 10
        assert v.attrs == {'foo': u'bar'}

    def test_attrs(self):
        v = self.cls(['time'], 0.5 * np.arange(10))
        assert v.attrs == {}
        attrs = {'foo': 'bar'}
        v.attrs = attrs
        assert v.attrs == attrs
        assert isinstance(v.attrs, OrderedDict)
        v.attrs['foo'] = 'baz'
        assert v.attrs['foo'] == 'baz'

    def test_getitem_dict(self):
        v = self.cls(['x'], np.random.randn(5))
        actual = v[{'x': 0}]
        expected = v[0]
        assert_identical(expected, actual)

    def test_getitem_1d(self):
        data = np.array([0, 1, 2])
        v = self.cls(['x'], data)

        v_new = v[dict(x=[0, 1])]
        assert v_new.dims == ('x', )
        assert_array_equal(v_new, data[[0, 1]])

        v_new = v[dict(x=slice(None))]
        assert v_new.dims == ('x', )
        assert_array_equal(v_new, data)

        v_new = v[dict(x=Variable('a', [0, 1]))]
        assert v_new.dims == ('a', )
        assert_array_equal(v_new, data[[0, 1]])

        v_new = v[dict(x=1)]
        assert v_new.dims == ()
        assert_array_equal(v_new, data[1])

        # tuple argument
        v_new = v[slice(None)]
        assert v_new.dims == ('x', )
        assert_array_equal(v_new, data)

    def test_getitem_1d_fancy(self):
        v = self.cls(['x'], [0, 1, 2])
        # 1d-variable should be indexable by multi-dimensional Variable
        ind = Variable(('a', 'b'), [[0, 1], [0, 1]])
        v_new = v[ind]
        assert v_new.dims == ('a', 'b')
        expected = np.array(v._data)[([0, 1], [0, 1]), ]
        assert_array_equal(v_new, expected)

        # boolean indexing
        ind = Variable(('x', ), [True, False, True])
        v_new = v[ind]
        assert_identical(v[[0, 2]], v_new)
        v_new = v[[True, False, True]]
        assert_identical(v[[0, 2]], v_new)

        with raises_regex(IndexError, "Boolean indexer should"):
            ind = Variable(('a', ), [True, False, True])
            v[ind]

    def test_getitem_with_mask(self):
        v = self.cls(['x'], [0, 1, 2])
        assert_identical(v._getitem_with_mask(-1), Variable((), np.nan))
        assert_identical(v._getitem_with_mask([0, -1, 1]),
                         self.cls(['x'], [0, np.nan, 1]))
        assert_identical(v._getitem_with_mask(slice(2)),
                         self.cls(['x'], [0, 1]))
        assert_identical(v._getitem_with_mask([0, -1, 1], fill_value=-99),
                         self.cls(['x'], [0, -99, 1]))

    def test_getitem_with_mask_size_zero(self):
        v = self.cls(['x'], [])
        assert_identical(v._getitem_with_mask(-1), Variable((), np.nan))
        assert_identical(v._getitem_with_mask([-1, -1, -1]),
                         self.cls(['x'], [np.nan, np.nan, np.nan]))

    def test_getitem_with_mask_nd_indexer(self):
        v = self.cls(['x'], [0, 1, 2])
        indexer = Variable(('x', 'y'), [[0, -1], [-1, 2]])
        assert_identical(v._getitem_with_mask(indexer, fill_value=-1), indexer)

    def _assertIndexedLikeNDArray(self, variable, expected_value0,
                                  expected_dtype=None):
        """Given a 1-dimensional variable, verify that the variable is indexed
        like a numpy.ndarray.
        """
        assert variable[0].shape == ()
        assert variable[0].ndim == 0
        assert variable[0].size == 1
        # test identity
        assert variable.equals(variable.copy())
        assert variable.identical(variable.copy())
        # check value is equal for both ndarray and Variable
        assert variable.values[0] == expected_value0
        assert variable[0].values == expected_value0
        # check type or dtype is consistent for both ndarray and Variable
        if expected_dtype is None:
            # check output type instead of array dtype
            assert type(variable.values[0]) == type(expected_value0)
            assert type(variable[0].values) == type(expected_value0)
        elif expected_dtype is not False:
            assert variable.values[0].dtype == expected_dtype
            assert variable[0].values.dtype == expected_dtype

    def test_index_0d_int(self):
        for value, dtype in [(0, np.int_),
                             (np.int32(0), np.int32)]:
            x = self.cls(['x'], [value])
            self._assertIndexedLikeNDArray(x, value, dtype)

    def test_index_0d_float(self):
        for value, dtype in [(0.5, np.float_),
                             (np.float32(0.5), np.float32)]:
            x = self.cls(['x'], [value])
            self._assertIndexedLikeNDArray(x, value, dtype)

    def test_index_0d_string(self):
        for value, dtype in [('foo', np.dtype('U3' if PY3 else 'S3')),
                             (u'foo', np.dtype('U3'))]:
            x = self.cls(['x'], [value])
            self._assertIndexedLikeNDArray(x, value, dtype)

    def test_index_0d_datetime(self):
        d = datetime(2000, 1, 1)
        x = self.cls(['x'], [d])
        self._assertIndexedLikeNDArray(x, np.datetime64(d))

        x = self.cls(['x'], [np.datetime64(d)])
        self._assertIndexedLikeNDArray(x, np.datetime64(d), 'datetime64[ns]')

        x = self.cls(['x'], pd.DatetimeIndex([d]))
        self._assertIndexedLikeNDArray(x, np.datetime64(d), 'datetime64[ns]')

    def test_index_0d_timedelta64(self):
        td = timedelta(hours=1)

        x = self.cls(['x'], [np.timedelta64(td)])
        self._assertIndexedLikeNDArray(
            x, np.timedelta64(td), 'timedelta64[ns]')

        x = self.cls(['x'], pd.to_timedelta([td]))
        self._assertIndexedLikeNDArray(
            x, np.timedelta64(td), 'timedelta64[ns]')

    def test_index_0d_not_a_time(self):
        d = np.datetime64('NaT', 'ns')
        x = self.cls(['x'], [d])
        self._assertIndexedLikeNDArray(x, d)

    def test_index_0d_object(self):

        class HashableItemWrapper(object):
            def __init__(self, item):
                self.item = item

            def __eq__(self, other):
                return self.item == other.item

            def __hash__(self):
                return hash(self.item)

            def __repr__(self):
                return '%s(item=%r)' % (type(self).__name__, self.item)

        item = HashableItemWrapper((1, 2, 3))
        x = self.cls('x', [item])
        self._assertIndexedLikeNDArray(x, item, expected_dtype=False)

    def test_0d_object_array_with_list(self):
        listarray = np.empty((1,), dtype=object)
        listarray[0] = [1, 2, 3]
        x = self.cls('x', listarray)
        assert_array_equal(x.data, listarray)
        assert_array_equal(x[0].data, listarray.squeeze())
        assert_array_equal(x.squeeze().data, listarray.squeeze())

    def test_index_and_concat_datetime(self):
        # regression test for #125
        date_range = pd.date_range('2011-09-01', periods=10)
        for dates in [date_range, date_range.values,
                      date_range.to_pydatetime()]:
            expected = self.cls('t', dates)
            for times in [[expected[i] for i in range(10)],
                          [expected[i:(i + 1)] for i in range(10)],
                          [expected[[i]] for i in range(10)]]:
                actual = Variable.concat(times, 't')
                assert expected.dtype == actual.dtype
                assert_array_equal(expected, actual)

    def test_0d_time_data(self):
        # regression test for #105
        x = self.cls('time', pd.date_range('2000-01-01', periods=5))
        expected = np.datetime64('2000-01-01', 'ns')
        assert x[0].values == expected

    def test_datetime64_conversion(self):
        times = pd.date_range('2000-01-01', periods=3)
        for values, preserve_source in [
            (times, True),
            (times.values, True),
            (times.values.astype('datetime64[s]'), False),
            (times.to_pydatetime(), False),
        ]:
            v = self.cls(['t'], values)
            assert v.dtype == np.dtype('datetime64[ns]')
            assert_array_equal(v.values, times.values)
            assert v.values.dtype == np.dtype('datetime64[ns]')
            same_source = source_ndarray(v.values) is source_ndarray(values)
            assert preserve_source == same_source

    def test_timedelta64_conversion(self):
        times = pd.timedelta_range(start=0, periods=3)
        for values, preserve_source in [
            (times, True),
            (times.values, True),
            (times.values.astype('timedelta64[s]'), False),
            (times.to_pytimedelta(), False),
        ]:
            v = self.cls(['t'], values)
            assert v.dtype == np.dtype('timedelta64[ns]')
            assert_array_equal(v.values, times.values)
            assert v.values.dtype == np.dtype('timedelta64[ns]')
            same_source = source_ndarray(v.values) is source_ndarray(values)
            assert preserve_source == same_source

    def test_object_conversion(self):
        data = np.arange(5).astype(str).astype(object)
        actual = self.cls('x', data)
        assert actual.dtype == data.dtype

    def test_pandas_data(self):
        v = self.cls(['x'], pd.Series([0, 1, 2], index=[3, 2, 1]))
        assert_identical(v, v[[0, 1, 2]])
        v = self.cls(['x'], pd.Index([0, 1, 2]))
        assert v[0].values == v.values[0]

    def test_pandas_period_index(self):
        v = self.cls(['x'], pd.period_range(start='2000', periods=20,
                                            freq='B'))
        v = v.load()  # for dask-based Variable
        assert v[0] == pd.Period('2000', freq='B')
        assert "Period('2000-01-03', 'B')" in repr(v)

    def test_1d_math(self):
        x = 1.0 * np.arange(5)
        y = np.ones(5)

        # should we need `.to_base_variable()`?
        # probably a break that `+v` changes type?
        v = self.cls(['x'], x)
        base_v = v.to_base_variable()
        # unary ops
        assert_identical(base_v, +v)
        assert_identical(base_v, abs(v))
        assert_array_equal((-v).values, -x)
        # binary ops with numbers
        assert_identical(base_v, v + 0)
        assert_identical(base_v, 0 + v)
        assert_identical(base_v, v * 1)
        # binary ops with numpy arrays
        assert_array_equal((v * x).values, x ** 2)
        assert_array_equal((x * v).values, x ** 2)
        assert_array_equal(v - y, v - 1)
        assert_array_equal(y - v, 1 - v)
        # verify attributes are dropped
        v2 = self.cls(['x'], x, {'units': 'meters'})
        assert_identical(base_v, +v2)
        # binary ops with all variables
        assert_array_equal(v + v, 2 * v)
        w = self.cls(['x'], y, {'foo': 'bar'})
        assert_identical(v + w, self.cls(['x'], x + y).to_base_variable())
        assert_array_equal((v * w).values, x * y)

        # something complicated
        assert_array_equal((v ** 2 * w - 1 + x).values, x ** 2 * y - 1 + x)
        # make sure dtype is preserved (for Index objects)
        assert float == (+v).dtype
        assert float == (+v).values.dtype
        assert float == (0 + v).dtype
        assert float == (0 + v).values.dtype
        # check types of returned data
        assert isinstance(+v, Variable)
        assert not isinstance(+v, IndexVariable)
        assert isinstance(0 + v, Variable)
        assert not isinstance(0 + v, IndexVariable)

    def test_1d_reduce(self):
        x = np.arange(5)
        v = self.cls(['x'], x)
        actual = v.sum()
        expected = Variable((), 10)
        assert_identical(expected, actual)
        assert type(actual) is Variable

    def test_array_interface(self):
        x = np.arange(5)
        v = self.cls(['x'], x)
        assert_array_equal(np.asarray(v), x)
        # test patched in methods
        assert_array_equal(v.astype(float), x.astype(float))
        # think this is a break, that argsort changes the type
        assert_identical(v.argsort(), v.to_base_variable())
        assert_identical(v.clip(2, 3),
                         self.cls('x', x.clip(2, 3)).to_base_variable())
        # test ufuncs
        assert_identical(np.sin(v),
                         self.cls(['x'], np.sin(x)).to_base_variable())
        assert isinstance(np.sin(v), Variable)
        assert not isinstance(np.sin(v), IndexVariable)

    def example_1d_objects(self):
        for data in [range(3),
                     0.5 * np.arange(3),
                     0.5 * np.arange(3, dtype=np.float32),
                     pd.date_range('2000-01-01', periods=3),
                     np.array(['a', 'b', 'c'], dtype=object)]:
            yield (self.cls('x', data), data)

    def test___array__(self):
        for v, data in self.example_1d_objects():
            assert_array_equal(v.values, np.asarray(data))
            assert_array_equal(np.asarray(v), np.asarray(data))
            assert v[0].values == np.asarray(data)[0]
            assert np.asarray(v[0]) == np.asarray(data)[0]

    def test_equals_all_dtypes(self):
        for v, _ in self.example_1d_objects():
            v2 = v.copy()
            assert v.equals(v2)
            assert v.identical(v2)
            assert v.no_conflicts(v2)
            assert v[0].equals(v2[0])
            assert v[0].identical(v2[0])
            assert v[0].no_conflicts(v2[0])
            assert v[:2].equals(v2[:2])
            assert v[:2].identical(v2[:2])
            assert v[:2].no_conflicts(v2[:2])

    def test_eq_all_dtypes(self):
        # ensure that we don't choke on comparisons for which numpy returns
        # scalars
        expected = Variable('x', 3 * [False])
        for v, _ in self.example_1d_objects():
            actual = 'z' == v
            assert_identical(expected, actual)
            actual = ~('z' != v)
            assert_identical(expected, actual)

    def test_encoding_preserved(self):
        expected = self.cls('x', range(3), {'foo': 1}, {'bar': 2})
        for actual in [expected.T,
                       expected[...],
                       expected.squeeze(),
                       expected.isel(x=slice(None)),
                       expected.set_dims({'x': 3}),
                       expected.copy(deep=True),
                       expected.copy(deep=False)]:

            assert_identical(expected.to_base_variable(),
                             actual.to_base_variable())
            assert expected.encoding == actual.encoding

    def test_concat(self):
        x = np.arange(5)
        y = np.arange(5, 10)
        v = self.cls(['a'], x)
        w = self.cls(['a'], y)
        assert_identical(Variable(['b', 'a'], np.array([x, y])),
                         Variable.concat([v, w], 'b'))
        assert_identical(Variable(['b', 'a'], np.array([x, y])),
                         Variable.concat((v, w), 'b'))
        assert_identical(Variable(['b', 'a'], np.array([x, y])),
                         Variable.concat((v, w), 'b'))
        with raises_regex(ValueError, 'inconsistent dimensions'):
            Variable.concat([v, Variable(['c'], y)], 'b')
        # test indexers
        actual = Variable.concat(
            [v, w],
            positions=[np.arange(0, 10, 2), np.arange(1, 10, 2)],
            dim='a')
        expected = Variable('a', np.array([x, y]).ravel(order='F'))
        assert_identical(expected, actual)
        # test concatenating along a dimension
        v = Variable(['time', 'x'], np.random.random((10, 8)))
        assert_identical(v, Variable.concat([v[:5], v[5:]], 'time'))
        assert_identical(v, Variable.concat([v[:5], v[5:6], v[6:]], 'time'))
        assert_identical(v, Variable.concat([v[:1], v[1:]], 'time'))
        # test dimension order
        assert_identical(v, Variable.concat([v[:, :5], v[:, 5:]], 'x'))
        with raises_regex(ValueError, 'all input arrays must have'):
            Variable.concat([v[:, 0], v[:, 1:]], 'x')

    def test_concat_attrs(self):
        # different or conflicting attributes should be removed
        v = self.cls('a', np.arange(5), {'foo': 'bar'})
        w = self.cls('a', np.ones(5))
        expected = self.cls(
            'a', np.concatenate([np.arange(5), np.ones(5)])).to_base_variable()
        assert_identical(expected, Variable.concat([v, w], 'a'))
        w.attrs['foo'] = 2
        assert_identical(expected, Variable.concat([v, w], 'a'))
        w.attrs['foo'] = 'bar'
        expected.attrs['foo'] = 'bar'
        assert_identical(expected, Variable.concat([v, w], 'a'))

    def test_concat_fixed_len_str(self):
        # regression test for #217
        for kind in ['S', 'U']:
            x = self.cls('animal', np.array(['horse'], dtype=kind))
            y = self.cls('animal', np.array(['aardvark'], dtype=kind))
            actual = Variable.concat([x, y], 'animal')
            expected = Variable(
                'animal', np.array(['horse', 'aardvark'], dtype=kind))
            assert_equal(expected, actual)

    def test_concat_number_strings(self):
        # regression test for #305
        a = self.cls('x', ['0', '1', '2'])
        b = self.cls('x', ['3', '4'])
        actual = Variable.concat([a, b], dim='x')
        expected = Variable('x', np.arange(5).astype(str))
        assert_identical(expected, actual)
        assert actual.dtype.kind == expected.dtype.kind

    def test_concat_mixed_dtypes(self):
        a = self.cls('x', [0, 1])
        b = self.cls('x', ['two'])
        actual = Variable.concat([a, b], dim='x')
        expected = Variable('x', np.array([0, 1, 'two'], dtype=object))
        assert_identical(expected, actual)
        assert actual.dtype == object

    def test_copy(self):
        v = self.cls('x', 0.5 * np.arange(10), {'foo': 'bar'})
        for deep in [True, False]:
            w = v.copy(deep=deep)
            assert type(v) is type(w)
            assert_identical(v, w)
            assert v.dtype == w.dtype
            if self.cls is Variable:
                if deep:
                    assert source_ndarray(v.values) is not \
                        source_ndarray(w.values)
                else:
                    assert source_ndarray(v.values) is \
                        source_ndarray(w.values)
        assert_identical(v, copy(v))

    def test_copy_index(self):
        midx = pd.MultiIndex.from_product([['a', 'b'], [1, 2], [-1, -2]],
                                          names=('one', 'two', 'three'))
        v = self.cls('x', midx)
        for deep in [True, False]:
            w = v.copy(deep=deep)
            assert isinstance(w._data, PandasIndexAdapter)
            assert isinstance(w.to_index(), pd.MultiIndex)
            assert_array_equal(v._data.array, w._data.array)

    def test_real_and_imag(self):
        v = self.cls('x', np.arange(3) - 1j * np.arange(3), {'foo': 'bar'})
        expected_re = self.cls('x', np.arange(3), {'foo': 'bar'})
        assert_identical(v.real, expected_re)

        expected_im = self.cls('x', -np.arange(3), {'foo': 'bar'})
        assert_identical(v.imag, expected_im)

        expected_abs = self.cls(
            'x', np.sqrt(2 * np.arange(3) ** 2)).to_base_variable()
        assert_allclose(abs(v), expected_abs)

    def test_aggregate_complex(self):
        # should skip NaNs
        v = self.cls('x', [1, 2j, np.nan])
        expected = Variable((), 0.5 + 1j)
        assert_allclose(v.mean(), expected)

    def test_pandas_cateogrical_dtype(self):
        data = pd.Categorical(np.arange(10, dtype='int64'))
        v = self.cls('x', data)
        print(v)  # should not error
        assert v.dtype == 'int64'

    def test_pandas_datetime64_with_tz(self):
        data = pd.date_range(start='2000-01-01',
                             tz=pytz.timezone('America/New_York'),
                             periods=10, freq='1h')
        v = self.cls('x', data)
        print(v)  # should not error
        if 'America/New_York' in str(data.dtype):
            # pandas is new enough that it has datetime64 with timezone dtype
            assert v.dtype == 'object'

    def test_multiindex(self):
        idx = pd.MultiIndex.from_product([list('abc'), [0, 1]])
        v = self.cls('x', idx)
        assert_identical(Variable((), ('a', 0)), v[0])
        assert_identical(v, v[:])

    def test_load(self):
        array = self.cls('x', np.arange(5))
        orig_data = array._data
        copied = array.copy(deep=True)
        if array.chunks is None:
            array.load()
            assert type(array._data) is type(orig_data)
            assert type(copied._data) is type(orig_data)
            assert_identical(array, copied)

    def test_getitem_advanced(self):
        v = self.cls(['x', 'y'], [[0, 1, 2], [3, 4, 5]])
        v_data = v.compute().data

        # orthogonal indexing
        v_new = v[([0, 1], [1, 0])]
        assert v_new.dims == ('x', 'y')
        assert_array_equal(v_new, v_data[[0, 1]][:, [1, 0]])

        v_new = v[[0, 1]]
        assert v_new.dims == ('x', 'y')
        assert_array_equal(v_new, v_data[[0, 1]])

        # with mixed arguments
        ind = Variable(['a'], [0, 1])
        v_new = v[dict(x=[0, 1], y=ind)]
        assert v_new.dims == ('x', 'a')
        assert_array_equal(v_new, v_data[[0, 1]][:, [0, 1]])

        # boolean indexing
        v_new = v[dict(x=[True, False], y=[False, True, False])]
        assert v_new.dims == ('x', 'y')
        assert_array_equal(v_new, v_data[0][1])

        # with scalar variable
        ind = Variable((), 2)
        v_new = v[dict(y=ind)]
        expected = v[dict(y=2)]
        assert_array_equal(v_new, expected)

        # with boolean variable with wrong shape
        ind = np.array([True, False])
        with raises_regex(IndexError, 'Boolean array size 2 is '):
            v[Variable(('a', 'b'), [[0, 1]]), ind]

        # boolean indexing with different dimension
        ind = Variable(['a'], [True, False, False])
        with raises_regex(IndexError, 'Boolean indexer should be'):
            v[dict(y=ind)]

    def test_getitem_uint_1d(self):
        # regression test for #1405
        v = self.cls(['x'], [0, 1, 2])
        v_data = v.compute().data

        v_new = v[np.array([0])]
        assert_array_equal(v_new, v_data[0])
        v_new = v[np.array([0], dtype="uint64")]
        assert_array_equal(v_new, v_data[0])

    def test_getitem_uint(self):
        # regression test for #1405
        v = self.cls(['x', 'y'], [[0, 1, 2], [3, 4, 5]])
        v_data = v.compute().data

        v_new = v[np.array([0])]
        assert_array_equal(v_new, v_data[[0], :])
        v_new = v[np.array([0], dtype="uint64")]
        assert_array_equal(v_new, v_data[[0], :])

        v_new = v[np.uint64(0)]
        assert_array_equal(v_new, v_data[0, :])

    def test_getitem_0d_array(self):
        # make sure 0d-np.array can be used as an indexer
        v = self.cls(['x'], [0, 1, 2])
        v_data = v.compute().data

        v_new = v[np.array([0])[0]]
        assert_array_equal(v_new, v_data[0])

        v_new = v[np.array(0)]
        assert_array_equal(v_new, v_data[0])

        v_new = v[Variable((), np.array(0))]
        assert_array_equal(v_new, v_data[0])

    def test_getitem_fancy(self):
        v = self.cls(['x', 'y'], [[0, 1, 2], [3, 4, 5]])
        v_data = v.compute().data

        ind = Variable(['a', 'b'], [[0, 1, 1], [1, 1, 0]])
        v_new = v[ind]
        assert v_new.dims == ('a', 'b', 'y')
        assert_array_equal(v_new, v_data[[[0, 1, 1], [1, 1, 0]], :])

        # It would be ok if indexed with the multi-dimensional array including
        # the same name
        ind = Variable(['x', 'b'], [[0, 1, 1], [1, 1, 0]])
        v_new = v[ind]
        assert v_new.dims == ('x', 'b', 'y')
        assert_array_equal(v_new, v_data[[[0, 1, 1], [1, 1, 0]], :])

        ind = Variable(['a', 'b'], [[0, 1, 2], [2, 1, 0]])
        v_new = v[dict(y=ind)]
        assert v_new.dims == ('x', 'a', 'b')
        assert_array_equal(v_new, v_data[:, ([0, 1, 2], [2, 1, 0])])

        ind = Variable(['a', 'b'], [[0, 0], [1, 1]])
        v_new = v[dict(x=[1, 0], y=ind)]
        assert v_new.dims == ('x', 'a', 'b')
        assert_array_equal(v_new, v_data[[1, 0]][:, ind])

        # along diagonal
        ind = Variable(['a'], [0, 1])
        v_new = v[ind, ind]
        assert v_new.dims == ('a',)
        assert_array_equal(v_new, v_data[[0, 1], [0, 1]])

        # with integer
        ind = Variable(['a', 'b'], [[0, 0], [1, 1]])
        v_new = v[dict(x=0, y=ind)]
        assert v_new.dims == ('a', 'b')
        assert_array_equal(v_new[0], v_data[0][[0, 0]])
        assert_array_equal(v_new[1], v_data[0][[1, 1]])

        # with slice
        ind = Variable(['a', 'b'], [[0, 0], [1, 1]])
        v_new = v[dict(x=slice(None), y=ind)]
        assert v_new.dims == ('x', 'a', 'b')
        assert_array_equal(v_new, v_data[:, [[0, 0], [1, 1]]])

        ind = Variable(['a', 'b'], [[0, 0], [1, 1]])
        v_new = v[dict(x=ind, y=slice(None))]
        assert v_new.dims == ('a', 'b', 'y')
        assert_array_equal(v_new, v_data[[[0, 0], [1, 1]], :])

        ind = Variable(['a', 'b'], [[0, 0], [1, 1]])
        v_new = v[dict(x=ind, y=slice(None, 1))]
        assert v_new.dims == ('a', 'b', 'y')
        assert_array_equal(v_new, v_data[[[0, 0], [1, 1]], slice(None, 1)])

        # slice matches explicit dimension
        ind = Variable(['y'], [0, 1])
        v_new = v[ind, :2]
        assert v_new.dims == ('y',)
        assert_array_equal(v_new, v_data[[0, 1], [0, 1]])

        # with multiple slices
        v = self.cls(['x', 'y', 'z'], [[[1, 2, 3], [4, 5, 6]]])
        ind = Variable(['a', 'b'], [[0]])
        v_new = v[ind, :, :]
        expected = Variable(['a', 'b', 'y', 'z'], v.data[np.newaxis, ...])
        assert_identical(v_new, expected)

        v = Variable(['w', 'x', 'y', 'z'], [[[[1, 2, 3], [4, 5, 6]]]])
        ind = Variable(['y'], [0])
        v_new = v[ind, :, 1:2, 2]
        expected = Variable(['y', 'x'], [[6]])
        assert_identical(v_new, expected)

        # slice and vector mixed indexing resulting in the same dimension
        v = Variable(['x', 'y', 'z'], np.arange(60).reshape(3, 4, 5))
        ind = Variable(['x'], [0, 1, 2])
        v_new = v[:, ind]
        expected = Variable(('x', 'z'), np.zeros((3, 5)))
        expected[0] = v.data[0, 0]
        expected[1] = v.data[1, 1]
        expected[2] = v.data[2, 2]
        assert_identical(v_new, expected)

        v_new = v[:, ind.data]
        assert v_new.shape == (3, 3, 5)

    def test_getitem_error(self):
        v = self.cls(['x', 'y'], [[0, 1, 2], [3, 4, 5]])

        with raises_regex(IndexError, "labeled multi-"):
            v[[[0, 1], [1, 2]]]

        ind_x = Variable(['a'], [0, 1, 1])
        ind_y = Variable(['a'], [0, 1])
        with raises_regex(IndexError, "Dimensions of indexers "):
            v[ind_x, ind_y]

        ind = Variable(['a', 'b'], [[True, False], [False, True]])
        with raises_regex(IndexError, '2-dimensional boolean'):
            v[dict(x=ind)]

        v = Variable(['x', 'y', 'z'], np.arange(60).reshape(3, 4, 5))
        ind = Variable(['x'], [0, 1])
        with raises_regex(IndexError, 'Dimensions of indexers mis'):
            v[:, ind]

    def test_pad(self):
        data = np.arange(4 * 3 * 2).reshape(4, 3, 2)
        v = self.cls(['x', 'y', 'z'], data)

        xr_args = [{'x': (2, 1)}, {'y': (0, 3)}, {'x': (3, 1), 'z': (2, 0)}]
        np_args = [((2, 1), (0, 0), (0, 0)), ((0, 0), (0, 3), (0, 0)),
                   ((3, 1), (0, 0), (2, 0))]
        for xr_arg, np_arg in zip(xr_args, np_args):
            actual = v.pad_with_fill_value(**xr_arg)
            expected = np.pad(np.array(v.data.astype(float)), np_arg,
                              mode='constant', constant_values=np.nan)
            assert_array_equal(actual, expected)
            assert isinstance(actual._data, type(v._data))

        # for the boolean array, we pad False
        data = np.full_like(data, False, dtype=bool).reshape(4, 3, 2)
        v = self.cls(['x', 'y', 'z'], data)
        for xr_arg, np_arg in zip(xr_args, np_args):
            actual = v.pad_with_fill_value(fill_value=False, **xr_arg)
            expected = np.pad(np.array(v.data), np_arg,
                              mode='constant', constant_values=False)
            assert_array_equal(actual, expected)

    def test_rolling_window(self):
        # Just a working test. See test_nputils for the algorithm validation
        v = self.cls(['x', 'y', 'z'],
                     np.arange(40 * 30 * 2).reshape(40, 30, 2))
        for (d, w) in [('x', 3), ('y', 5)]:
            v_rolling = v.rolling_window(d, w, d + '_window')
            assert v_rolling.dims == ('x', 'y', 'z', d + '_window')
            assert v_rolling.shape == v.shape + (w, )

            v_rolling = v.rolling_window(d, w, d + '_window', center=True)
            assert v_rolling.dims == ('x', 'y', 'z', d + '_window')
            assert v_rolling.shape == v.shape + (w, )

            # dask and numpy result should be the same
            v_loaded = v.load().rolling_window(d, w, d + '_window',
                                               center=True)
            assert_array_equal(v_rolling, v_loaded)

            # numpy backend should not be over-written
            if isinstance(v._data, np.ndarray):
                with pytest.raises(ValueError):
                    v_loaded[0] = 1.0


class TestVariable(TestCase, VariableSubclassTestCases):
    cls = staticmethod(Variable)

    def setUp(self):
        self.d = np.random.random((10, 3)).astype(np.float64)

    def test_data_and_values(self):
        v = Variable(['time', 'x'], self.d)
        assert_array_equal(v.data, self.d)
        assert_array_equal(v.values, self.d)
        assert source_ndarray(v.values) is self.d
        with pytest.raises(ValueError):
            # wrong size
            v.values = np.random.random(5)
        d2 = np.random.random((10, 3))
        v.values = d2
        assert source_ndarray(v.values) is d2
        d3 = np.random.random((10, 3))
        v.data = d3
        assert source_ndarray(v.data) is d3

    def test_numpy_same_methods(self):
        v = Variable([], np.float32(0.0))
        assert v.item() == 0
        assert type(v.item()) is float

        v = IndexVariable('x', np.arange(5))
        assert 2 == v.searchsorted(2)

    def test_datetime64_conversion_scalar(self):
        expected = np.datetime64('2000-01-01', 'ns')
        for values in [
            np.datetime64('2000-01-01'),
            pd.Timestamp('2000-01-01T00'),
            datetime(2000, 1, 1),
        ]:
            v = Variable([], values)
            assert v.dtype == np.dtype('datetime64[ns]')
            assert v.values == expected
            assert v.values.dtype == np.dtype('datetime64[ns]')

    def test_timedelta64_conversion_scalar(self):
        expected = np.timedelta64(24 * 60 * 60 * 10 ** 9, 'ns')
        for values in [
            np.timedelta64(1, 'D'),
            pd.Timedelta('1 day'),
            timedelta(days=1),
        ]:
            v = Variable([], values)
            assert v.dtype == np.dtype('timedelta64[ns]')
            assert v.values == expected
            assert v.values.dtype == np.dtype('timedelta64[ns]')

    def test_0d_str(self):
        v = Variable([], u'foo')
        assert v.dtype == np.dtype('U3')
        assert v.values == 'foo'

        v = Variable([], np.string_('foo'))
        assert v.dtype == np.dtype('S3')
        assert v.values == bytes('foo', 'ascii') if PY3 else 'foo'

    def test_0d_datetime(self):
        v = Variable([], pd.Timestamp('2000-01-01'))
        assert v.dtype == np.dtype('datetime64[ns]')
        assert v.values == np.datetime64('2000-01-01', 'ns')

    def test_0d_timedelta(self):
        for td in [pd.to_timedelta('1s'), np.timedelta64(1, 's')]:
            v = Variable([], td)
            assert v.dtype == np.dtype('timedelta64[ns]')
            assert v.values == np.timedelta64(10 ** 9, 'ns')

    def test_equals_and_identical(self):
        d = np.random.rand(10, 3)
        d[0, 0] = np.nan
        v1 = Variable(('dim1', 'dim2'), data=d,
                      attrs={'att1': 3, 'att2': [1, 2, 3]})
        v2 = Variable(('dim1', 'dim2'), data=d,
                      attrs={'att1': 3, 'att2': [1, 2, 3]})
        assert v1.equals(v2)
        assert v1.identical(v2)

        v3 = Variable(('dim1', 'dim3'), data=d)
        assert not v1.equals(v3)

        v4 = Variable(('dim1', 'dim2'), data=d)
        assert v1.equals(v4)
        assert not v1.identical(v4)

        v5 = deepcopy(v1)
        v5.values[:] = np.random.rand(10, 3)
        assert not v1.equals(v5)

        assert not v1.equals(None)
        assert not v1.equals(d)

        assert not v1.identical(None)
        assert not v1.identical(d)

    def test_broadcast_equals(self):
        v1 = Variable((), np.nan)
        v2 = Variable(('x'), [np.nan, np.nan])
        assert v1.broadcast_equals(v2)
        assert not v1.equals(v2)
        assert not v1.identical(v2)

        v3 = Variable(('x'), [np.nan])
        assert v1.broadcast_equals(v3)
        assert not v1.equals(v3)
        assert not v1.identical(v3)

        assert not v1.broadcast_equals(None)

        v4 = Variable(('x'), [np.nan] * 3)
        assert not v2.broadcast_equals(v4)

    def test_no_conflicts(self):
        v1 = Variable(('x'), [1, 2, np.nan, np.nan])
        v2 = Variable(('x'), [np.nan, 2, 3, np.nan])
        assert v1.no_conflicts(v2)
        assert not v1.equals(v2)
        assert not v1.broadcast_equals(v2)
        assert not v1.identical(v2)

        assert not v1.no_conflicts(None)

        v3 = Variable(('y'), [np.nan, 2, 3, np.nan])
        assert not v3.no_conflicts(v1)

        d = np.array([1, 2, np.nan, np.nan])
        assert not v1.no_conflicts(d)
        assert not v2.no_conflicts(d)

        v4 = Variable(('w', 'x'), [d])
        assert v1.no_conflicts(v4)

    def test_as_variable(self):
        data = np.arange(10)
        expected = Variable('x', data)
        expected_extra = Variable('x', data, attrs={'myattr': 'val'},
                                  encoding={'scale_factor': 1})

        assert_identical(expected, as_variable(expected))

        ds = Dataset({'x': expected})
        var = as_variable(ds['x']).to_base_variable()
        assert_identical(expected, var)
        assert not isinstance(ds['x'], Variable)
        assert isinstance(as_variable(ds['x']), Variable)

        FakeVariable = namedtuple('FakeVariable', 'values dims')
        fake_xarray = FakeVariable(expected.values, expected.dims)
        assert_identical(expected, as_variable(fake_xarray))

        FakeVariable = namedtuple('FakeVariable', 'data dims')
        fake_xarray = FakeVariable(expected.data, expected.dims)
        assert_identical(expected, as_variable(fake_xarray))

        FakeVariable = namedtuple('FakeVariable',
                                  'data values dims attrs encoding')
        fake_xarray = FakeVariable(expected_extra.data, expected_extra.values,
                                   expected_extra.dims, expected_extra.attrs,
                                   expected_extra.encoding)
        assert_identical(expected_extra, as_variable(fake_xarray))

        xarray_tuple = (expected_extra.dims, expected_extra.values,
                        expected_extra.attrs, expected_extra.encoding)
        assert_identical(expected_extra, as_variable(xarray_tuple))

        with raises_regex(TypeError, 'tuples to convert'):
            as_variable(tuple(data))
        with raises_regex(
                TypeError, 'without an explicit list of dimensions'):
            as_variable(data)

        actual = as_variable(data, name='x')
        assert_identical(expected.to_index_variable(), actual)

        actual = as_variable(0)
        expected = Variable([], 0)
        assert_identical(expected, actual)

        data = np.arange(9).reshape((3, 3))
        expected = Variable(('x', 'y'), data)
        with raises_regex(
                ValueError, 'without explicit dimension names'):
            as_variable(data, name='x')
        with raises_regex(
                ValueError, 'has more than 1-dimension'):
            as_variable(expected, name='x')

    def test_repr(self):
        v = Variable(['time', 'x'], [[1, 2, 3], [4, 5, 6]], {'foo': 'bar'})
        expected = dedent("""
        <xarray.Variable (time: 2, x: 3)>
        array([[1, 2, 3],
               [4, 5, 6]])
        Attributes:
            foo:      bar
        """).strip()
        assert expected == repr(v)

    def test_repr_lazy_data(self):
        v = Variable('x', LazilyOuterIndexedArray(np.arange(2e5)))
        assert '200000 values with dtype' in repr(v)
        assert isinstance(v._data, LazilyOuterIndexedArray)

    def test_detect_indexer_type(self):
        """ Tests indexer type was correctly detected. """
        data = np.random.random((10, 11))
        v = Variable(['x', 'y'], data)

        _, ind, _ = v._broadcast_indexes((0, 1))
        assert type(ind) == indexing.BasicIndexer

        _, ind, _ = v._broadcast_indexes((0, slice(0, 8, 2)))
        assert type(ind) == indexing.BasicIndexer

        _, ind, _ = v._broadcast_indexes((0, [0, 1]))
        assert type(ind) == indexing.OuterIndexer

        _, ind, _ = v._broadcast_indexes(([0, 1], 1))
        assert type(ind) == indexing.OuterIndexer

        _, ind, _ = v._broadcast_indexes(([0, 1], [1, 2]))
        assert type(ind) == indexing.OuterIndexer

        _, ind, _ = v._broadcast_indexes(([0, 1], slice(0, 8, 2)))
        assert type(ind) == indexing.OuterIndexer

        vind = Variable(('a', ), [0, 1])
        _, ind, _ = v._broadcast_indexes((vind, slice(0, 8, 2)))
        assert type(ind) == indexing.OuterIndexer

        vind = Variable(('y', ), [0, 1])
        _, ind, _ = v._broadcast_indexes((vind, 3))
        assert type(ind) == indexing.OuterIndexer

        vind = Variable(('a', ), [0, 1])
        _, ind, _ = v._broadcast_indexes((vind, vind))
        assert type(ind) == indexing.VectorizedIndexer

        vind = Variable(('a', 'b'), [[0, 2], [1, 3]])
        _, ind, _ = v._broadcast_indexes((vind, 3))
        assert type(ind) == indexing.VectorizedIndexer

    def test_indexer_type(self):
        # GH:issue:1688. Wrong indexer type induces NotImplementedError
        data = np.random.random((10, 11))
        v = Variable(['x', 'y'], data)

        def assert_indexer_type(key, object_type):
            dims, index_tuple, new_order = v._broadcast_indexes(key)
            assert isinstance(index_tuple, object_type)

        # should return BasicIndexer
        assert_indexer_type((0, 1), BasicIndexer)
        assert_indexer_type((0, slice(None, None)), BasicIndexer)
        assert_indexer_type((Variable([], 3), slice(None, None)), BasicIndexer)
        assert_indexer_type((Variable([], 3), (Variable([], 6))), BasicIndexer)

        # should return OuterIndexer
        assert_indexer_type(([0, 1], 1), OuterIndexer)
        assert_indexer_type(([0, 1], [1, 2]), OuterIndexer)
        assert_indexer_type((Variable(('x'), [0, 1]), 1), OuterIndexer)
        assert_indexer_type((Variable(('x'), [0, 1]), slice(None, None)),
                            OuterIndexer)
        assert_indexer_type((Variable(('x'), [0, 1]), Variable(('y'), [0, 1])),
                            OuterIndexer)

        # should return VectorizedIndexer
        assert_indexer_type((Variable(('y'), [0, 1]), [0, 1]),
                            VectorizedIndexer)
        assert_indexer_type((Variable(('z'), [0, 1]), Variable(('z'), [0, 1])),
                            VectorizedIndexer)
        assert_indexer_type((Variable(('a', 'b'), [[0, 1], [1, 2]]),
                             Variable(('a', 'b'), [[0, 1], [1, 2]])),
                            VectorizedIndexer)

    def test_items(self):
        data = np.random.random((10, 11))
        v = Variable(['x', 'y'], data)
        # test slicing
        assert_identical(v, v[:])
        assert_identical(v, v[...])
        assert_identical(Variable(['y'], data[0]), v[0])
        assert_identical(Variable(['x'], data[:, 0]), v[:, 0])
        assert_identical(Variable(['x', 'y'], data[:3, :2]),
                         v[:3, :2])
        # test array indexing
        x = Variable(['x'], np.arange(10))
        y = Variable(['y'], np.arange(11))
        assert_identical(v, v[x.values])
        assert_identical(v, v[x])
        assert_identical(v[:3], v[x < 3])
        assert_identical(v[:, 3:], v[:, y >= 3])
        assert_identical(v[:3, 3:], v[x < 3, y >= 3])
        assert_identical(v[:3, :2], v[x[:3], y[:2]])
        assert_identical(v[:3, :2], v[range(3), range(2)])
        # test iteration
        for n, item in enumerate(v):
            assert_identical(Variable(['y'], data[n]), item)
        with raises_regex(TypeError, 'iteration over a 0-d'):
            iter(Variable([], 0))
        # test setting
        v.values[:] = 0
        assert np.all(v.values == 0)
        # test orthogonal setting
        v[range(10), range(11)] = 1
        assert_array_equal(v.values, np.ones((10, 11)))

    def test_getitem_basic(self):
        v = self.cls(['x', 'y'], [[0, 1, 2], [3, 4, 5]])

        v_new = v[dict(x=0)]
        assert v_new.dims == ('y', )
        assert_array_equal(v_new, v._data[0])

        v_new = v[dict(x=0, y=slice(None))]
        assert v_new.dims == ('y', )
        assert_array_equal(v_new, v._data[0])

        v_new = v[dict(x=0, y=1)]
        assert v_new.dims == ()
        assert_array_equal(v_new, v._data[0, 1])

        v_new = v[dict(y=1)]
        assert v_new.dims == ('x', )
        assert_array_equal(v_new, v._data[:, 1])

        # tuple argument
        v_new = v[(slice(None), 1)]
        assert v_new.dims == ('x', )
        assert_array_equal(v_new, v._data[:, 1])

    def test_getitem_with_mask_2d_input(self):
        v = Variable(('x', 'y'), [[0, 1, 2], [3, 4, 5]])
        assert_identical(v._getitem_with_mask(([-1, 0], [1, -1])),
                         Variable(('x', 'y'), [[np.nan, np.nan], [1, np.nan]]))
        assert_identical(v._getitem_with_mask((slice(2), [0, 1, 2])), v)

    def test_isel(self):
        v = Variable(['time', 'x'], self.d)
        assert_identical(v.isel(time=slice(None)), v)
        assert_identical(v.isel(time=0), v[0])
        assert_identical(v.isel(time=slice(0, 3)), v[:3])
        assert_identical(v.isel(x=0), v[:, 0])
        with raises_regex(ValueError, 'do not exist'):
            v.isel(not_a_dim=0)

    def test_index_0d_numpy_string(self):
        # regression test to verify our work around for indexing 0d strings
        v = Variable([], np.string_('asdf'))
        assert_identical(v[()], v)

        v = Variable([], np.unicode_(u'asdf'))
        assert_identical(v[()], v)

    def test_indexing_0d_unicode(self):
        # regression test for GH568
        actual = Variable(('x'), [u'tmax'])[0][()]
        expected = Variable((), u'tmax')
        assert_identical(actual, expected)

    def test_shift(self):
        v = Variable('x', [1, 2, 3, 4, 5])

        assert_identical(v, v.shift(x=0))
        assert v is not v.shift(x=0)

        expected = Variable('x', [np.nan, 1, 2, 3, 4])
        assert_identical(expected, v.shift(x=1))

        expected = Variable('x', [np.nan, np.nan, 1, 2, 3])
        assert_identical(expected, v.shift(x=2))

        expected = Variable('x', [2, 3, 4, 5, np.nan])
        assert_identical(expected, v.shift(x=-1))

        expected = Variable('x', [np.nan] * 5)
        assert_identical(expected, v.shift(x=5))
        assert_identical(expected, v.shift(x=6))

        with raises_regex(ValueError, 'dimension'):
            v.shift(z=0)

        v = Variable('x', [1, 2, 3, 4, 5], {'foo': 'bar'})
        assert_identical(v, v.shift(x=0))

        expected = Variable('x', [np.nan, 1, 2, 3, 4], {'foo': 'bar'})
        assert_identical(expected, v.shift(x=1))

    def test_shift2d(self):
        v = Variable(('x', 'y'), [[1, 2], [3, 4]])
        expected = Variable(('x', 'y'), [[np.nan, np.nan], [np.nan, 1]])
        assert_identical(expected, v.shift(x=1, y=1))

    def test_roll(self):
        v = Variable('x', [1, 2, 3, 4, 5])

        assert_identical(v, v.roll(x=0))
        assert v is not v.roll(x=0)

        expected = Variable('x', [5, 1, 2, 3, 4])
        assert_identical(expected, v.roll(x=1))
        assert_identical(expected, v.roll(x=-4))
        assert_identical(expected, v.roll(x=6))

        expected = Variable('x', [4, 5, 1, 2, 3])
        assert_identical(expected, v.roll(x=2))
        assert_identical(expected, v.roll(x=-3))

        with raises_regex(ValueError, 'dimension'):
            v.roll(z=0)

    def test_roll_consistency(self):
        v = Variable(('x', 'y'), np.random.randn(5, 6))

        for axis, dim in [(0, 'x'), (1, 'y')]:
            for shift in [-3, 0, 1, 7, 11]:
                expected = np.roll(v.values, shift, axis=axis)
                actual = v.roll(**{dim: shift}).values
                assert_array_equal(expected, actual)

    def test_transpose(self):
        v = Variable(['time', 'x'], self.d)
        v2 = Variable(['x', 'time'], self.d.T)
        assert_identical(v, v2.transpose())
        assert_identical(v.transpose(), v.T)
        x = np.random.randn(2, 3, 4, 5)
        w = Variable(['a', 'b', 'c', 'd'], x)
        w2 = Variable(['d', 'b', 'c', 'a'], np.einsum('abcd->dbca', x))
        assert w2.shape == (5, 3, 4, 2)
        assert_identical(w2, w.transpose('d', 'b', 'c', 'a'))
        assert_identical(w, w2.transpose('a', 'b', 'c', 'd'))
        w3 = Variable(['b', 'c', 'd', 'a'], np.einsum('abcd->bcda', x))
        assert_identical(w, w3.transpose('a', 'b', 'c', 'd'))

    def test_transpose_0d(self):
        for value in [
                3.5,
                ('a', 1),
                np.datetime64('2000-01-01'),
                np.timedelta64(1, 'h'),
                None,
                object(),
        ]:
            variable = Variable([], value)
            actual = variable.transpose()
            assert actual.identical(variable)

    def test_squeeze(self):
        v = Variable(['x', 'y'], [[1]])
        assert_identical(Variable([], 1), v.squeeze())
        assert_identical(Variable(['y'], [1]), v.squeeze('x'))
        assert_identical(Variable(['y'], [1]), v.squeeze(['x']))
        assert_identical(Variable(['x'], [1]), v.squeeze('y'))
        assert_identical(Variable([], 1), v.squeeze(['x', 'y']))

        v = Variable(['x', 'y'], [[1, 2]])
        assert_identical(Variable(['y'], [1, 2]), v.squeeze())
        assert_identical(Variable(['y'], [1, 2]), v.squeeze('x'))
        with raises_regex(ValueError, 'cannot select a dimension'):
            v.squeeze('y')

    def test_get_axis_num(self):
        v = Variable(['x', 'y', 'z'], np.random.randn(2, 3, 4))
        assert v.get_axis_num('x') == 0
        assert v.get_axis_num(['x']) == (0,)
        assert v.get_axis_num(['x', 'y']) == (0, 1)
        assert v.get_axis_num(['z', 'y', 'x']) == (2, 1, 0)
        with raises_regex(ValueError, 'not found in array dim'):
            v.get_axis_num('foobar')

    def test_set_dims(self):
        v = Variable(['x'], [0, 1])
        actual = v.set_dims(['x', 'y'])
        expected = Variable(['x', 'y'], [[0], [1]])
        assert_identical(actual, expected)

        actual = v.set_dims(['y', 'x'])
        assert_identical(actual, expected.T)

        actual = v.set_dims(OrderedDict([('x', 2), ('y', 2)]))
        expected = Variable(['x', 'y'], [[0, 0], [1, 1]])
        assert_identical(actual, expected)

        v = Variable(['foo'], [0, 1])
        actual = v.set_dims('foo')
        expected = v
        assert_identical(actual, expected)

        with raises_regex(ValueError, 'must be a superset'):
            v.set_dims(['z'])

    def test_set_dims_object_dtype(self):
        v = Variable([], ('a', 1))
        actual = v.set_dims(('x',), (3,))
        exp_values = np.empty((3,), dtype=object)
        for i in range(3):
            exp_values[i] = ('a', 1)
        expected = Variable(['x'], exp_values)
        assert actual.identical(expected)

    def test_stack(self):
        v = Variable(['x', 'y'], [[0, 1], [2, 3]], {'foo': 'bar'})
        actual = v.stack(z=('x', 'y'))
        expected = Variable('z', [0, 1, 2, 3], v.attrs)
        assert_identical(actual, expected)

        actual = v.stack(z=('x',))
        expected = Variable(('y', 'z'), v.data.T, v.attrs)
        assert_identical(actual, expected)

        actual = v.stack(z=(),)
        assert_identical(actual, v)

        actual = v.stack(X=('x',), Y=('y',)).transpose('X', 'Y')
        expected = Variable(('X', 'Y'), v.data, v.attrs)
        assert_identical(actual, expected)

    def test_stack_errors(self):
        v = Variable(['x', 'y'], [[0, 1], [2, 3]], {'foo': 'bar'})

        with raises_regex(ValueError, 'invalid existing dim'):
            v.stack(z=('x1',))
        with raises_regex(ValueError, 'cannot create a new dim'):
            v.stack(x=('x',))

    def test_unstack(self):
        v = Variable('z', [0, 1, 2, 3], {'foo': 'bar'})
        actual = v.unstack(z=OrderedDict([('x', 2), ('y', 2)]))
        expected = Variable(('x', 'y'), [[0, 1], [2, 3]], v.attrs)
        assert_identical(actual, expected)

        actual = v.unstack(z=OrderedDict([('x', 4), ('y', 1)]))
        expected = Variable(('x', 'y'), [[0], [1], [2], [3]], v.attrs)
        assert_identical(actual, expected)

        actual = v.unstack(z=OrderedDict([('x', 4)]))
        expected = Variable('x', [0, 1, 2, 3], v.attrs)
        assert_identical(actual, expected)

    def test_unstack_errors(self):
        v = Variable('z', [0, 1, 2, 3])
        with raises_regex(ValueError, 'invalid existing dim'):
            v.unstack(foo={'x': 4})
        with raises_regex(ValueError, 'cannot create a new dim'):
            v.stack(z=('z',))
        with raises_regex(ValueError, 'the product of the new dim'):
            v.unstack(z={'x': 5})

    def test_unstack_2d(self):
        v = Variable(['x', 'y'], [[0, 1], [2, 3]])
        actual = v.unstack(y={'z': 2})
        expected = Variable(['x', 'z'], v.data)
        assert_identical(actual, expected)

        actual = v.unstack(x={'z': 2})
        expected = Variable(['y', 'z'], v.data.T)
        assert_identical(actual, expected)

    def test_stack_unstack_consistency(self):
        v = Variable(['x', 'y'], [[0, 1], [2, 3]])
        actual = (v.stack(z=('x', 'y'))
                  .unstack(z=OrderedDict([('x', 2), ('y', 2)])))
        assert_identical(actual, v)

    def test_broadcasting_math(self):
        x = np.random.randn(2, 3)
        v = Variable(['a', 'b'], x)
        # 1d to 2d broadcasting
        assert_identical(
            v * v,
            Variable(['a', 'b'], np.einsum('ab,ab->ab', x, x)))
        assert_identical(
            v * v[0],
            Variable(['a', 'b'], np.einsum('ab,b->ab', x, x[0])))
        assert_identical(
            v[0] * v,
            Variable(['b', 'a'], np.einsum('b,ab->ba', x[0], x)))
        assert_identical(
            v[0] * v[:, 0],
            Variable(['b', 'a'], np.einsum('b,a->ba', x[0], x[:, 0])))
        # higher dim broadcasting
        y = np.random.randn(3, 4, 5)
        w = Variable(['b', 'c', 'd'], y)
        assert_identical(
            v * w, Variable(['a', 'b', 'c', 'd'],
                            np.einsum('ab,bcd->abcd', x, y)))
        assert_identical(
            w * v, Variable(['b', 'c', 'd', 'a'],
                            np.einsum('bcd,ab->bcda', y, x)))
        assert_identical(
            v * w[0], Variable(['a', 'b', 'c', 'd'],
                               np.einsum('ab,cd->abcd', x, y[0])))

    def test_broadcasting_failures(self):
        a = Variable(['x'], np.arange(10))
        b = Variable(['x'], np.arange(5))
        c = Variable(['x', 'x'], np.arange(100).reshape(10, 10))
        with raises_regex(ValueError, 'mismatched lengths'):
            a + b
        with raises_regex(ValueError, 'duplicate dimensions'):
            a + c

    def test_inplace_math(self):
        x = np.arange(5)
        v = Variable(['x'], x)
        v2 = v
        v2 += 1
        assert v is v2
        # since we provided an ndarray for data, it is also modified in-place
        assert source_ndarray(v.values) is x
        assert_array_equal(v.values, np.arange(5) + 1)

        with raises_regex(ValueError, 'dimensions cannot change'):
            v += Variable('y', np.arange(5))

    def test_reduce(self):
        v = Variable(['x', 'y'], self.d, {'ignored': 'attributes'})
        assert_identical(v.reduce(np.std, 'x'),
                         Variable(['y'], self.d.std(axis=0)))
        assert_identical(v.reduce(np.std, axis=0),
                         v.reduce(np.std, dim='x'))
        assert_identical(v.reduce(np.std, ['y', 'x']),
                         Variable([], self.d.std(axis=(0, 1))))
        assert_identical(v.reduce(np.std),
                         Variable([], self.d.std()))
        assert_identical(
            v.reduce(np.mean, 'x').reduce(np.std, 'y'),
            Variable([], self.d.mean(axis=0).std()))
        assert_allclose(v.mean('x'), v.reduce(np.mean, 'x'))

        with raises_regex(ValueError, 'cannot supply both'):
            v.mean(dim='x', axis=0)

    @pytest.mark.skipif(LooseVersion(np.__version__) < LooseVersion('1.10.0'),
                        reason='requires numpy version 1.10.0 or later')
    def test_quantile(self):
        v = Variable(['x', 'y'], self.d)
        for q in [0.25, [0.50], [0.25, 0.75]]:
            for axis, dim in zip([None, 0, [0], [0, 1]],
                                 [None, 'x', ['x'], ['x', 'y']]):
                actual = v.quantile(q, dim=dim)

                expected = np.nanpercentile(self.d, np.array(q) * 100,
                                            axis=axis)
                np.testing.assert_allclose(actual.values, expected)

    @requires_dask
    def test_quantile_dask_raises(self):
        # regression for GH1524
        v = Variable(['x', 'y'], self.d).chunk(2)

        with raises_regex(TypeError, 'arrays stored as dask'):
            v.quantile(0.5, dim='x')

    @requires_dask
    @requires_bottleneck
    def test_rank_dask_raises(self):
        v = Variable(['x'], [3.0, 1.0, np.nan, 2.0, 4.0]).chunk(2)
        with raises_regex(TypeError, 'arrays stored as dask'):
            v.rank('x')

    @requires_bottleneck
    def test_rank(self):
        import bottleneck as bn
        # floats
        v = Variable(['x', 'y'], [[3, 4, np.nan, 1]])
        expect_0 = bn.nanrankdata(v.data, axis=0)
        expect_1 = bn.nanrankdata(v.data, axis=1)
        np.testing.assert_allclose(v.rank('x').values, expect_0)
        np.testing.assert_allclose(v.rank('y').values, expect_1)
        # int
        v = Variable(['x'], [3, 2, 1])
        expect = bn.rankdata(v.data, axis=0)
        np.testing.assert_allclose(v.rank('x').values, expect)
        # str
        v = Variable(['x'], ['c', 'b', 'a'])
        expect = bn.rankdata(v.data, axis=0)
        np.testing.assert_allclose(v.rank('x').values, expect)
        # pct
        v = Variable(['x'], [3.0, 1.0, np.nan, 2.0, 4.0])
        v_expect = Variable(['x'], [0.75, 0.25, np.nan, 0.5, 1.0])
        assert_equal(v.rank('x', pct=True), v_expect)
        # invalid dim
        with raises_regex(ValueError, 'not found'):
            v.rank('y')

    def test_big_endian_reduce(self):
        # regression test for GH489
        data = np.ones(5, dtype='>f4')
        v = Variable(['x'], data)
        expected = Variable([], 5)
        assert_identical(expected, v.sum())

    def test_reduce_funcs(self):
        v = Variable('x', np.array([1, np.nan, 2, 3]))
        assert_identical(v.mean(), Variable([], 2))
        assert_identical(v.mean(skipna=True), Variable([], 2))
        assert_identical(v.mean(skipna=False), Variable([], np.nan))
        assert_identical(np.mean(v), Variable([], 2))

        assert_identical(v.prod(), Variable([], 6))
        assert_identical(v.cumsum(axis=0),
                         Variable('x', np.array([1, 1, 3, 6])))
        assert_identical(v.cumprod(axis=0),
                         Variable('x', np.array([1, 1, 2, 6])))
        assert_identical(v.var(), Variable([], 2.0 / 3))

        if LooseVersion(np.__version__) < '1.9':
            with pytest.raises(NotImplementedError):
                v.median()
        else:
            assert_identical(v.median(), Variable([], 2))

        v = Variable('x', [True, False, False])
        assert_identical(v.any(), Variable([], True))
        assert_identical(v.all(dim='x'), Variable([], False))

        v = Variable('t', pd.date_range('2000-01-01', periods=3))
        with pytest.raises(NotImplementedError):
            v.argmax(skipna=True)
        assert_identical(
            v.max(), Variable([], pd.Timestamp('2000-01-03')))

    def test_reduce_keep_attrs(self):
        _attrs = {'units': 'test', 'long_name': 'testing'}

        v = Variable(['x', 'y'], self.d, _attrs)

        # Test dropped attrs
        vm = v.mean()
        assert len(vm.attrs) == 0
        assert vm.attrs == OrderedDict()

        # Test kept attrs
        vm = v.mean(keep_attrs=True)
        assert len(vm.attrs) == len(_attrs)
        assert vm.attrs == _attrs

    def test_count(self):
        expected = Variable([], 3)
        actual = Variable(['x'], [1, 2, 3, np.nan]).count()
        assert_identical(expected, actual)

        v = Variable(['x'], np.array(['1', '2', '3', np.nan], dtype=object))
        actual = v.count()
        assert_identical(expected, actual)

        actual = Variable(['x'], [True, False, True]).count()
        assert_identical(expected, actual)
        assert actual.dtype == int

        expected = Variable(['x'], [2, 3])
        actual = Variable(['x', 'y'], [[1, 0, np.nan], [1, 1, 1]]).count('y')
        assert_identical(expected, actual)

    def test_setitem(self):
        v = Variable(['x', 'y'], [[0, 3, 2], [3, 4, 5]])
        v[0, 1] = 1
        assert v[0, 1] == 1

        v = Variable(['x', 'y'], [[0, 3, 2], [3, 4, 5]])
        v[dict(x=[0, 1])] = 1
        assert_array_equal(v[[0, 1]], np.ones_like(v[[0, 1]]))

        # boolean indexing
        v = Variable(['x', 'y'], [[0, 3, 2], [3, 4, 5]])
        v[dict(x=[True, False])] = 1

        assert_array_equal(v[0], np.ones_like(v[0]))
        v = Variable(['x', 'y'], [[0, 3, 2], [3, 4, 5]])
        v[dict(x=[True, False], y=[False, True, False])] = 1
        assert v[0, 1] == 1

    def test_setitem_fancy(self):
        # assignment which should work as np.ndarray does
        def assert_assigned_2d(array, key_x, key_y, values):
            expected = array.copy()
            expected[key_x, key_y] = values
            v = Variable(['x', 'y'], array)
            v[dict(x=key_x, y=key_y)] = values
            assert_array_equal(expected, v)

        # 1d vectorized indexing
        assert_assigned_2d(np.random.randn(4, 3),
                           key_x=Variable(['a'], [0, 1]),
                           key_y=Variable(['a'], [0, 1]),
                           values=0)
        assert_assigned_2d(np.random.randn(4, 3),
                           key_x=Variable(['a'], [0, 1]),
                           key_y=Variable(['a'], [0, 1]),
                           values=Variable((), 0))
        assert_assigned_2d(np.random.randn(4, 3),
                           key_x=Variable(['a'], [0, 1]),
                           key_y=Variable(['a'], [0, 1]),
                           values=Variable(('a'), [3, 2]))
        assert_assigned_2d(np.random.randn(4, 3),
                           key_x=slice(None),
                           key_y=Variable(['a'], [0, 1]),
                           values=Variable(('a'), [3, 2]))

        # 2d-vectorized indexing
        assert_assigned_2d(np.random.randn(4, 3),
                           key_x=Variable(['a', 'b'], [[0, 1]]),
                           key_y=Variable(['a', 'b'], [[1, 0]]),
                           values=0)
        assert_assigned_2d(np.random.randn(4, 3),
                           key_x=Variable(['a', 'b'], [[0, 1]]),
                           key_y=Variable(['a', 'b'], [[1, 0]]),
                           values=[0])
        assert_assigned_2d(np.random.randn(5, 4),
                           key_x=Variable(['a', 'b'], [[0, 1], [2, 3]]),
                           key_y=Variable(['a', 'b'], [[1, 0], [3, 3]]),
                           values=[2, 3])

        # vindex with slice
        v = Variable(['x', 'y', 'z'], np.ones((4, 3, 2)))
        ind = Variable(['a'], [0, 1])
        v[dict(x=ind, z=ind)] = 0
        expected = Variable(['x', 'y', 'z'], np.ones((4, 3, 2)))
        expected[0, :, 0] = 0
        expected[1, :, 1] = 0
        assert_identical(expected, v)

        # dimension broadcast
        v = Variable(['x', 'y'], np.ones((3, 2)))
        ind = Variable(['a', 'b'], [[0, 1]])
        v[ind, :] = 0
        expected = Variable(['x', 'y'], [[0, 0], [0, 0], [1, 1]])
        assert_identical(expected, v)

        with raises_regex(ValueError, "shape mismatch"):
            v[ind, ind] = np.zeros((1, 2, 1))

        v = Variable(['x', 'y'], [[0, 3, 2], [3, 4, 5]])
        ind = Variable(['a'], [0, 1])
        v[dict(x=ind)] = Variable(['a', 'y'], np.ones((2, 3), dtype=int) * 10)
        assert_array_equal(v[0], np.ones_like(v[0]) * 10)
        assert_array_equal(v[1], np.ones_like(v[1]) * 10)
        assert v.dims == ('x', 'y')  # dimension should not change

        # increment
        v = Variable(['x', 'y'], np.arange(6).reshape(3, 2))
        ind = Variable(['a'], [0, 1])
        v[dict(x=ind)] += 1
        expected = Variable(['x', 'y'], [[1, 2], [3, 4], [4, 5]])
        assert_identical(v, expected)

        ind = Variable(['a'], [0, 0])
        v[dict(x=ind)] += 1
        expected = Variable(['x', 'y'], [[2, 3], [3, 4], [4, 5]])
        assert_identical(v, expected)


@requires_dask
class TestVariableWithDask(TestCase, VariableSubclassTestCases):
    cls = staticmethod(lambda *args: Variable(*args).chunk())

    @pytest.mark.xfail
    def test_0d_object_array_with_list(self):
        super(TestVariableWithDask, self).test_0d_object_array_with_list()

    @pytest.mark.xfail
    def test_array_interface(self):
        # dask array does not have `argsort`
        super(TestVariableWithDask, self).test_array_interface()

    @pytest.mark.xfail
    def test_copy_index(self):
        super(TestVariableWithDask, self).test_copy_index()

    @pytest.mark.xfail
    def test_eq_all_dtypes(self):
        super(TestVariableWithDask, self).test_eq_all_dtypes()

    def test_getitem_fancy(self):
        import dask
        if LooseVersion(dask.__version__) <= LooseVersion('0.15.1'):
            pytest.xfail("vindex from latest dask is required")
        super(TestVariableWithDask, self).test_getitem_fancy()

    def test_getitem_1d_fancy(self):
        import dask
        if LooseVersion(dask.__version__) <= LooseVersion('0.15.1'):
            pytest.xfail("vindex from latest dask is required")
        super(TestVariableWithDask, self).test_getitem_1d_fancy()

    def test_getitem_with_mask_nd_indexer(self):
        import dask.array as da
        v = Variable(['x'], da.arange(3, chunks=3))
        indexer = Variable(('x', 'y'), [[0, -1], [-1, 2]])
        assert_identical(v._getitem_with_mask(indexer, fill_value=-1),
                         self.cls(('x', 'y'), [[0, -1], [-1, 2]]))


class TestIndexVariable(TestCase, VariableSubclassTestCases):
    cls = staticmethod(IndexVariable)

    def test_init(self):
        with raises_regex(ValueError, 'must be 1-dimensional'):
            IndexVariable((), 0)

    def test_to_index(self):
        data = 0.5 * np.arange(10)
        v = IndexVariable(['time'], data, {'foo': 'bar'})
        assert pd.Index(data, name='time').identical(v.to_index())

    def test_multiindex_default_level_names(self):
        midx = pd.MultiIndex.from_product([['a', 'b'], [1, 2]])
        v = IndexVariable(['x'], midx, {'foo': 'bar'})
        assert v.to_index().names == ('x_level_0', 'x_level_1')

    def test_data(self):
        x = IndexVariable('x', np.arange(3.0))
        assert isinstance(x._data, PandasIndexAdapter)
        assert isinstance(x.data, np.ndarray)
        assert float == x.dtype
        assert_array_equal(np.arange(3), x)
        assert float == x.values.dtype
        with raises_regex(TypeError, 'cannot be modified'):
            x[:] = 0

    def test_name(self):
        coord = IndexVariable('x', [10.0])
        assert coord.name == 'x'

        with pytest.raises(AttributeError):
            coord.name = 'y'

    def test_level_names(self):
        midx = pd.MultiIndex.from_product([['a', 'b'], [1, 2]],
                                          names=['level_1', 'level_2'])
        x = IndexVariable('x', midx)
        assert x.level_names == midx.names

        assert IndexVariable('y', [10.0]).level_names is None

    def test_get_level_variable(self):
        midx = pd.MultiIndex.from_product([['a', 'b'], [1, 2]],
                                          names=['level_1', 'level_2'])
        x = IndexVariable('x', midx)
        level_1 = IndexVariable('x', midx.get_level_values('level_1'))
        assert_identical(x.get_level_variable('level_1'), level_1)

        with raises_regex(ValueError, 'has no MultiIndex'):
            IndexVariable('y', [10.0]).get_level_variable('level')

    def test_concat_periods(self):
        periods = pd.period_range('2000-01-01', periods=10)
        coords = [IndexVariable('t', periods[:5]),
                  IndexVariable('t', periods[5:])]
        expected = IndexVariable('t', periods)
        actual = IndexVariable.concat(coords, dim='t')
        assert actual.identical(expected)
        assert isinstance(actual.to_index(), pd.PeriodIndex)

        positions = [list(range(5)), list(range(5, 10))]
        actual = IndexVariable.concat(coords, dim='t', positions=positions)
        assert actual.identical(expected)
        assert isinstance(actual.to_index(), pd.PeriodIndex)

    def test_concat_multiindex(self):
        idx = pd.MultiIndex.from_product([[0, 1, 2], ['a', 'b']])
        coords = [IndexVariable('x', idx[:2]), IndexVariable('x', idx[2:])]
        expected = IndexVariable('x', idx)
        actual = IndexVariable.concat(coords, dim='x')
        assert actual.identical(expected)
        assert isinstance(actual.to_index(), pd.MultiIndex)

    def test_coordinate_alias(self):
        with pytest.warns(Warning, match='deprecated'):
            x = Coordinate('x', [1, 2, 3])
        assert isinstance(x, IndexVariable)

    def test_datetime64(self):
        # GH:1932  Make sure indexing keeps precision
        t = np.array([1518418799999986560, 1518418799999996560],
                     dtype='datetime64[ns]')
        v = IndexVariable('t', t)
        assert v[0].data == t[0]

    # These tests make use of multi-dimensional variables, which are not valid
    # IndexVariable objects:
    @pytest.mark.xfail
    def test_getitem_error(self):
        super(TestIndexVariable, self).test_getitem_error()

    @pytest.mark.xfail
    def test_getitem_advanced(self):
        super(TestIndexVariable, self).test_getitem_advanced()

    @pytest.mark.xfail
    def test_getitem_fancy(self):
        super(TestIndexVariable, self).test_getitem_fancy()

    @pytest.mark.xfail
    def test_getitem_uint(self):
        super(TestIndexVariable, self).test_getitem_fancy()

    @pytest.mark.xfail
    def test_pad(self):
        super(TestIndexVariable, self).test_rolling_window()

    @pytest.mark.xfail
    def test_rolling_window(self):
        super(TestIndexVariable, self).test_rolling_window()


class TestAsCompatibleData(TestCase):
    def test_unchanged_types(self):
        types = (np.asarray, PandasIndexAdapter, LazilyOuterIndexedArray)
        for t in types:
            for data in [np.arange(3),
                         pd.date_range('2000-01-01', periods=3),
                         pd.date_range('2000-01-01', periods=3).values]:
                x = t(data)
                assert source_ndarray(x) is \
                    source_ndarray(as_compatible_data(x))

    def test_converted_types(self):
        for input_array in [[[0, 1, 2]], pd.DataFrame([[0, 1, 2]])]:
            actual = as_compatible_data(input_array)
            assert_array_equal(np.asarray(input_array), actual)
            assert np.ndarray == type(actual)
            assert np.asarray(input_array).dtype == actual.dtype

    def test_masked_array(self):
        original = np.ma.MaskedArray(np.arange(5))
        expected = np.arange(5)
        actual = as_compatible_data(original)
        assert_array_equal(expected, actual)
        assert np.dtype(int) == actual.dtype

        original = np.ma.MaskedArray(np.arange(5), mask=4 * [False] + [True])
        expected = np.arange(5.0)
        expected[-1] = np.nan
        actual = as_compatible_data(original)
        assert_array_equal(expected, actual)
        assert np.dtype(float) == actual.dtype

    def test_datetime(self):
        expected = np.datetime64('2000-01-01')
        actual = as_compatible_data(expected)
        assert expected == actual
        assert np.ndarray == type(actual)
        assert np.dtype('datetime64[ns]') == actual.dtype

        expected = np.array([np.datetime64('2000-01-01')])
        actual = as_compatible_data(expected)
        assert np.asarray(expected) == actual
        assert np.ndarray == type(actual)
        assert np.dtype('datetime64[ns]') == actual.dtype

        expected = np.array([np.datetime64('2000-01-01', 'ns')])
        actual = as_compatible_data(expected)
        assert np.asarray(expected) == actual
        assert np.ndarray == type(actual)
        assert np.dtype('datetime64[ns]') == actual.dtype
        assert expected is source_ndarray(np.asarray(actual))

        expected = np.datetime64('2000-01-01', 'ns')
        actual = as_compatible_data(datetime(2000, 1, 1))
        assert np.asarray(expected) == actual
        assert np.ndarray == type(actual)
        assert np.dtype('datetime64[ns]') == actual.dtype

    def test_full_like(self):
        # For more thorough tests, see test_variable.py
        orig = Variable(dims=('x', 'y'), data=[[1.5, 2.0], [3.1, 4.3]],
                        attrs={'foo': 'bar'})

        expect = orig.copy(deep=True)
        expect.values = [[2.0, 2.0], [2.0, 2.0]]
        assert_identical(expect, full_like(orig, 2))

        # override dtype
        expect.values = [[True, True], [True, True]]
        assert expect.dtype == bool
        assert_identical(expect, full_like(orig, True, dtype=bool))

    @requires_dask
    def test_full_like_dask(self):
        orig = Variable(dims=('x', 'y'), data=[[1.5, 2.0], [3.1, 4.3]],
                        attrs={'foo': 'bar'}).chunk(((1, 1), (2,)))

        def check(actual, expect_dtype, expect_values):
            assert actual.dtype == expect_dtype
            assert actual.shape == orig.shape
            assert actual.dims == orig.dims
            assert actual.attrs == orig.attrs
            assert actual.chunks == orig.chunks
            assert_array_equal(actual.values, expect_values)

        check(full_like(orig, 2),
              orig.dtype, np.full_like(orig.values, 2))
        # override dtype
        check(full_like(orig, True, dtype=bool),
              bool, np.full_like(orig.values, True, dtype=bool))

        # Check that there's no array stored inside dask
        # (e.g. we didn't create a numpy array and then we chunked it!)
        dsk = full_like(orig, 1).data.dask
        for v in dsk.values():
            if isinstance(v, tuple):
                for vi in v:
                    assert not isinstance(vi, np.ndarray)
            else:
                assert not isinstance(v, np.ndarray)

    def test_zeros_like(self):
        orig = Variable(dims=('x', 'y'), data=[[1.5, 2.0], [3.1, 4.3]],
                        attrs={'foo': 'bar'})
        assert_identical(zeros_like(orig),
                         full_like(orig, 0))
        assert_identical(zeros_like(orig, dtype=int),
                         full_like(orig, 0, dtype=int))

    def test_ones_like(self):
        orig = Variable(dims=('x', 'y'), data=[[1.5, 2.0], [3.1, 4.3]],
                        attrs={'foo': 'bar'})
        assert_identical(ones_like(orig),
                         full_like(orig, 1))
        assert_identical(ones_like(orig, dtype=int),
                         full_like(orig, 1, dtype=int))

    def test_unsupported_type(self):
        # Non indexable type
        class CustomArray(NDArrayMixin):
            def __init__(self, array):
                self.array = array

        class CustomIndexable(CustomArray, indexing.ExplicitlyIndexed):
            pass

        array = CustomArray(np.arange(3))
        orig = Variable(dims=('x'), data=array, attrs={'foo': 'bar'})
        assert isinstance(orig._data, np.ndarray)  # should not be CustomArray

        array = CustomIndexable(np.arange(3))
        orig = Variable(dims=('x'), data=array, attrs={'foo': 'bar'})
        assert isinstance(orig._data, CustomIndexable)


def test_raise_no_warning_for_nan_in_binary_ops():
    with pytest.warns(None) as record:
        Variable('x', [1, 2, np.NaN]) > 0
    assert len(record) == 0


class TestBackendIndexing(TestCase):
    """    Make sure all the array wrappers can be indexed. """

    def setUp(self):
        self.d = np.random.random((10, 3)).astype(np.float64)

    def check_orthogonal_indexing(self, v):
        assert np.allclose(v.isel(x=[8, 3], y=[2, 1]),
                           self.d[[8, 3]][:, [2, 1]])

    def check_vectorized_indexing(self, v):
        ind_x = Variable('z', [0, 2])
        ind_y = Variable('z', [2, 1])
        assert np.allclose(v.isel(x=ind_x, y=ind_y), self.d[ind_x, ind_y])

    def test_NumpyIndexingAdapter(self):
        v = Variable(dims=('x', 'y'), data=NumpyIndexingAdapter(self.d))
        self.check_orthogonal_indexing(v)
        self.check_vectorized_indexing(v)
        # could not doubly wrapping
        with raises_regex(TypeError, 'NumpyIndexingAdapter only wraps '):
            v = Variable(dims=('x', 'y'), data=NumpyIndexingAdapter(
                NumpyIndexingAdapter(self.d)))

    def test_LazilyOuterIndexedArray(self):
        v = Variable(dims=('x', 'y'), data=LazilyOuterIndexedArray(self.d))
        self.check_orthogonal_indexing(v)
        self.check_vectorized_indexing(v)
        # doubly wrapping
        v = Variable(
            dims=('x', 'y'),
            data=LazilyOuterIndexedArray(LazilyOuterIndexedArray(self.d)))
        self.check_orthogonal_indexing(v)
        # hierarchical wrapping
        v = Variable(
            dims=('x', 'y'),
            data=LazilyOuterIndexedArray(NumpyIndexingAdapter(self.d)))
        self.check_orthogonal_indexing(v)

    def test_CopyOnWriteArray(self):
        v = Variable(dims=('x', 'y'), data=CopyOnWriteArray(self.d))
        self.check_orthogonal_indexing(v)
        self.check_vectorized_indexing(v)
        # doubly wrapping
        v = Variable(
            dims=('x', 'y'),
            data=CopyOnWriteArray(LazilyOuterIndexedArray(self.d)))
        self.check_orthogonal_indexing(v)
        self.check_vectorized_indexing(v)

    def test_MemoryCachedArray(self):
        v = Variable(dims=('x', 'y'), data=MemoryCachedArray(self.d))
        self.check_orthogonal_indexing(v)
        self.check_vectorized_indexing(v)
        # doubly wrapping
        v = Variable(dims=('x', 'y'),
                     data=CopyOnWriteArray(MemoryCachedArray(self.d)))
        self.check_orthogonal_indexing(v)
        self.check_vectorized_indexing(v)

    @requires_dask
    def test_DaskIndexingAdapter(self):
        import dask.array as da
        da = da.asarray(self.d)
        v = Variable(dims=('x', 'y'), data=DaskIndexingAdapter(da))
        self.check_orthogonal_indexing(v)
        self.check_vectorized_indexing(v)
        # doubly wrapping
        v = Variable(dims=('x', 'y'),
                     data=CopyOnWriteArray(DaskIndexingAdapter(da)))
        self.check_orthogonal_indexing(v)
        self.check_vectorized_indexing(v)