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
|
# TODO is it possible to import pint-xarray from within xarray if pint is present?
import itertools
import pint
from pint import Unit
from xarray import register_dataarray_accessor, register_dataset_accessor
from xarray.core.dtypes import NA
from pint_xarray import conversion
from pint_xarray.conversion import no_unit_values
from pint_xarray.errors import format_error_message
_default = object()
def setup_registry(registry):
"""set up the given registry for use with pint_xarray
Namely, it enables ``force_ndarray_like`` to make sure results are always
duck arrays.
Parameters
----------
registry : pint.UnitRegistry
The registry to modify
"""
if not registry.force_ndarray and not registry.force_ndarray_like:
registry.force_ndarray_like = True
return registry
default_registry = setup_registry(pint.get_application_registry())
# TODO could/should we overwrite xr.open_dataset and xr.open_mfdataset to make
# them apply units upon loading???
# TODO could even override the decode_cf kwarg?
# TODO docstrings
# TODO type hints
def is_dict_like(obj):
return hasattr(obj, "keys") and hasattr(obj, "__getitem__")
def zip_mappings(*mappings, fill_value=None):
"""zip mappings by combining values for common keys into a tuple
Works like itertools.zip_longest, so if a key is missing from a
mapping, it is replaced by ``fill_value``.
Parameters
----------
*mappings : dict-like
The mappings to zip
fill_value
The value to use if a key is missing from a mapping.
Returns
-------
zipped : dict-like
The zipped mapping
"""
keys = set(itertools.chain.from_iterable(mapping.keys() for mapping in mappings))
# TODO: could this be made more efficient using itertools.groupby?
zipped = {
key: tuple(mapping.get(key, fill_value) for mapping in mappings) for key in keys
}
return zipped
def units_to_str_or_none(mapping, unit_format):
formatter = str if not unit_format else lambda v: unit_format.format(v)
return {
key: formatter(value) if isinstance(value, Unit) else value
for key, value in mapping.items()
}
# based on xarray.core.utils.either_dict_or_kwargs
# https://github.com/pydata/xarray/blob/v0.15.1/xarray/core/utils.py#L249-L268
def either_dict_or_kwargs(positional, keywords, method_name):
if positional not in (_default, None):
if not is_dict_like(positional):
raise ValueError(
f"the first argument to .{method_name} must be a dictionary"
)
if keywords:
raise ValueError(
"cannot specify both keyword and positional "
f"arguments to .{method_name}"
)
return positional
else:
return keywords
def get_registry(unit_registry, new_units, existing_units):
units = itertools.chain(new_units.values(), existing_units.values())
registries = {unit._REGISTRY for unit in units if isinstance(unit, Unit)}
if unit_registry is None:
if not registries:
unit_registry = default_registry
elif len(registries) == 1:
(unit_registry,) = registries
registries.add(unit_registry)
if len(registries) > 1 or unit_registry not in registries:
raise ValueError(
"using multiple unit registries in the same object is not supported"
)
if not unit_registry.force_ndarray_like and not unit_registry.force_ndarray:
raise ValueError(
"invalid registry. Please enable 'force_ndarray_like' or 'force_ndarray'."
)
return unit_registry
def _decide_units(units, registry, unit_attribute):
if units is _default and unit_attribute in (None, _default):
# or warn and return None?
raise ValueError("no units given")
elif units in no_unit_values or isinstance(units, Unit):
# TODO what happens if they pass in a Unit from a different registry
return units
elif units is _default:
if unit_attribute in no_unit_values:
return unit_attribute
if isinstance(unit_attribute, Unit):
units = unit_attribute
else:
units = registry.parse_units(unit_attribute)
else:
units = registry.parse_units(units)
return units
class DatasetLocIndexer:
__slots__ = ("ds",)
def __init__(self, ds):
self.ds = ds
def __getitem__(self, indexers):
if not is_dict_like(indexers):
raise NotImplementedError("pandas-style indexing is not supported, yet")
dims = self.ds.dims
indexer_units = conversion.extract_indexer_units(indexers)
indexer_units = {
name: indexer for name, indexer in indexer_units.items() if name in dims
}
# convert the indexes to the indexer's units
try:
converted = conversion.convert_units(self.ds, indexer_units)
except ValueError as e:
raise KeyError(*e.args) from e
# index
stripped_indexers = conversion.strip_indexer_units(indexers)
stripped = conversion.strip_units(converted)
converted_units = conversion.extract_units(converted)
indexed = stripped.loc[stripped_indexers]
return conversion.attach_units(indexed, converted_units)
class DataArrayLocIndexer:
__slots__ = ("da",)
def __init__(self, da):
self.da = da
def __getitem__(self, indexers):
if not is_dict_like(indexers):
raise NotImplementedError("pandas-style indexing is not supported, yet")
dims = self.da.dims
indexer_units = conversion.extract_indexer_units(indexers)
indexer_units = {
name: indexer for name, indexer in indexer_units.items() if name in dims
}
# convert the indexes to the indexer's units
try:
converted = conversion.convert_units(self.da, indexer_units)
except ValueError as e:
raise KeyError(*e.args) from e
# index
stripped_indexers = conversion.strip_indexer_units(indexers)
stripped = conversion.strip_units(converted)
converted_units = conversion.extract_units(converted)
indexed = stripped.loc[stripped_indexers]
return conversion.attach_units(indexed, converted_units)
def __setitem__(self, indexers, values):
if not is_dict_like(indexers):
raise NotImplementedError("pandas-style indexing is not supported, yet")
dims = self.da.dims
unit_attrs = conversion.extract_unit_attributes(self.da)
index_units = {
name: units for name, units in unit_attrs.items() if name in dims
}
# convert the indexers to the index units
try:
converted = conversion.convert_indexer_units(indexers, index_units)
except ValueError as e:
raise KeyError(*e.args) from e
# index
stripped_indexers = conversion.strip_indexer_units(converted)
self.da.loc[stripped_indexers] = values
@register_dataarray_accessor("pint")
class PintDataArrayAccessor:
"""
Access methods for DataArrays with units using Pint.
Methods and attributes can be accessed through the `.pint` attribute.
"""
def __init__(self, da):
self.da = da
def quantify(self, units=_default, unit_registry=None, **unit_kwargs):
"""
Attach units to the DataArray.
Units can be specified as a pint.Unit or as a string, which will be
parsed by the given unit registry. If no units are specified then the
units will be parsed from the `'units'` entry of the DataArray's
`.attrs`. Will raise a ValueError if the DataArray already contains a
unit-aware array with a different unit.
.. note::
Be aware that unless you're using ``dask`` this will load
the data into memory. To avoid that, consider converting
to ``dask`` first (e.g. using ``chunk``).
.. note::
Also note that datetime units (i.e. ones that match
``{units} since {date}``) in unit attributes will be
ignored, to avoid interfering with ``xarray``'s datetime
encoding / decoding.
Parameters
----------
units : unit-like or mapping of hashable to unit-like, optional
Physical units to use for this DataArray. If a str or
pint.Unit, will be used as the DataArray's units. If a
dict-like, it should map a variable name to the desired
unit (use the DataArray's name to refer to its data). If
not provided, ``quantify`` will try to read them from
``DataArray.attrs['units']`` using pint's parser. The
``"units"`` attribute will be removed from all variables
except from dimension coordinates.
unit_registry : pint.UnitRegistry, optional
Unit registry to be used for the units attached to this DataArray.
If not given then a default registry will be created.
**unit_kwargs
Keyword argument form of units.
Returns
-------
quantified : DataArray
DataArray whose wrapped array data will now be a Quantity
array with the specified units.
Notes
-----
``"none"`` and ``None`` can be used to mark variables that should not
be quantified.
Examples
--------
>>> da = xr.DataArray(
... data=[0.4, 0.9, 1.7, 4.8, 3.2, 9.1],
... dims=["wavelength"],
... coords={"wavelength": [1e-4, 2e-4, 4e-4, 6e-4, 1e-3, 2e-3]},
... )
>>> da.pint.quantify(units="Hz")
<xarray.DataArray (wavelength: 6)> Size: 48B
<Quantity([0.4 0.9 1.7 4.8 3.2 9.1], 'hertz')>
Coordinates:
* wavelength (wavelength) float64 48B 0.0001 0.0002 0.0004 0.0006 0.001 0.002
Don't quantify the data:
>>> da = xr.DataArray(
... data=[0.4, 0.9],
... dims=["wavelength"],
... attrs={"units": "Hz"},
... )
>>> da.pint.quantify(units=None)
<xarray.DataArray (wavelength: 2)> Size: 16B
array([0.4, 0.9])
Dimensions without coordinates: wavelength
Quantify with the same unit:
>>> q = da.pint.quantify()
>>> q
<xarray.DataArray (wavelength: 2)> Size: 16B
<Quantity([0.4 0.9], 'hertz')>
Dimensions without coordinates: wavelength
>>> q.pint.quantify("Hz")
<xarray.DataArray (wavelength: 2)> Size: 16B
<Quantity([0.4 0.9], 'hertz')>
Dimensions without coordinates: wavelength
"""
if units is None or isinstance(units, (str, pint.Unit)):
if self.da.name in unit_kwargs:
raise ValueError(
f"ambiguous values given for {repr(self.da.name)}:"
f" {repr(units)} and {repr(unit_kwargs[self.da.name])}"
)
unit_kwargs[self.da.name] = units
units = None
units = either_dict_or_kwargs(units, unit_kwargs, "quantify")
registry = get_registry(unit_registry, units, conversion.extract_units(self.da))
unit_attrs = conversion.extract_unit_attributes(self.da)
possible_new_units = zip_mappings(units, unit_attrs, fill_value=_default)
new_units = {}
invalid_units = {}
for name, (unit, attr) in possible_new_units.items():
if unit not in (_default, None) or attr not in (_default, None):
try:
new_units[name] = _decide_units(unit, registry, attr)
except (ValueError, pint.UndefinedUnitError) as e:
if unit not in (_default, None):
type = "parameter"
reported_unit = unit
else:
type = "attribute"
reported_unit = attr
invalid_units[name] = (reported_unit, type, e)
if invalid_units:
raise ValueError(format_error_message(invalid_units, "parse"))
existing_units = {
name: unit
for name, unit in conversion.extract_units(self.da).items()
if isinstance(unit, Unit)
}
overwritten_units = {
name: (old, new)
for name, (old, new) in zip_mappings(
existing_units, new_units, fill_value=_default
).items()
if old is not _default and new is not _default and old != new
}
if overwritten_units:
errors = {
name: (
new,
ValueError(
f"Cannot attach unit {repr(new)} to quantity: data "
f"already has units {repr(old)}"
),
)
for name, (old, new) in overwritten_units.items()
}
raise ValueError(format_error_message(errors, "attach"))
return self.da.pipe(conversion.strip_unit_attributes).pipe(
conversion.attach_units, new_units
)
def dequantify(self, format=None):
r"""
Convert the units of the DataArray to string attributes.
Will replace ``.attrs['units']`` on each variable with a string
representation of the ``pint.Unit`` instance.
Parameters
----------
format : str, default: None
The format specification (as accepted by pint) used for the string
representations. If ``None``, the registry's default
(:py:attr:`pint.UnitRegistry.default_format`) is used instead.
Returns
-------
dequantified : DataArray
DataArray whose array data is unitless, and of the type
that was previously wrapped by `pint.Quantity`.
See Also
--------
:doc:`pint:user/formatting`
pint's string formatting guide
Examples
--------
>>> da = xr.DataArray([0, 1], dims="x")
>>> q = da.pint.quantify("m / s")
>>> q
<xarray.DataArray (x: 2)> Size: 16B
<Quantity([0 1], 'meter / second')>
Dimensions without coordinates: x
>>> q.pint.dequantify(format="P")
<xarray.DataArray (x: 2)> Size: 16B
array([0, 1])
Dimensions without coordinates: x
Attributes:
units: meter/second
>>> q.pint.dequantify(format="~P")
<xarray.DataArray (x: 2)> Size: 16B
array([0, 1])
Dimensions without coordinates: x
Attributes:
units: m/s
Use the registry's default format
>>> pint_xarray.unit_registry.default_format = "~L"
>>> q.pint.dequantify()
<xarray.DataArray (x: 2)> Size: 16B
array([0, 1])
Dimensions without coordinates: x
Attributes:
units: \frac{\mathrm{m}}{\mathrm{s}}
"""
units = conversion.extract_unit_attributes(self.da)
units.update(conversion.extract_units(self.da))
unit_format = f"{{:{format}}}" if isinstance(format, str) else format
units = units_to_str_or_none(units, unit_format)
return (
self.da.pipe(conversion.strip_units)
.pipe(conversion.strip_unit_attributes)
.pipe(conversion.attach_unit_attributes, units)
)
@property
def magnitude(self):
"""the magnitude of the data or the data itself if not a quantity."""
data = self.da.data
return getattr(data, "magnitude", data)
@property
def units(self):
"""the units of the data or :py:obj:`None` if not a quantity.
Setting the units is possible, but only if the data is not already a quantity.
"""
return getattr(self.da.data, "units", None)
@units.setter
def units(self, units):
self.da.data = conversion.array_attach_units(self.da.data, units)
@property
def dimensionality(self):
"""get the dimensionality of the data or :py:obj:`None` if not a quantity."""
return getattr(self.da.data, "dimensionality", None)
@property
def registry(self):
# TODO is this a bad idea? (see GH issue #1071 in pint)
return getattr(self.da.data, "_REGISTRY", None)
@registry.setter
def registry(self, _):
raise AttributeError("Don't try to change the registry once created")
def to(self, units=None, **unit_kwargs):
"""convert the quantities in a DataArray
Parameters
----------
units : unit-like or mapping of hashable to unit-like, optional
The units to convert to. If a unit name or ``pint.Unit``
object, convert the DataArray's data. If a dict-like, it
has to map a variable name to a unit name or ``pint.Unit``
object.
**unit_kwargs
The kwargs form of ``units``. Can only be used for
variable names that are strings and valid python identifiers.
Returns
-------
object : DataArray
A new object with converted units.
Examples
--------
>>> da = xr.DataArray(
... data=np.linspace(0, 1, 5) * ureg.m,
... coords={"u": ("x", np.arange(5) * ureg.s)},
... dims="x",
... name="arr",
... )
>>> da
<xarray.DataArray 'arr' (x: 5)> Size: 40B
<Quantity([0. 0.25 0.5 0.75 1. ], 'meter')>
Coordinates:
u (x) int64 40B [s] 0 1 2 3 4
Dimensions without coordinates: x
Convert the data
>>> da.pint.to("mm")
<xarray.DataArray 'arr' (x: 5)> Size: 40B
<Quantity([ 0. 250. 500. 750. 1000.], 'millimeter')>
Coordinates:
u (x) int64 40B [s] 0 1 2 3 4
Dimensions without coordinates: x
>>> da.pint.to(ureg.mm)
<xarray.DataArray 'arr' (x: 5)> Size: 40B
<Quantity([ 0. 250. 500. 750. 1000.], 'millimeter')>
Coordinates:
u (x) int64 40B [s] 0 1 2 3 4
Dimensions without coordinates: x
>>> da.pint.to({da.name: "mm"})
<xarray.DataArray 'arr' (x: 5)> Size: 40B
<Quantity([ 0. 250. 500. 750. 1000.], 'millimeter')>
Coordinates:
u (x) int64 40B [s] 0 1 2 3 4
Dimensions without coordinates: x
Convert coordinates
>>> da.pint.to({"u": ureg.ms})
<xarray.DataArray 'arr' (x: 5)> Size: 40B
<Quantity([0. 0.25 0.5 0.75 1. ], 'meter')>
Coordinates:
u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03
Dimensions without coordinates: x
>>> da.pint.to(u="ms")
<xarray.DataArray 'arr' (x: 5)> Size: 40B
<Quantity([0. 0.25 0.5 0.75 1. ], 'meter')>
Coordinates:
u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03
Dimensions without coordinates: x
Convert both simultaneously
>>> da.pint.to("mm", u="ms")
<xarray.DataArray 'arr' (x: 5)> Size: 40B
<Quantity([ 0. 250. 500. 750. 1000.], 'millimeter')>
Coordinates:
u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03
Dimensions without coordinates: x
>>> da.pint.to({"arr": ureg.mm, "u": ureg.ms})
<xarray.DataArray 'arr' (x: 5)> Size: 40B
<Quantity([ 0. 250. 500. 750. 1000.], 'millimeter')>
Coordinates:
u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03
Dimensions without coordinates: x
>>> da.pint.to(arr="mm", u="ms")
<xarray.DataArray 'arr' (x: 5)> Size: 40B
<Quantity([ 0. 250. 500. 750. 1000.], 'millimeter')>
Coordinates:
u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03
Dimensions without coordinates: x
"""
if isinstance(units, (str, pint.Unit)):
unit_kwargs[self.da.name] = units
units = None
elif units is not None and not is_dict_like(units):
raise ValueError(
"units must be either a string, a pint.Unit object or a dict-like,"
f" but got {units!r}"
)
units = either_dict_or_kwargs(units, unit_kwargs, "to")
return conversion.convert_units(self.da, units)
def chunk(self, chunks, name_prefix="xarray-", token=None, lock=False):
"""unit-aware version of chunk
Like :py:meth:`xarray.DataArray.chunk`, but chunking a quantity will change the
wrapped type to ``dask``.
.. note::
It is recommended to only use this when chunking in-memory arrays. To
rechunk please use :py:meth:`xarray.DataArray.chunk`.
See Also
--------
xarray.DataArray.chunk
xarray.Dataset.pint.chunk
"""
units = conversion.extract_units(self.da)
stripped = conversion.strip_units(self.da)
chunked = stripped.chunk(
chunks, name_prefix=name_prefix, token=token, lock=lock
)
return conversion.attach_units(chunked, units)
def reindex(
self,
indexers=None,
method=None,
tolerance=None,
copy=True,
fill_value=NA,
**indexers_kwargs,
):
"""unit-aware version of reindex
Like :py:meth:`xarray.DataArray.reindex`, except the object's indexes are
converted to the units of the indexers first.
.. note::
``tolerance`` and ``fill_value`` are not supported, yet. They will be passed
through to ``DataArray.reindex`` unmodified.
See Also
--------
xarray.Dataset.pint.reindex
xarray.DataArray.pint.reindex_like
xarray.DataArray.reindex
"""
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "reindex")
dims = self.da.dims
indexer_units = conversion.extract_indexer_units(indexers)
indexer_units = {
name: indexer for name, indexer in indexer_units.items() if name in dims
}
# TODO: handle tolerance
# TODO: handle fill_value
# convert the indexes to the indexer's units
converted = conversion.convert_units(self.da, indexer_units)
converted_units = conversion.extract_units(converted)
stripped = conversion.strip_units(converted)
# index
stripped_indexers = conversion.strip_indexer_units(indexers)
indexed = stripped.reindex(
stripped_indexers,
method=method,
tolerance=tolerance,
copy=copy,
fill_value=fill_value,
)
return conversion.attach_units(indexed, converted_units)
def reindex_like(
self, other, method=None, tolerance=None, copy=True, fill_value=NA
):
"""unit-aware version of reindex_like
Like :py:meth:`xarray.DataArray.reindex_like`, except the object's indexes
are converted to the units of the indexers first.
.. note::
``tolerance`` and ``fill_value`` are not supported, yet. They will be passed
through to ``DataArray.reindex_like`` unmodified.
See Also
--------
xarray.Dataset.pint.reindex_like
xarray.DataArray.pint.reindex
xarray.DataArray.reindex_like
"""
indexer_units = conversion.extract_units(other)
converted = conversion.convert_units(self.da, indexer_units)
units = conversion.extract_units(converted)
stripped = conversion.strip_units(converted)
stripped_other = conversion.strip_units(other)
# TODO: handle tolerance
# TODO: handle fill_value
reindexed = stripped.reindex_like(
stripped_other,
method=method,
tolerance=tolerance,
copy=copy,
fill_value=fill_value,
)
return conversion.attach_units(reindexed, units)
def interp(
self,
coords=None,
method="linear",
assume_sorted=False,
kwargs=None,
**coords_kwargs,
):
"""unit-aware version of interp
Like :py:meth:`xarray.DataArray.interp`, except the object's indexes are
converted to the units of the indexers first.
.. note::
``method``, ``assume_sorted`` and ``kwargs`` are passed unmodified to
``DataArray.interp``.
See Also
--------
xarray.Dataset.pint.interp
xarray.DataArray.pint.interp_like
xarray.DataArray.interp
"""
indexers = either_dict_or_kwargs(coords, coords_kwargs, "interp")
dims = self.da.dims
indexer_units = conversion.extract_indexer_units(indexers)
indexer_units = {
name: indexer for name, indexer in indexer_units.items() if name in dims
}
# convert the indexes to the indexer's units
converted = conversion.convert_units(self.da, indexer_units)
units = conversion.extract_units(converted)
stripped = conversion.strip_units(converted)
# index
stripped_indexers = conversion.strip_indexer_units(indexers)
interpolated = stripped.interp(
stripped_indexers,
method=method,
assume_sorted=assume_sorted,
kwargs=kwargs,
)
return conversion.attach_units(interpolated, units)
def interp_like(self, other, method="linear", assume_sorted=False, kwargs=None):
"""unit-aware version of interp_like
Like :py:meth:`xarray.DataArray.interp_like`, except the object's indexes are converted
to the units of the indexers first.
.. note::
``method``, ``assume_sorted`` and ``kwargs`` are passed unmodified to
``DataArray.interp``.
See Also
--------
xarray.Dataset.pint.interp_like
xarray.DataArray.pint.interp
xarray.DataArray.interp_like
"""
indexer_units = conversion.extract_units(other)
converted = conversion.convert_units(self.da, indexer_units)
units = conversion.extract_units(converted)
stripped = conversion.strip_units(converted)
stripped_other = conversion.strip_units(other)
interpolated = stripped.interp_like(
stripped_other,
method=method,
assume_sorted=assume_sorted,
kwargs=kwargs,
)
return conversion.attach_units(interpolated, units)
def sel(
self, indexers=None, method=None, tolerance=None, drop=False, **indexers_kwargs
):
"""unit-aware version of sel
Like :py:meth:`xarray.DataArray.sel`, except the object's indexes are converted
to the units of the indexers first.
.. note::
``tolerance`` is not supported, yet. It will be passed through to
``DataArray.sel`` unmodified.
See Also
--------
xarray.Dataset.pint.sel
xarray.DataArray.sel
xarray.Dataset.sel
"""
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "sel")
dims = self.da.dims
indexer_units = conversion.extract_indexer_units(indexers)
indexer_units = {
name: indexer for name, indexer in indexer_units.items() if name in dims
}
# TODO: handle tolerance
# convert the indexes to the indexer's units
try:
converted = conversion.convert_units(self.da, indexer_units)
except ValueError as e:
raise KeyError(*e.args) from e
# index
stripped_indexers = conversion.strip_indexer_units(indexers)
stripped = conversion.strip_units(converted)
converted_units = conversion.extract_units(converted)
indexed = stripped.sel(
stripped_indexers,
method=method,
tolerance=tolerance,
drop=drop,
)
return conversion.attach_units(indexed, converted_units)
@property
def loc(self):
"""Unit-aware attribute for indexing
.. note::
Position based indexing (e.g. ``ds.loc[1, 2:]``) is not supported, yet
See Also
--------
xarray.DataArray.loc
"""
return DataArrayLocIndexer(self.da)
def drop_sel(self, labels=None, *, errors="raise", **labels_kwargs):
"""unit-aware version of drop_sel
Just like :py:meth:`xarray.DataArray.drop_sel`, except the indexers are converted
to the units of the object's indexes first.
See Also
--------
xarray.Dataset.pint.drop_sel
xarray.DataArray.drop_sel
xarray.Dataset.drop_sel
"""
indexers = either_dict_or_kwargs(labels, labels_kwargs, "drop_sel")
dims = self.da.dims
unit_attrs = conversion.extract_unit_attributes(self.da)
index_units = {
name: units for name, units in unit_attrs.items() if name in dims
}
# convert the indexers to the indexes units
try:
converted_indexers = conversion.convert_indexer_units(indexers, index_units)
except ValueError as e:
raise KeyError(*e.args) from e
# index
stripped_indexers = conversion.strip_indexer_units(converted_indexers)
indexed = self.da.drop_sel(
stripped_indexers,
errors=errors,
)
return indexed
def ffill(self, dim, limit=None):
"""unit-aware version of ffill
Like :py:meth:`xarray.DataArray.ffill` but without stripping the data units.
See Also
--------
xarray.DataArray.ffill
xarray.DataArray.pint.bfill
"""
units = conversion.extract_units(self.da)
stripped = conversion.strip_units(self.da)
filled = stripped.ffill(dim=dim, limit=limit)
return conversion.attach_units(filled, units)
def bfill(self, dim, limit=None):
"""unit-aware version of bfill
Like :py:meth:`xarray.DataArray.bfill` but without stripping the data units.
See Also
--------
xarray.DataArray.bfill
xarray.DataArray.pint.ffill
"""
units = conversion.extract_units(self.da)
stripped = conversion.strip_units(self.da)
filled = stripped.bfill(dim=dim, limit=limit)
return conversion.attach_units(filled, units)
def interpolate_na(
self,
dim=None,
method="linear",
limit=None,
use_coordinate=True,
max_gap=None,
keep_attrs=None,
**kwargs,
):
"""unit-aware version of interpolate_na
Like :py:meth:`xarray.DataArray.interpolate_na` but without stripping the units
on data or coordinates.
.. note::
``max_gap`` is not supported, yet, and will be passed through to
``DataArray.interpolate_na`` unmodified.
See Also
--------
xarray.Dataset.pint.interpolate_na
xarray.DataArray.interpolate_na
"""
units = conversion.extract_units(self.da)
stripped = conversion.strip_units(self.da)
interpolated = stripped.interpolate_na(
dim=dim,
method=method,
limit=limit,
use_coordinate=use_coordinate,
max_gap=max_gap,
keep_attrs=keep_attrs,
**kwargs,
)
return conversion.attach_units(interpolated, units)
@register_dataset_accessor("pint")
class PintDatasetAccessor:
"""
Access methods for DataArrays with units using Pint.
Methods and attributes can be accessed through the `.pint` attribute.
"""
def __init__(self, ds):
self.ds = ds
def quantify(self, units=_default, unit_registry=None, **unit_kwargs):
"""
Attach units to the variables of the Dataset.
Units can be specified as a ``pint.Unit`` or as a
string, which will be parsed by the given unit registry. If no
units are specified then the units will be parsed from the
``"units"`` entry of the Dataset variable's ``.attrs``. Will
raise a ValueError if any of the variables already contain a
unit-aware array with a different unit.
.. note::
Be aware that unless you're using ``dask`` this will load
the data into memory. To avoid that, consider converting
to ``dask`` first (e.g. using ``chunk``).
.. note::
Also note that datetime units (i.e. ones that match
``{units} since {date}``) in unit attributes will be
ignored, to avoid interfering with ``xarray``'s datetime
encoding / decoding.
Parameters
----------
units : mapping of hashable to unit-like, optional
Physical units to use for particular DataArrays in this
Dataset. It should map variable names to units (unit names
or ``pint.Unit`` objects). If not provided, ``quantify``
will try to read them from ``Dataset[var].attrs['units']``
using pint's parser. The ``"units"`` attribute will be
removed from all variables except from dimension coordinates.
unit_registry : pint.UnitRegistry, optional
Unit registry to be used for the units attached to each
DataArray in this Dataset. If not given then a default
registry will be created.
**unit_kwargs
Keyword argument form of ``units``.
Returns
-------
quantified : Dataset
Dataset whose variables will now contain Quantity arrays
with units.
Notes
-----
``"none"`` and ``None`` can be used to mark variables
that should not be quantified.
Examples
--------
>>> ds = xr.Dataset(
... {"a": ("x", [0, 3, 2], {"units": "m"}), "b": ("x", [5, -2, 1])},
... coords={"x": [0, 1, 2], "u": ("x", [-1, 0, 1], {"units": "s"})},
... )
>>> ds.pint.quantify()
<xarray.Dataset> Size: 96B
Dimensions: (x: 3)
Coordinates:
* x (x) int64 24B 0 1 2
u (x) int64 24B [s] -1 0 1
Data variables:
a (x) int64 24B [m] 0 3 2
b (x) int64 24B 5 -2 1
>>> ds.pint.quantify({"b": "dm"})
<xarray.Dataset> Size: 96B
Dimensions: (x: 3)
Coordinates:
* x (x) int64 24B 0 1 2
u (x) int64 24B [s] -1 0 1
Data variables:
a (x) int64 24B [m] 0 3 2
b (x) int64 24B [dm] 5 -2 1
Don't quantify specific variables:
>>> ds.pint.quantify({"a": None})
<xarray.Dataset> Size: 96B
Dimensions: (x: 3)
Coordinates:
* x (x) int64 24B 0 1 2
u (x) int64 24B [s] -1 0 1
Data variables:
a (x) int64 24B 0 3 2
b (x) int64 24B 5 -2 1
Quantify with the same unit:
>>> q = ds.pint.quantify()
>>> q
<xarray.Dataset> Size: 96B
Dimensions: (x: 3)
Coordinates:
* x (x) int64 24B 0 1 2
u (x) int64 24B [s] -1 0 1
Data variables:
a (x) int64 24B [m] 0 3 2
b (x) int64 24B 5 -2 1
>>> q.pint.quantify({"a": "m"})
<xarray.Dataset> Size: 96B
Dimensions: (x: 3)
Coordinates:
* x (x) int64 24B 0 1 2
u (x) int64 24B [s] -1 0 1
Data variables:
a (x) int64 24B [m] 0 3 2
b (x) int64 24B 5 -2 1
"""
units = either_dict_or_kwargs(units, unit_kwargs, "quantify")
registry = get_registry(unit_registry, units, conversion.extract_units(self.ds))
unit_attrs = conversion.extract_unit_attributes(self.ds)
possible_new_units = zip_mappings(units, unit_attrs, fill_value=_default)
new_units = {}
invalid_units = {}
for name, (unit, attr) in possible_new_units.items():
if unit is not _default or attr not in (None, _default):
try:
new_units[name] = _decide_units(unit, registry, attr)
except (ValueError, pint.UndefinedUnitError) as e:
if unit is not _default:
type = "parameter"
reported_unit = unit
else:
type = "attribute"
reported_unit = attr
invalid_units[name] = (reported_unit, type, e)
if invalid_units:
raise ValueError(format_error_message(invalid_units, "parse"))
existing_units = {
name: unit
for name, unit in conversion.extract_units(self.ds).items()
if isinstance(unit, Unit)
}
overwritten_units = {
name: (old, new)
for name, (old, new) in zip_mappings(
existing_units, new_units, fill_value=_default
).items()
if old is not _default and new is not _default and old != new
}
if overwritten_units:
errors = {
name: (
new,
ValueError(
f"Cannot attach unit {repr(new)} to quantity: data "
f"already has units {repr(old)}"
),
)
for name, (old, new) in overwritten_units.items()
}
raise ValueError(format_error_message(errors, "attach"))
return self.ds.pipe(conversion.strip_unit_attributes).pipe(
conversion.attach_units, new_units
)
def dequantify(self, format=None):
r"""
Convert units from the Dataset to string attributes.
Will replace ``.attrs['units']`` on each variable with a string
representation of the ``pint.Unit`` instance.
Parameters
----------
format : str, default: None
The format specification (as accepted by pint's unit formatter) used for the
string representations. If ``None``, the registry's default
(:py:attr:`pint.UnitRegistry.default_format`) is used instead.
Returns
-------
dequantified : Dataset
Dataset whose data variables are unitless, and of the type
that was previously wrapped by ``pint.Quantity``.
See Also
--------
:doc:`pint:user/formatting`
pint's string formatting guide
Examples
--------
>>> ds = xr.Dataset({"a": ("x", [0, 1]), "b": ("y", [2, 3, 4])})
>>> q = ds.pint.quantify({"a": "m / s", "b": "s"})
>>> q
<xarray.Dataset> Size: 40B
Dimensions: (x: 2, y: 3)
Dimensions without coordinates: x, y
Data variables:
a (x) int64 16B [m/s] 0 1
b (y) int64 24B [s] 2 3 4
>>> d = q.pint.dequantify(format="P")
>>> d.a
<xarray.DataArray 'a' (x: 2)> Size: 16B
array([0, 1])
Dimensions without coordinates: x
Attributes:
units: meter/second
>>> d.b
<xarray.DataArray 'b' (y: 3)> Size: 24B
array([2, 3, 4])
Dimensions without coordinates: y
Attributes:
units: second
>>> d = q.pint.dequantify(format="~P")
>>> d.a
<xarray.DataArray 'a' (x: 2)> Size: 16B
array([0, 1])
Dimensions without coordinates: x
Attributes:
units: m/s
>>> d.b
<xarray.DataArray 'b' (y: 3)> Size: 24B
array([2, 3, 4])
Dimensions without coordinates: y
Attributes:
units: s
Use the registry's default format
>>> pint_xarray.unit_registry.default_format = "~L"
>>> d = q.pint.dequantify()
>>> d.a
<xarray.DataArray 'a' (x: 2)> Size: 16B
array([0, 1])
Dimensions without coordinates: x
Attributes:
units: \frac{\mathrm{m}}{\mathrm{s}}
>>> d.b
<xarray.DataArray 'b' (y: 3)> Size: 24B
array([2, 3, 4])
Dimensions without coordinates: y
Attributes:
units: \mathrm{s}
"""
units = conversion.extract_unit_attributes(self.ds)
units.update(conversion.extract_units(self.ds))
unit_format = f"{{:{format}}}" if isinstance(format, str) else format
units = units_to_str_or_none(units, unit_format)
return (
self.ds.pipe(conversion.strip_units)
.pipe(conversion.strip_unit_attributes)
.pipe(conversion.attach_unit_attributes, units)
)
def to(self, units=None, **unit_kwargs):
"""convert the quantities in a Dataset
Parameters
----------
units : unit-like or mapping of hashable to unit-like, optional
The units to convert to. If a unit name or ``pint.Unit``
object, convert all the object's data variables. If a dict-like, it
maps variable names to unit names or ``pint.Unit``
objects.
**unit_kwargs
The kwargs form of ``units``. Can only be used for
variable names that are strings and valid python identifiers.
Returns
-------
object : Dataset
A new object with converted units.
Examples
--------
>>> ds = xr.Dataset(
... data_vars={
... "a": ("x", np.linspace(0, 1, 5) * ureg.m),
... "b": ("x", np.linspace(-1, 0, 5) * ureg.kg),
... },
... coords={"u": ("x", np.arange(5) * ureg.s)},
... )
>>> ds
<xarray.Dataset> Size: 120B
Dimensions: (x: 5)
Coordinates:
u (x) int64 40B [s] 0 1 2 3 4
Dimensions without coordinates: x
Data variables:
a (x) float64 40B [m] 0.0 0.25 0.5 0.75 1.0
b (x) float64 40B [kg] -1.0 -0.75 -0.5 -0.25 0.0
Convert the data
>>> ds.pint.to({"a": "mm", "b": ureg.g})
<xarray.Dataset> Size: 120B
Dimensions: (x: 5)
Coordinates:
u (x) int64 40B [s] 0 1 2 3 4
Dimensions without coordinates: x
Data variables:
a (x) float64 40B [mm] 0.0 250.0 500.0 750.0 1e+03
b (x) float64 40B [g] -1e+03 -750.0 -500.0 -250.0 0.0
>>> ds.pint.to(a=ureg.mm, b="g")
<xarray.Dataset> Size: 120B
Dimensions: (x: 5)
Coordinates:
u (x) int64 40B [s] 0 1 2 3 4
Dimensions without coordinates: x
Data variables:
a (x) float64 40B [mm] 0.0 250.0 500.0 750.0 1e+03
b (x) float64 40B [g] -1e+03 -750.0 -500.0 -250.0 0.0
Convert coordinates
>>> ds.pint.to({"u": ureg.ms})
<xarray.Dataset> Size: 120B
Dimensions: (x: 5)
Coordinates:
u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03
Dimensions without coordinates: x
Data variables:
a (x) float64 40B [m] 0.0 0.25 0.5 0.75 1.0
b (x) float64 40B [kg] -1.0 -0.75 -0.5 -0.25 0.0
>>> ds.pint.to(u="ms")
<xarray.Dataset> Size: 120B
Dimensions: (x: 5)
Coordinates:
u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03
Dimensions without coordinates: x
Data variables:
a (x) float64 40B [m] 0.0 0.25 0.5 0.75 1.0
b (x) float64 40B [kg] -1.0 -0.75 -0.5 -0.25 0.0
Convert both simultaneously
>>> ds.pint.to(a=ureg.mm, b=ureg.g, u="ms")
<xarray.Dataset> Size: 120B
Dimensions: (x: 5)
Coordinates:
u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03
Dimensions without coordinates: x
Data variables:
a (x) float64 40B [mm] 0.0 250.0 500.0 750.0 1e+03
b (x) float64 40B [g] -1e+03 -750.0 -500.0 -250.0 0.0
>>> ds.pint.to({"a": "mm", "b": "g", "u": ureg.ms})
<xarray.Dataset> Size: 120B
Dimensions: (x: 5)
Coordinates:
u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03
Dimensions without coordinates: x
Data variables:
a (x) float64 40B [mm] 0.0 250.0 500.0 750.0 1e+03
b (x) float64 40B [g] -1e+03 -750.0 -500.0 -250.0 0.0
Convert homogeneous data
>>> ds = xr.Dataset(
... data_vars={
... "a": ("x", np.linspace(0, 1, 5) * ureg.kg),
... "b": ("x", np.linspace(-1, 0, 5) * ureg.mg),
... },
... coords={"u": ("x", np.arange(5) * ureg.s)},
... )
>>> ds
<xarray.Dataset> Size: 120B
Dimensions: (x: 5)
Coordinates:
u (x) int64 40B [s] 0 1 2 3 4
Dimensions without coordinates: x
Data variables:
a (x) float64 40B [kg] 0.0 0.25 0.5 0.75 1.0
b (x) float64 40B [mg] -1.0 -0.75 -0.5 -0.25 0.0
>>> ds.pint.to("g")
<xarray.Dataset> Size: 120B
Dimensions: (x: 5)
Coordinates:
u (x) int64 40B [s] 0 1 2 3 4
Dimensions without coordinates: x
Data variables:
a (x) float64 40B [g] 0.0 250.0 500.0 750.0 1e+03
b (x) float64 40B [g] -0.001 -0.00075 -0.0005 -0.00025 0.0
"""
if isinstance(units, (str, pint.Unit)):
unit_kwargs.update(
{name: units for name in self.ds.keys() if name not in unit_kwargs}
)
units = None
elif units is not None and not is_dict_like(units):
raise ValueError(
"units must be either a string, a pint.Unit object or a dict-like,"
f" but got {units!r}"
)
units = either_dict_or_kwargs(units, unit_kwargs, "to")
return conversion.convert_units(self.ds, units)
def chunk(self, chunks, name_prefix="xarray-", token=None, lock=False):
"""unit-aware version of chunk
Like :py:meth:`xarray.Dataset.chunk`, but chunking a quantity will change the
wrapped type to ``dask``.
.. note::
It is recommended to only use this when chunking in-memory arrays. To
rechunk please use :py:meth:`xarray.Dataset.chunk`.
See Also
--------
xarray.Dataset.chunk
xarray.DataArray.pint.chunk
"""
units = conversion.extract_units(self.ds)
stripped = conversion.strip_units(self.ds)
chunked = stripped.chunk(
chunks, name_prefix=name_prefix, token=token, lock=lock
)
return conversion.attach_units(chunked, units)
def reindex(
self,
indexers=None,
method=None,
tolerance=None,
copy=True,
fill_value=NA,
**indexers_kwargs,
):
"""unit-aware version of reindex
Like :py:meth:`xarray.Dataset.reindex`, except the object's indexes are converted
to the units of the indexers first.
.. note::
``tolerance`` and ``fill_value`` are not supported, yet. They will be passed through to
``Dataset.reindex`` unmodified.
See Also
--------
xarray.DataArray.pint.reindex
xarray.Dataset.pint.reindex_like
xarray.Dataset.reindex
"""
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "reindex")
dims = self.ds.dims
indexer_units = conversion.extract_indexer_units(indexers)
indexer_units = {
name: indexer for name, indexer in indexer_units.items() if name in dims
}
# TODO: handle tolerance
# TODO: handle fill_value
# convert the indexes to the indexer's units
converted = conversion.convert_units(self.ds, indexer_units)
converted_units = conversion.extract_units(converted)
stripped = conversion.strip_units(converted)
# index
stripped_indexers = conversion.strip_indexer_units(indexers)
indexed = stripped.reindex(
stripped_indexers,
method=method,
tolerance=tolerance,
copy=copy,
fill_value=fill_value,
)
return conversion.attach_units(indexed, converted_units)
def reindex_like(
self, other, method=None, tolerance=None, copy=True, fill_value=NA
):
"""unit-aware version of reindex_like
Like :py:meth:`xarray.Dataset.reindex_like`, except the object's indexes are converted
to the units of the indexers first.
.. note::
``tolerance`` and ``fill_value`` are not supported, yet. They will be passed through to
``Dataset.reindex_like`` unmodified.
See Also
--------
xarray.DataArray.pint.reindex_like
xarray.Dataset.pint.reindex
xarray.Dataset.reindex_like
"""
indexer_units = conversion.extract_units(other)
converted = conversion.convert_units(self.ds, indexer_units)
units = conversion.extract_units(converted)
stripped = conversion.strip_units(converted)
stripped_other = conversion.strip_units(other)
# TODO: handle tolerance
# TODO: handle fill_value
reindexed = stripped.reindex_like(
stripped_other,
method=method,
tolerance=tolerance,
copy=copy,
fill_value=fill_value,
)
return conversion.attach_units(reindexed, units)
def interp(
self,
coords=None,
method="linear",
assume_sorted=False,
kwargs=None,
**coords_kwargs,
):
"""unit-aware version of interp
Like :py:meth:`xarray.Dataset.interp`, except the object's indexes are converted
to the units of the indexers first.
.. note::
``method``, ``assume_sorted`` and ``kwargs`` are passed unmodified to
``DataArray.interp``.
See Also
--------
xarray.DataArray.pint.interp
xarray.Dataset.pint.interp_like
xarray.Dataset.interp
"""
indexers = either_dict_or_kwargs(coords, coords_kwargs, "interp")
dims = self.ds.dims
indexer_units = conversion.extract_indexer_units(indexers)
indexer_units = {
name: indexer for name, indexer in indexer_units.items() if name in dims
}
# convert the indexes to the indexer's units
converted = conversion.convert_units(self.ds, indexer_units)
units = conversion.extract_units(converted)
stripped = conversion.strip_units(converted)
# index
stripped_indexers = conversion.strip_indexer_units(indexers)
interpolated = stripped.interp(
stripped_indexers,
method=method,
assume_sorted=assume_sorted,
kwargs=kwargs,
)
return conversion.attach_units(interpolated, units)
def interp_like(self, other, method="linear", assume_sorted=False, kwargs=None):
"""unit-aware version of interp_like
Like :py:meth:`xarray.Dataset.interp_like`, except the object's indexes are
converted to the units of the indexers first.
.. note::
``method``, ``assume_sorted`` and ``kwargs`` are passed unmodified to
``DataArray.interp``.
See Also
--------
xarray.DataArray.pint.interp_like
xarray.Dataset.pint.interp
xarray.Dataset.interp_like
"""
indexer_units = conversion.extract_units(other)
converted = conversion.convert_units(self.ds, indexer_units)
units = conversion.extract_units(converted)
stripped = conversion.strip_units(converted)
stripped_other = conversion.strip_units(other)
interpolated = stripped.interp_like(
stripped_other,
method=method,
assume_sorted=assume_sorted,
kwargs=kwargs,
)
return conversion.attach_units(interpolated, units)
def sel(
self, indexers=None, method=None, tolerance=None, drop=False, **indexers_kwargs
):
"""unit-aware version of sel
Like :py:meth:`xarray.Dataset.sel`, except the object's indexes are converted to
the units of the indexers first.
.. note::
``tolerance`` is not supported, yet. It will be passed through to
``Dataset.sel`` unmodified.
See Also
--------
xarray.DataArray.pint.sel
xarray.Dataset.sel
xarray.DataArray.sel
"""
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "sel")
dims = self.ds.dims
indexer_units = conversion.extract_indexer_units(indexers)
indexer_units = {
name: indexer for name, indexer in indexer_units.items() if name in dims
}
# TODO: handle tolerance
# convert the indexes to the indexer's units
try:
converted = conversion.convert_units(self.ds, indexer_units)
except ValueError as e:
raise KeyError(*e.args) from e
# index
stripped_indexers = conversion.strip_indexer_units(indexers)
stripped = conversion.strip_units(converted)
converted_units = conversion.extract_units(converted)
indexed = stripped.sel(
stripped_indexers,
method=method,
tolerance=tolerance,
drop=drop,
)
return conversion.attach_units(indexed, converted_units)
@property
def loc(self):
"""Unit-aware attribute for indexing
Only supports ``__getitem__``.
.. note::
Position based indexing (e.g. ``ds.loc[1, 2:]``) is not supported, yet
See Also
--------
xarray.Dataset.loc
"""
return DatasetLocIndexer(self.ds)
def drop_sel(self, labels=None, *, errors="raise", **labels_kwargs):
"""unit-aware version of drop_sel
Just like :py:meth:`xarray.Dataset.drop_sel`, except the indexers are converted
to the units of the object's indexes first.
See Also
--------
xarray.DataArray.pint.drop_sel
xarray.Dataset.drop_sel
xarray.DataArray.drop_sel
"""
indexers = either_dict_or_kwargs(labels, labels_kwargs, "drop_sel")
dims = self.ds.dims
unit_attrs = conversion.extract_unit_attributes(self.ds)
index_units = {
name: units for name, units in unit_attrs.items() if name in dims
}
# convert the indexers to the indexes units
try:
converted_indexers = conversion.convert_indexer_units(indexers, index_units)
except ValueError as e:
raise KeyError(*e.args) from e
# index
stripped_indexers = conversion.strip_indexer_units(converted_indexers)
indexed = self.ds.drop_sel(
stripped_indexers,
errors=errors,
)
return indexed
def ffill(self, dim, limit=None):
"""unit-aware version of ffill
Like :py:meth:`xarray.Dataset.ffill` but without stripping the data units.
See Also
--------
xarray.Dataset.ffill
xarray.Dataset.pint.bfill
"""
units = conversion.extract_units(self.ds)
stripped = conversion.strip_units(self.ds)
filled = stripped.ffill(dim=dim, limit=limit)
return conversion.attach_units(filled, units)
def bfill(self, dim, limit=None):
"""unit-aware version of bfill
Like :py:meth:`xarray.Dataset.bfill` but without stripping the data units.
See Also
--------
xarray.Dataset.bfill
xarray.Dataset.pint.ffill
"""
units = conversion.extract_units(self.ds)
stripped = conversion.strip_units(self.ds)
filled = stripped.bfill(dim=dim, limit=limit)
return conversion.attach_units(filled, units)
def interpolate_na(
self,
dim=None,
method="linear",
limit=None,
use_coordinate=True,
max_gap=None,
keep_attrs=None,
**kwargs,
):
"""unit-aware version of interpolate_na
Like :py:meth:`xarray.Dataset.interpolate_na` but without stripping the units on
data or coordinates.
.. note::
``max_gap`` is not supported, yet, and will be passed through to
``Dataset.interpolate_na`` unmodified.
See Also
--------
xarray.DataArray.pint.interpolate_na
xarray.Dataset.interpolate_na
"""
units = conversion.extract_units(self.ds)
stripped = conversion.strip_units(self.ds)
interpolated = stripped.interpolate_na(
dim=dim,
method=method,
limit=limit,
use_coordinate=use_coordinate,
max_gap=max_gap,
keep_attrs=keep_attrs,
**kwargs,
)
return conversion.attach_units(interpolated, units)
|