pycontrails 0.54.0__cp312-cp312-macosx_10_13_x86_64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of pycontrails might be problematic. Click here for more details.
- pycontrails/__init__.py +70 -0
- pycontrails/_version.py +16 -0
- pycontrails/core/__init__.py +30 -0
- pycontrails/core/aircraft_performance.py +641 -0
- pycontrails/core/airports.py +226 -0
- pycontrails/core/cache.py +881 -0
- pycontrails/core/coordinates.py +174 -0
- pycontrails/core/fleet.py +470 -0
- pycontrails/core/flight.py +2314 -0
- pycontrails/core/flightplan.py +220 -0
- pycontrails/core/fuel.py +140 -0
- pycontrails/core/interpolation.py +721 -0
- pycontrails/core/met.py +2833 -0
- pycontrails/core/met_var.py +307 -0
- pycontrails/core/models.py +1181 -0
- pycontrails/core/polygon.py +549 -0
- pycontrails/core/rgi_cython.cpython-312-darwin.so +0 -0
- pycontrails/core/vector.py +2190 -0
- pycontrails/datalib/__init__.py +12 -0
- pycontrails/datalib/_leo_utils/search.py +250 -0
- pycontrails/datalib/_leo_utils/static/bq_roi_query.sql +6 -0
- pycontrails/datalib/_leo_utils/vis.py +59 -0
- pycontrails/datalib/_met_utils/metsource.py +746 -0
- pycontrails/datalib/ecmwf/__init__.py +73 -0
- pycontrails/datalib/ecmwf/arco_era5.py +340 -0
- pycontrails/datalib/ecmwf/common.py +109 -0
- pycontrails/datalib/ecmwf/era5.py +550 -0
- pycontrails/datalib/ecmwf/era5_model_level.py +487 -0
- pycontrails/datalib/ecmwf/hres.py +782 -0
- pycontrails/datalib/ecmwf/hres_model_level.py +459 -0
- pycontrails/datalib/ecmwf/ifs.py +284 -0
- pycontrails/datalib/ecmwf/model_levels.py +434 -0
- pycontrails/datalib/ecmwf/static/model_level_dataframe_v20240418.csv +139 -0
- pycontrails/datalib/ecmwf/variables.py +267 -0
- pycontrails/datalib/gfs/__init__.py +28 -0
- pycontrails/datalib/gfs/gfs.py +646 -0
- pycontrails/datalib/gfs/variables.py +100 -0
- pycontrails/datalib/goes.py +772 -0
- pycontrails/datalib/landsat.py +569 -0
- pycontrails/datalib/sentinel.py +511 -0
- pycontrails/datalib/spire.py +739 -0
- pycontrails/ext/bada.py +41 -0
- pycontrails/ext/cirium.py +14 -0
- pycontrails/ext/empirical_grid.py +140 -0
- pycontrails/ext/synthetic_flight.py +430 -0
- pycontrails/models/__init__.py +1 -0
- pycontrails/models/accf.py +406 -0
- pycontrails/models/apcemm/__init__.py +8 -0
- pycontrails/models/apcemm/apcemm.py +982 -0
- pycontrails/models/apcemm/inputs.py +226 -0
- pycontrails/models/apcemm/static/apcemm_yaml_template.yaml +183 -0
- pycontrails/models/apcemm/utils.py +437 -0
- pycontrails/models/cocip/__init__.py +29 -0
- pycontrails/models/cocip/cocip.py +2616 -0
- pycontrails/models/cocip/cocip_params.py +299 -0
- pycontrails/models/cocip/cocip_uncertainty.py +285 -0
- pycontrails/models/cocip/contrail_properties.py +1517 -0
- pycontrails/models/cocip/output_formats.py +2261 -0
- pycontrails/models/cocip/radiative_forcing.py +1262 -0
- pycontrails/models/cocip/radiative_heating.py +520 -0
- pycontrails/models/cocip/unterstrasser_wake_vortex.py +403 -0
- pycontrails/models/cocip/wake_vortex.py +396 -0
- pycontrails/models/cocip/wind_shear.py +120 -0
- pycontrails/models/cocipgrid/__init__.py +9 -0
- pycontrails/models/cocipgrid/cocip_grid.py +2573 -0
- pycontrails/models/cocipgrid/cocip_grid_params.py +138 -0
- pycontrails/models/dry_advection.py +494 -0
- pycontrails/models/emissions/__init__.py +21 -0
- pycontrails/models/emissions/black_carbon.py +594 -0
- pycontrails/models/emissions/emissions.py +1353 -0
- pycontrails/models/emissions/ffm2.py +336 -0
- pycontrails/models/emissions/static/default-engine-uids.csv +239 -0
- pycontrails/models/emissions/static/edb-gaseous-v29b-engines.csv +596 -0
- pycontrails/models/emissions/static/edb-nvpm-v29b-engines.csv +215 -0
- pycontrails/models/humidity_scaling/__init__.py +37 -0
- pycontrails/models/humidity_scaling/humidity_scaling.py +1025 -0
- pycontrails/models/humidity_scaling/quantiles/era5-model-level-quantiles.pq +0 -0
- pycontrails/models/humidity_scaling/quantiles/era5-pressure-level-quantiles.pq +0 -0
- pycontrails/models/issr.py +210 -0
- pycontrails/models/pcc.py +327 -0
- pycontrails/models/pcr.py +154 -0
- pycontrails/models/ps_model/__init__.py +17 -0
- pycontrails/models/ps_model/ps_aircraft_params.py +376 -0
- pycontrails/models/ps_model/ps_grid.py +505 -0
- pycontrails/models/ps_model/ps_model.py +1017 -0
- pycontrails/models/ps_model/ps_operational_limits.py +540 -0
- pycontrails/models/ps_model/static/ps-aircraft-params-20240524.csv +68 -0
- pycontrails/models/ps_model/static/ps-synonym-list-20240524.csv +103 -0
- pycontrails/models/sac.py +459 -0
- pycontrails/models/tau_cirrus.py +168 -0
- pycontrails/physics/__init__.py +1 -0
- pycontrails/physics/constants.py +116 -0
- pycontrails/physics/geo.py +989 -0
- pycontrails/physics/jet.py +837 -0
- pycontrails/physics/thermo.py +451 -0
- pycontrails/physics/units.py +472 -0
- pycontrails/py.typed +0 -0
- pycontrails/utils/__init__.py +1 -0
- pycontrails/utils/dependencies.py +66 -0
- pycontrails/utils/iteration.py +13 -0
- pycontrails/utils/json.py +188 -0
- pycontrails/utils/temp.py +50 -0
- pycontrails/utils/types.py +165 -0
- pycontrails-0.54.0.dist-info/LICENSE +178 -0
- pycontrails-0.54.0.dist-info/METADATA +179 -0
- pycontrails-0.54.0.dist-info/NOTICE +43 -0
- pycontrails-0.54.0.dist-info/RECORD +109 -0
- pycontrails-0.54.0.dist-info/WHEEL +5 -0
- pycontrails-0.54.0.dist-info/top_level.txt +3 -0
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""JSON utilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class NumpyEncoder(json.JSONEncoder):
|
|
13
|
+
"""Custom JSONEncoder for numpy data types.
|
|
14
|
+
|
|
15
|
+
Examples
|
|
16
|
+
--------
|
|
17
|
+
>>> import json
|
|
18
|
+
>>> import numpy as np
|
|
19
|
+
>>> from pycontrails.utils.json import NumpyEncoder
|
|
20
|
+
|
|
21
|
+
>>> data = np.array([0, 1, 2, 3])
|
|
22
|
+
>>> json.dumps(data, cls=NumpyEncoder)
|
|
23
|
+
'[0, 1, 2, 3]'
|
|
24
|
+
|
|
25
|
+
>>> data = np.datetime64(1234567890, "s")
|
|
26
|
+
>>> json.dumps(data, cls=NumpyEncoder)
|
|
27
|
+
'"2009-02-13T23:31:30"'
|
|
28
|
+
|
|
29
|
+
Notes
|
|
30
|
+
-----
|
|
31
|
+
Adapted https://github.com/hmallen/numpyencoder/blob/master/numpyencoder/numpyencoder.py
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def default(self, obj: Any) -> Any:
|
|
35
|
+
"""Encode numpy data types.
|
|
36
|
+
|
|
37
|
+
This method overrides :meth:`default` on the JSONEncoder class.
|
|
38
|
+
|
|
39
|
+
Parameters
|
|
40
|
+
----------
|
|
41
|
+
obj : Any
|
|
42
|
+
Object to encode.
|
|
43
|
+
|
|
44
|
+
Returns
|
|
45
|
+
-------
|
|
46
|
+
Any
|
|
47
|
+
Encoded object.
|
|
48
|
+
"""
|
|
49
|
+
if isinstance(
|
|
50
|
+
obj,
|
|
51
|
+
np.int_
|
|
52
|
+
| np.intc
|
|
53
|
+
| np.intp
|
|
54
|
+
| np.int8
|
|
55
|
+
| np.int16
|
|
56
|
+
| np.int32
|
|
57
|
+
| np.int64
|
|
58
|
+
| np.uint8
|
|
59
|
+
| np.uint16
|
|
60
|
+
| np.uint32
|
|
61
|
+
| np.uint64,
|
|
62
|
+
):
|
|
63
|
+
return int(obj)
|
|
64
|
+
|
|
65
|
+
if isinstance(obj, np.float16 | np.float32 | np.float64):
|
|
66
|
+
return float(obj)
|
|
67
|
+
|
|
68
|
+
# TODO: this is not easily reversible - np.timedelta64(str(np.timedelta64(1, "h"))) raises
|
|
69
|
+
if isinstance(obj, (np.timedelta64)):
|
|
70
|
+
return str(obj)
|
|
71
|
+
|
|
72
|
+
if isinstance(obj, (np.datetime64)):
|
|
73
|
+
return str(obj)
|
|
74
|
+
|
|
75
|
+
if isinstance(obj, np.complex64 | np.complex128):
|
|
76
|
+
return {"real": obj.real, "imag": obj.imag}
|
|
77
|
+
|
|
78
|
+
if isinstance(obj, np.ndarray):
|
|
79
|
+
return obj.tolist()
|
|
80
|
+
|
|
81
|
+
if isinstance(obj, (np.bool_)):
|
|
82
|
+
return bool(obj)
|
|
83
|
+
|
|
84
|
+
if isinstance(obj, (np.void)):
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
if isinstance(obj, pd.Series | pd.Index):
|
|
88
|
+
return obj.to_numpy().tolist()
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
return json.JSONEncoder.default(self, obj)
|
|
92
|
+
|
|
93
|
+
# last ditch attempt by looking for a to_json attribute
|
|
94
|
+
except TypeError as e:
|
|
95
|
+
try:
|
|
96
|
+
return obj.to_json
|
|
97
|
+
except AttributeError:
|
|
98
|
+
raise TypeError from e
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def dataframe_to_geojson_points(
|
|
102
|
+
df: pd.DataFrame,
|
|
103
|
+
properties: list[str] | None = None,
|
|
104
|
+
filter_nan: bool | list[str] = False,
|
|
105
|
+
) -> dict[str, Any]:
|
|
106
|
+
"""Convert a pandas DataFrame to a GeoJSON-like dictionary.
|
|
107
|
+
|
|
108
|
+
This function create a Python representation of a GeoJSON FeatureCollection with Point features
|
|
109
|
+
based on a :class:`pandas.DataFrame` with geospatial coordinate columns.
|
|
110
|
+
|
|
111
|
+
Parameters
|
|
112
|
+
----------
|
|
113
|
+
df : pd.DataFrame
|
|
114
|
+
Base dataframe.
|
|
115
|
+
Must contain geospatial coordinate columns ["longitude", "latitude", "altitude", "time"]
|
|
116
|
+
properties : list[str], optional
|
|
117
|
+
Specify columns to include feature properties.
|
|
118
|
+
By default, will use all column data that is not in the coordinate columns.
|
|
119
|
+
filter_nan : bool | list[str], optional
|
|
120
|
+
Filter out points with nan values in any columns, including coordinate columns.
|
|
121
|
+
If `list of str` is input, only `filter_nan` columns will be used for filtering,
|
|
122
|
+
allowing null values in the other columns.
|
|
123
|
+
|
|
124
|
+
Returns
|
|
125
|
+
-------
|
|
126
|
+
dict[str, Any]
|
|
127
|
+
Description
|
|
128
|
+
|
|
129
|
+
Raises
|
|
130
|
+
------
|
|
131
|
+
KeyError
|
|
132
|
+
Raises if `properties` or `filter_nan` input contains a column label that does
|
|
133
|
+
not exist in `df`
|
|
134
|
+
"""
|
|
135
|
+
# required columns
|
|
136
|
+
coord_cols = ["longitude", "latitude", "altitude", "time"]
|
|
137
|
+
|
|
138
|
+
# get all properties if not defined
|
|
139
|
+
if properties is None:
|
|
140
|
+
properties = [c for c in df.columns if c not in coord_cols]
|
|
141
|
+
elif [c for c in properties if c not in df.columns]:
|
|
142
|
+
raise KeyError(
|
|
143
|
+
f"{[c for c in properties if c not in df.columns]} do not exist in dataframe"
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
# downselect dataframe
|
|
147
|
+
cols = ["longitude", "latitude", "altitude", "time", *properties]
|
|
148
|
+
df = df[cols]
|
|
149
|
+
|
|
150
|
+
# filter out coords with nan values, or filter just on "filter_nan" labels
|
|
151
|
+
if isinstance(filter_nan, bool) and filter_nan:
|
|
152
|
+
df = df[np.all(~np.isnan(df[cols]), axis=1)]
|
|
153
|
+
elif isinstance(filter_nan, list):
|
|
154
|
+
if [c for c in filter_nan if c not in df.columns]:
|
|
155
|
+
raise KeyError(
|
|
156
|
+
f"{[c for c in filter_nan if c not in df.columns]} do not exist in dataframe"
|
|
157
|
+
)
|
|
158
|
+
df = df[np.all(~np.isnan(df[filter_nan]), axis=1)]
|
|
159
|
+
|
|
160
|
+
def row_to_feature(row: pd.Series) -> dict[str, str | dict[str, Any]]:
|
|
161
|
+
point = [
|
|
162
|
+
np.round(row.longitude, decimals=4) if not np.isnan(row.longitude) else None,
|
|
163
|
+
np.round(row.latitude, decimals=4) if not np.isnan(row.latitude) else None,
|
|
164
|
+
np.round(row.altitude, decimals=4) if not np.isnan(row.altitude) else None,
|
|
165
|
+
]
|
|
166
|
+
# converting to int to allow JSON serialization
|
|
167
|
+
properties = {"time": int(row.time.timestamp())}
|
|
168
|
+
used_keys = ["time", "latitude", "longitude", "altitude"]
|
|
169
|
+
unused_keys = [k for k in row.keys() if k not in used_keys] # noqa: SIM118
|
|
170
|
+
properties.update(
|
|
171
|
+
{
|
|
172
|
+
k: (
|
|
173
|
+
row[k]
|
|
174
|
+
if not isinstance(row[k], float)
|
|
175
|
+
or isinstance(row[k], float)
|
|
176
|
+
and not np.isnan(row[k])
|
|
177
|
+
else None
|
|
178
|
+
)
|
|
179
|
+
for k in unused_keys
|
|
180
|
+
}
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
geometry = {"type": "Point", "coordinates": point}
|
|
184
|
+
return {"type": "Feature", "geometry": geometry, "properties": properties}
|
|
185
|
+
|
|
186
|
+
features = []
|
|
187
|
+
df.apply(lambda row: features.append(row_to_feature(row)), axis=1)
|
|
188
|
+
return {"type": "FeatureCollection", "features": features}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Temp utilities."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import tempfile
|
|
6
|
+
from collections.abc import Generator
|
|
7
|
+
from contextlib import contextmanager
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def temp_filename() -> str:
|
|
13
|
+
"""Get a filename in the host computers temp directory.
|
|
14
|
+
|
|
15
|
+
More robust than using tempfile.NamedTemporaryFile()
|
|
16
|
+
|
|
17
|
+
Returns
|
|
18
|
+
-------
|
|
19
|
+
str
|
|
20
|
+
Temp filename
|
|
21
|
+
|
|
22
|
+
See Also
|
|
23
|
+
--------
|
|
24
|
+
temp_file : Context manager for temp file creation and cleanup
|
|
25
|
+
"""
|
|
26
|
+
return os.path.join(tempfile.gettempdir(), os.urandom(24).hex())
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def remove_tempfile(temp_filename: str) -> None:
|
|
30
|
+
"""Remove temp file.
|
|
31
|
+
|
|
32
|
+
Parameters
|
|
33
|
+
----------
|
|
34
|
+
temp_filename : str
|
|
35
|
+
Temp filename
|
|
36
|
+
"""
|
|
37
|
+
try:
|
|
38
|
+
os.unlink(temp_filename)
|
|
39
|
+
except OSError as e:
|
|
40
|
+
logger.warning("Failed to delete temp file %s with error %s", temp_filename, e)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@contextmanager
|
|
44
|
+
def temp_file() -> Generator[str, None, None]:
|
|
45
|
+
"""Get context manager for temp file creation and cleanup."""
|
|
46
|
+
filename = temp_filename()
|
|
47
|
+
try:
|
|
48
|
+
yield filename
|
|
49
|
+
finally:
|
|
50
|
+
remove_tempfile(filename)
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Convienence types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from typing import Any, TypeVar
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import numpy.typing as npt
|
|
12
|
+
import pandas as pd
|
|
13
|
+
import xarray as xr
|
|
14
|
+
|
|
15
|
+
#: Array like (np.ndarray, xr.DataArray)
|
|
16
|
+
ArrayLike = TypeVar("ArrayLike", np.ndarray, xr.DataArray, xr.DataArray | np.ndarray)
|
|
17
|
+
|
|
18
|
+
#: Array or Float (np.ndarray, float)
|
|
19
|
+
ArrayOrFloat = TypeVar(
|
|
20
|
+
"ArrayOrFloat", npt.NDArray[np.float64], float, float | npt.NDArray[np.float64]
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
#: Array like input (np.ndarray, xr.DataArray, np.float64, float)
|
|
24
|
+
ArrayScalarLike = TypeVar(
|
|
25
|
+
"ArrayScalarLike",
|
|
26
|
+
np.ndarray,
|
|
27
|
+
xr.DataArray,
|
|
28
|
+
np.float64,
|
|
29
|
+
float,
|
|
30
|
+
np.ndarray | float,
|
|
31
|
+
xr.DataArray | np.ndarray,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
#: Datetime like input (datetime, pd.Timestamp, np.datetime64)
|
|
35
|
+
DatetimeLike = TypeVar("DatetimeLike", datetime, pd.Timestamp, np.datetime64, str)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def support_arraylike(
|
|
39
|
+
func: Callable[[np.ndarray], np.ndarray],
|
|
40
|
+
) -> Callable[[ArrayScalarLike], ArrayScalarLike]:
|
|
41
|
+
"""Extend a numpy universal function operating on arrays of floats.
|
|
42
|
+
|
|
43
|
+
This decorator allows `func` to support any ArrayScalarLike parameter and
|
|
44
|
+
keeps the return type consistent with the parameter.
|
|
45
|
+
|
|
46
|
+
Parameters
|
|
47
|
+
----------
|
|
48
|
+
func : Callable[[ArrayScalarLike], np.ndarray]
|
|
49
|
+
A numpy `ufunc` taking in a single array with `float`-like dtype.
|
|
50
|
+
This decorator assumes `func` returns a numpy array.
|
|
51
|
+
|
|
52
|
+
Returns
|
|
53
|
+
-------
|
|
54
|
+
Callable[[ArrayScalarLike], ArrayScalarLike]
|
|
55
|
+
Extended function.
|
|
56
|
+
|
|
57
|
+
See Also
|
|
58
|
+
--------
|
|
59
|
+
- `numpy ufuncs <https://numpy.org/doc/stable/reference/ufuncs.html>`_
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def wrapped(arr: ArrayScalarLike) -> ArrayScalarLike:
|
|
63
|
+
x = np.asarray(arr)
|
|
64
|
+
|
|
65
|
+
# Convert to float if not already
|
|
66
|
+
if x.dtype not in (np.float32, np.float64):
|
|
67
|
+
x = x.astype(np.float64)
|
|
68
|
+
ret = func(x)
|
|
69
|
+
|
|
70
|
+
# Numpy in, numpy out
|
|
71
|
+
if isinstance(arr, np.ndarray):
|
|
72
|
+
return ret
|
|
73
|
+
|
|
74
|
+
# Keep python native numeric types native
|
|
75
|
+
if isinstance(arr, float | int | np.float64):
|
|
76
|
+
return ret.item()
|
|
77
|
+
|
|
78
|
+
# Recreate pd.Series
|
|
79
|
+
if isinstance(arr, pd.Series):
|
|
80
|
+
return pd.Series(data=ret, index=arr.index)
|
|
81
|
+
|
|
82
|
+
# Recreate xr.DataArray
|
|
83
|
+
if isinstance(arr, xr.DataArray):
|
|
84
|
+
return arr.copy(data=ret) # See documentation for xr.copy!
|
|
85
|
+
|
|
86
|
+
# Pass numpy `ret` through for anything else
|
|
87
|
+
return ret
|
|
88
|
+
|
|
89
|
+
# this line produces a mypy error starting on mypy version 1.1.0,
|
|
90
|
+
# likely due to changes in https://github.com/python/mypy/pull/16942
|
|
91
|
+
return functools.update_wrapper(wrapped, func) # type: ignore
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def apply_nan_mask_to_arraylike(arr: ArrayLike, nan_mask: np.ndarray) -> ArrayLike:
|
|
95
|
+
"""Apply ``nan_mask`` to ``arr`` while maintaining the type.
|
|
96
|
+
|
|
97
|
+
The parameter ``arr`` should have a ``float`` ``dtype``.
|
|
98
|
+
|
|
99
|
+
This function is tested against :class:`xr.DataArray`, :class:`pd.Series`, and
|
|
100
|
+
:class:`np.ndarray` types.
|
|
101
|
+
|
|
102
|
+
Parameters
|
|
103
|
+
----------
|
|
104
|
+
arr : ArrayLike
|
|
105
|
+
Array with ``np.float64`` entries
|
|
106
|
+
nan_mask : np.ndarray
|
|
107
|
+
Boolean array of the same shape as ``arr``
|
|
108
|
+
|
|
109
|
+
Returns
|
|
110
|
+
-------
|
|
111
|
+
ArrayLike
|
|
112
|
+
Array ``arr`` with values in ``nan_mask`` set to ``np.nan``. The ``arr`` is
|
|
113
|
+
mutated in place if it is a :class:`np.ndarray`. For :class:`xr.DataArray`,
|
|
114
|
+
a copy is returned.
|
|
115
|
+
|
|
116
|
+
Notes
|
|
117
|
+
-----
|
|
118
|
+
When ``arr`` is a :class:`xr.DataArray`, this function keeps any ``attrs``
|
|
119
|
+
from ``arr`` in the returned instance.
|
|
120
|
+
"""
|
|
121
|
+
if isinstance(arr, xr.DataArray):
|
|
122
|
+
# The previous implementation uses xr.where instead of arr.where
|
|
123
|
+
# There was some change in xarray 2022.6.0 that broke the former implementation
|
|
124
|
+
# Instead, use arr.where
|
|
125
|
+
return arr.where(~nan_mask, np.nan)
|
|
126
|
+
|
|
127
|
+
# If we want to avoid copying, use np.where(~nan_mask, arr, np.nan)
|
|
128
|
+
arr[nan_mask] = np.nan
|
|
129
|
+
return arr
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
_Object = TypeVar("_Object")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def type_guard(
|
|
136
|
+
obj: Any,
|
|
137
|
+
type_: type[_Object] | tuple[type[_Object], ...],
|
|
138
|
+
error_message: str | None = None,
|
|
139
|
+
) -> _Object:
|
|
140
|
+
"""Shortcut utility to type guard a variable with custom error message.
|
|
141
|
+
|
|
142
|
+
Parameters
|
|
143
|
+
----------
|
|
144
|
+
obj : Any
|
|
145
|
+
Any variable object
|
|
146
|
+
type_ : Type[_Object]
|
|
147
|
+
Type of variable.
|
|
148
|
+
Can be a tuple of types
|
|
149
|
+
error_message : str, optional
|
|
150
|
+
Custom error message
|
|
151
|
+
|
|
152
|
+
Returns
|
|
153
|
+
-------
|
|
154
|
+
_Object
|
|
155
|
+
Returns the input object ensured to be ``type_``
|
|
156
|
+
|
|
157
|
+
Raises
|
|
158
|
+
------
|
|
159
|
+
ValueError
|
|
160
|
+
Raises ValueError if ``obj`` is not ``type_``
|
|
161
|
+
"""
|
|
162
|
+
if not isinstance(obj, type_):
|
|
163
|
+
raise TypeError(error_message or f"Object must be of type {type_}")
|
|
164
|
+
|
|
165
|
+
return obj
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|