- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathxarray.py
More file actions
Latest commit
216 lines (178 loc) · 6.13 KB
/
Copy pathxarray.py
File metadata and controls
216 lines (178 loc) · 6.13 KB
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
importnumpyasnp
importxarrayasxr
importpandasaspd
fromfunctoolsimportreduce
from .cartopyimporttransform_points
deftransform_dataset(ds, coords, from_crs, to_crs):
"""
Transform coordinates of a Dataset or DataArray.
Output can be directly assigned into a dataset.
Arguments
---------
ds: xarray dataset
coords: iterable of dimension, coordinates, or data variable names
that hold the coordinates to be transformed
from_crs, to_crs: cartopy CRS instances
"""
x=ds[coords[0]]
y=ds[coords[1]]
x, y=xr.broadcast(x, y) # coerce to at least 2D
dims=x.dims
xp, yp=transform_points(from_crs, to_crs, x.values, y.values)
return ((dims, xp), (dims, yp))
defcrop(ds, **constraints):
"""
Crop an xarray dataset.
Discards all coordinates where a given coordinate or data variable is outside
the bounds given by the respective tuple.
Arguments
---------
ds: Dataset
constraints: dict, where keys are the name of a coordinate or data_var,
and values are tuples that will bound that coordinate or data_var.
"""
ds=ds.set_coords(list(constraints))
# set nan
forvar, (varmin, varmax) inconstraints.items():
ds=ds.where((ds[var]>varmin) & (ds[var]<varmax))
# crop array
fordiminds.dims:
other_dims= [dfordinds.dimsifd!=dim]
all_nans= [ds[var].isnull().all(other_dims) forvarinds.data_vars]
all_nan=reduce(lambdax, y: x&y, all_nans)
ds=ds.isel({dim: ~all_nan})
returnds
defapply_1d(over_da, func, dim, **kwargs):
"""
For those occasions where you'd think that ds.reduce() should do the trick,
but you somehow don't have a function that already handles ndarrays.
Parameters
----------
over_da : xarray DataArray or list thereof
func : Function that can handle a 1-dimensional ndarray
dim : Dimension over which to apply func
Usage
-----
e.g.: apply_1d(da, ols, dim='Depth', param='slope')
License
-------
GNU-GPLv3, (C) A. Randelhoff
(https://github.com/poplarShift/python-data-science-utils)
"""
ifnotisinstance(over_da, list):
over_da= [over_da]
da_dropped=over_da[0].isel({dim: 0}).drop(dim)
dims=da_dropped.coords.dims
results=np.nan*da_dropped
foridx, _innp.ndenumerate(da_dropped):
sel_dict= {c: iforc, iinzip(dims, idx)}
res=func(
*(da[sel_dict] fordainover_da),
**kwargs
)
results[sel_dict] =res
returnresults
defcritical_index_value(vals, crit_val, dim, smaller_than):
"""
Find the first value of an index (`dim`: str) where some value (`vals`: xr.DataArray) becomes
larger or smaller (`smaller_than`: bool) than `crit_val` (float).
Example
-----
To find Zeu, where iPAR drops below 1% of surface iPAR0-:
ds['Zeu'] = critical_index_value(ds['iPAR']/ds['iPAR0minus'], 0.01, 'Depth', True)
"""
ifsmaller_than:
criterion=vals<crit_val
else:
criterion=vals>crit_val
idx=criterion.reduce(np.argmax, dim=dim) #True>False
returnxr.where(idx>0, vals[dim].isel(**{dim:idx}), np.nan)
defols(da, param='slope'):
"""
Apply statsmodel's OLS regression to a 1d DataArray.
Handles datetimes (in that case, regression is against days).
Parameters
----------
data : xarray DataArray
str, one of ['slope', 'intercept', 'slope_pvalue',
'intercept_pvalue', 'slope_se', 'intercept_se',]
sought-after regression parameter
Notes
-----
https://www.statsmodels.org/dev/generated/statsmodels.regression.linear_model.OLS.html
License
-------
GNU-GPLv3, (C) A. Randelhoff
(https://github.com/poplarShift/python-data-science-utils)
"""
importstatsmodels.apiassm
data=da.dropna(dim=da.dims[0])
# specify function with which to retrieve sought-after
# parameter from statsmodels RegressionResultsWrapper
res_fn= {
'intercept': lambdares: res.params[0],
'slope': lambdares: res.params[1],
'intercept_pvalue': lambdares: res.pvalues[0],
'slope_pvalue': lambdares: res.pvalues[1],
'intercept_se': lambdares: res.bse[0],
'slope_se': lambdares: res.bse[1],
}
iflen(data)>=2:
y=data.values
xdata=data[data.dims[0]]
ifxdata.dtype.kindin ['M']:
x=xdata.astype(float).values/1e9/86400.
else:
x=xdata.values
ols=sm.OLS(y, sm.add_constant(x))
res=ols.fit()
returnres_fn[param](res)
else:
returnnp.nan
# implement precision for uniqueness?
# np.round(12.3456789, decimals=4)
# np.unique(ds.longitude.isel(profile_id=0))[2]
defget_unique(x, axis=0):
"""
Return unique non-nan value along specified xarray axis.
Use this to squeeze out dimensions with length>1.
Raises
------
ValueError: if there are more than one non-nan values
Usage
-----
ds.reduce(get_unique, dim=some_dim)
License
-------
GNU-GPLv3, (C) A. Randelhoff
(https://github.com/poplarShift/python-data-science-utils)
"""
is_obj=x.dtype.char=='O'
is_dt=np.issubdtype(x.dtype, np.datetime64)
x_=np.moveaxis(x, source=axis, destination=-1)
iteridx=x_.shape[:-1]
ifis_dt:
u=np.zeros(iteridx, dtype=x.dtype)
elifis_obj:
u=np.zeros(iteridx, dtype=x.dtype)
else: # numeric
u=np.nan*np.zeros(iteridx)
ifnotisinstance(u, np.ndarray):
# if iteridx was empty tuple
u=np.array(u)
isnull=lambdax: pd.isnull(x) | (x=='')
foriinnp.ndindex(iteridx):
u_1dim=np.unique(x_[i])
u_non_null=u_1dim[~isnull(u_1dim)]
iflen(u_non_null)==1:
u[i] =u_non_null[0]
elifisnull(u_1dim[0]):
ifis_dt:
u[i] =np.datetime64('NaT')
elifis_obj:
u[i] =''
else:
u[i] =np.nan
else:
raiseValueError(f'Non-unique slices encountered at {i}!')
returnu