Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

185bb7e5-284c-4ca0-80d9-a0f6d296fc26 25 KB
Raw

You have to be logged in to leave a comment. Sign In
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
  1. """Compatibility module defining operations on duck numpy-arrays.
  2. Currently, this means Dask or NumPy arrays. None of these functions should
  3. accept or return xarray objects.
  4. """
  5. from __future__ import annotations
  6. import contextlib
  7. import datetime
  8. import inspect
  9. import warnings
  10. from functools import partial
  11. from importlib import import_module
  12. import numpy as np
  13. import pandas as pd
  14. from numpy import all as array_all # noqa
  15. from numpy import any as array_any # noqa
  16. from numpy import ( # noqa
  17. around, # noqa
  18. gradient,
  19. isclose,
  20. isin,
  21. isnat,
  22. take,
  23. tensordot,
  24. transpose,
  25. unravel_index,
  26. zeros_like, # noqa
  27. )
  28. from numpy import concatenate as _concatenate
  29. from numpy.core.multiarray import normalize_axis_index # type: ignore[attr-defined]
  30. from numpy.lib.stride_tricks import sliding_window_view # noqa
  31. from packaging.version import Version
  32. from xarray.core import dask_array_ops, dtypes, nputils, pycompat
  33. from xarray.core.options import OPTIONS
  34. from xarray.core.parallelcompat import get_chunked_array_type, is_chunked_array
  35. from xarray.core.pycompat import array_type, is_duck_dask_array
  36. from xarray.core.utils import is_duck_array, module_available
  37. dask_available = module_available("dask")
  38. def get_array_namespace(x):
  39. if hasattr(x, "__array_namespace__"):
  40. return x.__array_namespace__()
  41. else:
  42. return np
  43. def einsum(*args, **kwargs):
  44. from xarray.core.options import OPTIONS
  45. if OPTIONS["use_opt_einsum"] and module_available("opt_einsum"):
  46. import opt_einsum
  47. return opt_einsum.contract(*args, **kwargs)
  48. else:
  49. return np.einsum(*args, **kwargs)
  50. def _dask_or_eager_func(
  51. name,
  52. eager_module=np,
  53. dask_module="dask.array",
  54. ):
  55. """Create a function that dispatches to dask for dask array inputs."""
  56. def f(*args, **kwargs):
  57. if any(is_duck_dask_array(a) for a in args):
  58. mod = (
  59. import_module(dask_module)
  60. if isinstance(dask_module, str)
  61. else dask_module
  62. )
  63. wrapped = getattr(mod, name)
  64. else:
  65. wrapped = getattr(eager_module, name)
  66. return wrapped(*args, **kwargs)
  67. return f
  68. def fail_on_dask_array_input(values, msg=None, func_name=None):
  69. if is_duck_dask_array(values):
  70. if msg is None:
  71. msg = "%r is not yet a valid method on dask arrays"
  72. if func_name is None:
  73. func_name = inspect.stack()[1][3]
  74. raise NotImplementedError(msg % func_name)
  75. # Requires special-casing because pandas won't automatically dispatch to dask.isnull via NEP-18
  76. pandas_isnull = _dask_or_eager_func("isnull", eager_module=pd, dask_module="dask.array")
  77. # np.around has failing doctests, overwrite it so they pass:
  78. # https://github.com/numpy/numpy/issues/19759
  79. around.__doc__ = str.replace(
  80. around.__doc__ or "",
  81. "array([0., 2.])",
  82. "array([0., 2.])",
  83. )
  84. around.__doc__ = str.replace(
  85. around.__doc__ or "",
  86. "array([0., 2.])",
  87. "array([0., 2.])",
  88. )
  89. around.__doc__ = str.replace(
  90. around.__doc__ or "",
  91. "array([0.4, 1.6])",
  92. "array([0.4, 1.6])",
  93. )
  94. around.__doc__ = str.replace(
  95. around.__doc__ or "",
  96. "array([0., 2., 2., 4., 4.])",
  97. "array([0., 2., 2., 4., 4.])",
  98. )
  99. around.__doc__ = str.replace(
  100. around.__doc__ or "",
  101. (
  102. ' .. [2] "How Futile are Mindless Assessments of\n'
  103. ' Roundoff in Floating-Point Computation?", William Kahan,\n'
  104. " https://people.eecs.berkeley.edu/~wkahan/Mindless.pdf\n"
  105. ),
  106. "",
  107. )
  108. def isnull(data):
  109. data = asarray(data)
  110. scalar_type = data.dtype.type
  111. if issubclass(scalar_type, (np.datetime64, np.timedelta64)):
  112. # datetime types use NaT for null
  113. # note: must check timedelta64 before integers, because currently
  114. # timedelta64 inherits from np.integer
  115. return isnat(data)
  116. elif issubclass(scalar_type, np.inexact):
  117. # float types use NaN for null
  118. xp = get_array_namespace(data)
  119. return xp.isnan(data)
  120. elif issubclass(scalar_type, (np.bool_, np.integer, np.character, np.void)):
  121. # these types cannot represent missing values
  122. return zeros_like(data, dtype=bool)
  123. else:
  124. # at this point, array should have dtype=object
  125. if isinstance(data, np.ndarray):
  126. return pandas_isnull(data)
  127. else:
  128. # Not reachable yet, but intended for use with other duck array
  129. # types. For full consistency with pandas, we should accept None as
  130. # a null value as well as NaN, but it isn't clear how to do this
  131. # with duck typing.
  132. return data != data
  133. def notnull(data):
  134. return ~isnull(data)
  135. # TODO replace with simply np.ma.masked_invalid once numpy/numpy#16022 is fixed
  136. masked_invalid = _dask_or_eager_func(
  137. "masked_invalid", eager_module=np.ma, dask_module="dask.array.ma"
  138. )
  139. def trapz(y, x, axis):
  140. if axis < 0:
  141. axis = y.ndim + axis
  142. x_sl1 = (slice(1, None),) + (None,) * (y.ndim - axis - 1)
  143. x_sl2 = (slice(None, -1),) + (None,) * (y.ndim - axis - 1)
  144. slice1 = (slice(None),) * axis + (slice(1, None),)
  145. slice2 = (slice(None),) * axis + (slice(None, -1),)
  146. dx = x[x_sl1] - x[x_sl2]
  147. integrand = dx * 0.5 * (y[tuple(slice1)] + y[tuple(slice2)])
  148. return sum(integrand, axis=axis, skipna=False)
  149. def cumulative_trapezoid(y, x, axis):
  150. if axis < 0:
  151. axis = y.ndim + axis
  152. x_sl1 = (slice(1, None),) + (None,) * (y.ndim - axis - 1)
  153. x_sl2 = (slice(None, -1),) + (None,) * (y.ndim - axis - 1)
  154. slice1 = (slice(None),) * axis + (slice(1, None),)
  155. slice2 = (slice(None),) * axis + (slice(None, -1),)
  156. dx = x[x_sl1] - x[x_sl2]
  157. integrand = dx * 0.5 * (y[tuple(slice1)] + y[tuple(slice2)])
  158. # Pad so that 'axis' has same length in result as it did in y
  159. pads = [(1, 0) if i == axis else (0, 0) for i in range(y.ndim)]
  160. integrand = np.pad(integrand, pads, mode="constant", constant_values=0.0)
  161. return cumsum(integrand, axis=axis, skipna=False)
  162. def astype(data, dtype, **kwargs):
  163. if hasattr(data, "__array_namespace__"):
  164. xp = get_array_namespace(data)
  165. if xp == np:
  166. # numpy currently doesn't have a astype:
  167. return data.astype(dtype, **kwargs)
  168. return xp.astype(data, dtype, **kwargs)
  169. return data.astype(dtype, **kwargs)
  170. def asarray(data, xp=np):
  171. return data if is_duck_array(data) else xp.asarray(data)
  172. def as_shared_dtype(scalars_or_arrays, xp=np):
  173. """Cast a arrays to a shared dtype using xarray's type promotion rules."""
  174. array_type_cupy = array_type("cupy")
  175. if array_type_cupy and any(
  176. isinstance(x, array_type_cupy) for x in scalars_or_arrays
  177. ):
  178. import cupy as cp
  179. arrays = [asarray(x, xp=cp) for x in scalars_or_arrays]
  180. else:
  181. arrays = [asarray(x, xp=xp) for x in scalars_or_arrays]
  182. # Pass arrays directly instead of dtypes to result_type so scalars
  183. # get handled properly.
  184. # Note that result_type() safely gets the dtype from dask arrays without
  185. # evaluating them.
  186. out_type = dtypes.result_type(*arrays)
  187. return [astype(x, out_type, copy=False) for x in arrays]
  188. def broadcast_to(array, shape):
  189. xp = get_array_namespace(array)
  190. return xp.broadcast_to(array, shape)
  191. def lazy_array_equiv(arr1, arr2):
  192. """Like array_equal, but doesn't actually compare values.
  193. Returns True when arr1, arr2 identical or their dask tokens are equal.
  194. Returns False when shapes are not equal.
  195. Returns None when equality cannot determined: one or both of arr1, arr2 are numpy arrays;
  196. or their dask tokens are not equal
  197. """
  198. if arr1 is arr2:
  199. return True
  200. arr1 = asarray(arr1)
  201. arr2 = asarray(arr2)
  202. if arr1.shape != arr2.shape:
  203. return False
  204. if dask_available and is_duck_dask_array(arr1) and is_duck_dask_array(arr2):
  205. from dask.base import tokenize
  206. # GH3068, GH4221
  207. if tokenize(arr1) == tokenize(arr2):
  208. return True
  209. else:
  210. return None
  211. return None
  212. def allclose_or_equiv(arr1, arr2, rtol=1e-5, atol=1e-8):
  213. """Like np.allclose, but also allows values to be NaN in both arrays"""
  214. arr1 = asarray(arr1)
  215. arr2 = asarray(arr2)
  216. lazy_equiv = lazy_array_equiv(arr1, arr2)
  217. if lazy_equiv is None:
  218. with warnings.catch_warnings():
  219. warnings.filterwarnings("ignore", r"All-NaN (slice|axis) encountered")
  220. return bool(isclose(arr1, arr2, rtol=rtol, atol=atol, equal_nan=True).all())
  221. else:
  222. return lazy_equiv
  223. def array_equiv(arr1, arr2):
  224. """Like np.array_equal, but also allows values to be NaN in both arrays"""
  225. arr1 = asarray(arr1)
  226. arr2 = asarray(arr2)
  227. lazy_equiv = lazy_array_equiv(arr1, arr2)
  228. if lazy_equiv is None:
  229. with warnings.catch_warnings():
  230. warnings.filterwarnings("ignore", "In the future, 'NAT == x'")
  231. flag_array = (arr1 == arr2) | (isnull(arr1) & isnull(arr2))
  232. return bool(flag_array.all())
  233. else:
  234. return lazy_equiv
  235. def array_notnull_equiv(arr1, arr2):
  236. """Like np.array_equal, but also allows values to be NaN in either or both
  237. arrays
  238. """
  239. arr1 = asarray(arr1)
  240. arr2 = asarray(arr2)
  241. lazy_equiv = lazy_array_equiv(arr1, arr2)
  242. if lazy_equiv is None:
  243. with warnings.catch_warnings():
  244. warnings.filterwarnings("ignore", "In the future, 'NAT == x'")
  245. flag_array = (arr1 == arr2) | isnull(arr1) | isnull(arr2)
  246. return bool(flag_array.all())
  247. else:
  248. return lazy_equiv
  249. def count(data, axis=None):
  250. """Count the number of non-NA in this array along the given axis or axes"""
  251. return np.sum(np.logical_not(isnull(data)), axis=axis)
  252. def sum_where(data, axis=None, dtype=None, where=None):
  253. xp = get_array_namespace(data)
  254. if where is not None:
  255. a = where_method(xp.zeros_like(data), where, data)
  256. else:
  257. a = data
  258. result = xp.sum(a, axis=axis, dtype=dtype)
  259. return result
  260. def where(condition, x, y):
  261. """Three argument where() with better dtype promotion rules."""
  262. xp = get_array_namespace(condition)
  263. return xp.where(condition, *as_shared_dtype([x, y], xp=xp))
  264. def where_method(data, cond, other=dtypes.NA):
  265. if other is dtypes.NA:
  266. other = dtypes.get_fill_value(data.dtype)
  267. return where(cond, data, other)
  268. def fillna(data, other):
  269. # we need to pass data first so pint has a chance of returning the
  270. # correct unit
  271. # TODO: revert after https://github.com/hgrecco/pint/issues/1019 is fixed
  272. return where(notnull(data), data, other)
  273. def concatenate(arrays, axis=0):
  274. """concatenate() with better dtype promotion rules."""
  275. # TODO: remove the additional check once `numpy` adds `concat` to its array namespace
  276. if hasattr(arrays[0], "__array_namespace__") and not isinstance(
  277. arrays[0], np.ndarray
  278. ):
  279. xp = get_array_namespace(arrays[0])
  280. return xp.concat(as_shared_dtype(arrays, xp=xp), axis=axis)
  281. return _concatenate(as_shared_dtype(arrays), axis=axis)
  282. def stack(arrays, axis=0):
  283. """stack() with better dtype promotion rules."""
  284. xp = get_array_namespace(arrays[0])
  285. return xp.stack(as_shared_dtype(arrays, xp=xp), axis=axis)
  286. def reshape(array, shape):
  287. xp = get_array_namespace(array)
  288. return xp.reshape(array, shape)
  289. def ravel(array):
  290. return reshape(array, (-1,))
  291. @contextlib.contextmanager
  292. def _ignore_warnings_if(condition):
  293. if condition:
  294. with warnings.catch_warnings():
  295. warnings.simplefilter("ignore")
  296. yield
  297. else:
  298. yield
  299. def _create_nan_agg_method(name, coerce_strings=False, invariant_0d=False):
  300. from xarray.core import nanops
  301. def f(values, axis=None, skipna=None, **kwargs):
  302. if kwargs.pop("out", None) is not None:
  303. raise TypeError(f"`out` is not valid for {name}")
  304. # The data is invariant in the case of 0d data, so do not
  305. # change the data (and dtype)
  306. # See https://github.com/pydata/xarray/issues/4885
  307. if invariant_0d and axis == ():
  308. return values
  309. values = asarray(values)
  310. if coerce_strings and values.dtype.kind in "SU":
  311. values = astype(values, object)
  312. func = None
  313. if skipna or (skipna is None and values.dtype.kind in "cfO"):
  314. nanname = "nan" + name
  315. func = getattr(nanops, nanname)
  316. else:
  317. if name in ["sum", "prod"]:
  318. kwargs.pop("min_count", None)
  319. xp = get_array_namespace(values)
  320. func = getattr(xp, name)
  321. try:
  322. with warnings.catch_warnings():
  323. warnings.filterwarnings("ignore", "All-NaN slice encountered")
  324. return func(values, axis=axis, **kwargs)
  325. except AttributeError:
  326. if not is_duck_dask_array(values):
  327. raise
  328. try: # dask/dask#3133 dask sometimes needs dtype argument
  329. # if func does not accept dtype, then raises TypeError
  330. return func(values, axis=axis, dtype=values.dtype, **kwargs)
  331. except (AttributeError, TypeError):
  332. raise NotImplementedError(
  333. f"{name} is not yet implemented on dask arrays"
  334. )
  335. f.__name__ = name
  336. return f
  337. # Attributes `numeric_only`, `available_min_count` is used for docs.
  338. # See ops.inject_reduce_methods
  339. argmax = _create_nan_agg_method("argmax", coerce_strings=True)
  340. argmin = _create_nan_agg_method("argmin", coerce_strings=True)
  341. max = _create_nan_agg_method("max", coerce_strings=True, invariant_0d=True)
  342. min = _create_nan_agg_method("min", coerce_strings=True, invariant_0d=True)
  343. sum = _create_nan_agg_method("sum", invariant_0d=True)
  344. sum.numeric_only = True
  345. sum.available_min_count = True
  346. std = _create_nan_agg_method("std")
  347. std.numeric_only = True
  348. var = _create_nan_agg_method("var")
  349. var.numeric_only = True
  350. median = _create_nan_agg_method("median", invariant_0d=True)
  351. median.numeric_only = True
  352. prod = _create_nan_agg_method("prod", invariant_0d=True)
  353. prod.numeric_only = True
  354. prod.available_min_count = True
  355. cumprod_1d = _create_nan_agg_method("cumprod", invariant_0d=True)
  356. cumprod_1d.numeric_only = True
  357. cumsum_1d = _create_nan_agg_method("cumsum", invariant_0d=True)
  358. cumsum_1d.numeric_only = True
  359. _mean = _create_nan_agg_method("mean", invariant_0d=True)
  360. def _datetime_nanmin(array):
  361. """nanmin() function for datetime64.
  362. Caveats that this function deals with:
  363. - In numpy < 1.18, min() on datetime64 incorrectly ignores NaT
  364. - numpy nanmin() don't work on datetime64 (all versions at the moment of writing)
  365. - dask min() does not work on datetime64 (all versions at the moment of writing)
  366. """
  367. assert array.dtype.kind in "mM"
  368. dtype = array.dtype
  369. # (NaT).astype(float) does not produce NaN...
  370. array = where(pandas_isnull(array), np.nan, array.astype(float))
  371. array = min(array, skipna=True)
  372. if isinstance(array, float):
  373. array = np.array(array)
  374. # ...but (NaN).astype("M8") does produce NaT
  375. return array.astype(dtype)
  376. def datetime_to_numeric(array, offset=None, datetime_unit=None, dtype=float):
  377. """Convert an array containing datetime-like data to numerical values.
  378. Convert the datetime array to a timedelta relative to an offset.
  379. Parameters
  380. ----------
  381. array : array-like
  382. Input data
  383. offset : None, datetime or cftime.datetime
  384. Datetime offset. If None, this is set by default to the array's minimum
  385. value to reduce round off errors.
  386. datetime_unit : {None, Y, M, W, D, h, m, s, ms, us, ns, ps, fs, as}
  387. If not None, convert output to a given datetime unit. Note that some
  388. conversions are not allowed due to non-linear relationships between units.
  389. dtype : dtype
  390. Output dtype.
  391. Returns
  392. -------
  393. array
  394. Numerical representation of datetime object relative to an offset.
  395. Notes
  396. -----
  397. Some datetime unit conversions won't work, for example from days to years, even
  398. though some calendars would allow for them (e.g. no_leap). This is because there
  399. is no `cftime.timedelta` object.
  400. """
  401. # Set offset to minimum if not given
  402. if offset is None:
  403. if array.dtype.kind in "Mm":
  404. offset = _datetime_nanmin(array)
  405. else:
  406. offset = min(array)
  407. # Compute timedelta object.
  408. # For np.datetime64, this can silently yield garbage due to overflow.
  409. # One option is to enforce 1970-01-01 as the universal offset.
  410. # This map_blocks call is for backwards compatibility.
  411. # dask == 2021.04.1 does not support subtracting object arrays
  412. # which is required for cftime
  413. if is_duck_dask_array(array) and np.issubdtype(array.dtype, object):
  414. array = array.map_blocks(lambda a, b: a - b, offset, meta=array._meta)
  415. else:
  416. array = array - offset
  417. # Scalar is converted to 0d-array
  418. if not hasattr(array, "dtype"):
  419. array = np.array(array)
  420. # Convert timedelta objects to float by first converting to microseconds.
  421. if array.dtype.kind in "O":
  422. return py_timedelta_to_float(array, datetime_unit or "ns").astype(dtype)
  423. # Convert np.NaT to np.nan
  424. elif array.dtype.kind in "mM":
  425. # Convert to specified timedelta units.
  426. if datetime_unit:
  427. array = array / np.timedelta64(1, datetime_unit)
  428. return np.where(isnull(array), np.nan, array.astype(dtype))
  429. def timedelta_to_numeric(value, datetime_unit="ns", dtype=float):
  430. """Convert a timedelta-like object to numerical values.
  431. Parameters
  432. ----------
  433. value : datetime.timedelta, numpy.timedelta64, pandas.Timedelta, str
  434. Time delta representation.
  435. datetime_unit : {Y, M, W, D, h, m, s, ms, us, ns, ps, fs, as}
  436. The time units of the output values. Note that some conversions are not allowed due to
  437. non-linear relationships between units.
  438. dtype : type
  439. The output data type.
  440. """
  441. import datetime as dt
  442. if isinstance(value, dt.timedelta):
  443. out = py_timedelta_to_float(value, datetime_unit)
  444. elif isinstance(value, np.timedelta64):
  445. out = np_timedelta64_to_float(value, datetime_unit)
  446. elif isinstance(value, pd.Timedelta):
  447. out = pd_timedelta_to_float(value, datetime_unit)
  448. elif isinstance(value, str):
  449. try:
  450. a = pd.to_timedelta(value)
  451. except ValueError:
  452. raise ValueError(
  453. f"Could not convert {value!r} to timedelta64 using pandas.to_timedelta"
  454. )
  455. return py_timedelta_to_float(a, datetime_unit)
  456. else:
  457. raise TypeError(
  458. f"Expected value of type str, pandas.Timedelta, datetime.timedelta "
  459. f"or numpy.timedelta64, but received {type(value).__name__}"
  460. )
  461. return out.astype(dtype)
  462. def _to_pytimedelta(array, unit="us"):
  463. return array.astype(f"timedelta64[{unit}]").astype(datetime.timedelta)
  464. def np_timedelta64_to_float(array, datetime_unit):
  465. """Convert numpy.timedelta64 to float.
  466. Notes
  467. -----
  468. The array is first converted to microseconds, which is less likely to
  469. cause overflow errors.
  470. """
  471. array = array.astype("timedelta64[ns]").astype(np.float64)
  472. conversion_factor = np.timedelta64(1, "ns") / np.timedelta64(1, datetime_unit)
  473. return conversion_factor * array
  474. def pd_timedelta_to_float(value, datetime_unit):
  475. """Convert pandas.Timedelta to float.
  476. Notes
  477. -----
  478. Built on the assumption that pandas timedelta values are in nanoseconds,
  479. which is also the numpy default resolution.
  480. """
  481. value = value.to_timedelta64()
  482. return np_timedelta64_to_float(value, datetime_unit)
  483. def _timedelta_to_seconds(array):
  484. if isinstance(array, datetime.timedelta):
  485. return array.total_seconds() * 1e6
  486. else:
  487. return np.reshape([a.total_seconds() for a in array.ravel()], array.shape) * 1e6
  488. def py_timedelta_to_float(array, datetime_unit):
  489. """Convert a timedelta object to a float, possibly at a loss of resolution."""
  490. array = asarray(array)
  491. if is_duck_dask_array(array):
  492. array = array.map_blocks(
  493. _timedelta_to_seconds, meta=np.array([], dtype=np.float64)
  494. )
  495. else:
  496. array = _timedelta_to_seconds(array)
  497. conversion_factor = np.timedelta64(1, "us") / np.timedelta64(1, datetime_unit)
  498. return conversion_factor * array
  499. def mean(array, axis=None, skipna=None, **kwargs):
  500. """inhouse mean that can handle np.datetime64 or cftime.datetime
  501. dtypes"""
  502. from xarray.core.common import _contains_cftime_datetimes
  503. array = asarray(array)
  504. if array.dtype.kind in "Mm":
  505. offset = _datetime_nanmin(array)
  506. # xarray always uses np.datetime64[ns] for np.datetime64 data
  507. dtype = "timedelta64[ns]"
  508. return (
  509. _mean(
  510. datetime_to_numeric(array, offset), axis=axis, skipna=skipna, **kwargs
  511. ).astype(dtype)
  512. + offset
  513. )
  514. elif _contains_cftime_datetimes(array):
  515. offset = min(array)
  516. timedeltas = datetime_to_numeric(array, offset, datetime_unit="us")
  517. mean_timedeltas = _mean(timedeltas, axis=axis, skipna=skipna, **kwargs)
  518. return _to_pytimedelta(mean_timedeltas, unit="us") + offset
  519. else:
  520. return _mean(array, axis=axis, skipna=skipna, **kwargs)
  521. mean.numeric_only = True # type: ignore[attr-defined]
  522. def _nd_cum_func(cum_func, array, axis, **kwargs):
  523. array = asarray(array)
  524. if axis is None:
  525. axis = tuple(range(array.ndim))
  526. if isinstance(axis, int):
  527. axis = (axis,)
  528. out = array
  529. for ax in axis:
  530. out = cum_func(out, axis=ax, **kwargs)
  531. return out
  532. def cumprod(array, axis=None, **kwargs):
  533. """N-dimensional version of cumprod."""
  534. return _nd_cum_func(cumprod_1d, array, axis, **kwargs)
  535. def cumsum(array, axis=None, **kwargs):
  536. """N-dimensional version of cumsum."""
  537. return _nd_cum_func(cumsum_1d, array, axis, **kwargs)
  538. def first(values, axis, skipna=None):
  539. """Return the first non-NA elements in this array along the given axis"""
  540. if (skipna or skipna is None) and values.dtype.kind not in "iSU":
  541. # only bother for dtypes that can hold NaN
  542. if is_chunked_array(values):
  543. return chunked_nanfirst(values, axis)
  544. else:
  545. return nputils.nanfirst(values, axis)
  546. return take(values, 0, axis=axis)
  547. def last(values, axis, skipna=None):
  548. """Return the last non-NA elements in this array along the given axis"""
  549. if (skipna or skipna is None) and values.dtype.kind not in "iSU":
  550. # only bother for dtypes that can hold NaN
  551. if is_chunked_array(values):
  552. return chunked_nanlast(values, axis)
  553. else:
  554. return nputils.nanlast(values, axis)
  555. return take(values, -1, axis=axis)
  556. def least_squares(lhs, rhs, rcond=None, skipna=False):
  557. """Return the coefficients and residuals of a least-squares fit."""
  558. if is_duck_dask_array(rhs):
  559. return dask_array_ops.least_squares(lhs, rhs, rcond=rcond, skipna=skipna)
  560. else:
  561. return nputils.least_squares(lhs, rhs, rcond=rcond, skipna=skipna)
  562. def _push(array, n: int | None = None, axis: int = -1):
  563. """
  564. Use either bottleneck or numbagg depending on options & what's available
  565. """
  566. if not OPTIONS["use_bottleneck"] and not OPTIONS["use_numbagg"]:
  567. raise RuntimeError(
  568. "ffill & bfill requires bottleneck or numbagg to be enabled."
  569. " Call `xr.set_options(use_bottleneck=True)` or `xr.set_options(use_numbagg=True)` to enable one."
  570. )
  571. if OPTIONS["use_numbagg"] and module_available("numbagg"):
  572. import numbagg
  573. if pycompat.mod_version("numbagg") < Version("0.6.2"):
  574. warnings.warn(
  575. f"numbagg >= 0.6.2 is required for bfill & ffill; {pycompat.mod_version('numbagg')} is installed. We'll attempt with bottleneck instead."
  576. )
  577. else:
  578. return numbagg.ffill(array, limit=n, axis=axis)
  579. # work around for bottleneck 178
  580. limit = n if n is not None else array.shape[axis]
  581. import bottleneck as bn
  582. return bn.push(array, limit, axis)
  583. def push(array, n, axis):
  584. if not OPTIONS["use_bottleneck"] and not OPTIONS["use_numbagg"]:
  585. raise RuntimeError(
  586. "ffill & bfill requires bottleneck or numbagg to be enabled."
  587. " Call `xr.set_options(use_bottleneck=True)` or `xr.set_options(use_numbagg=True)` to enable one."
  588. )
  589. if is_duck_dask_array(array):
  590. return dask_array_ops.push(array, n, axis)
  591. else:
  592. return _push(array, n, axis)
  593. def _first_last_wrapper(array, *, axis, op, keepdims):
  594. return op(array, axis, keepdims=keepdims)
  595. def _chunked_first_or_last(darray, axis, op):
  596. chunkmanager = get_chunked_array_type(darray)
  597. # This will raise the same error message seen for numpy
  598. axis = normalize_axis_index(axis, darray.ndim)
  599. wrapped_op = partial(_first_last_wrapper, op=op)
  600. return chunkmanager.reduction(
  601. darray,
  602. func=wrapped_op,
  603. aggregate_func=wrapped_op,
  604. axis=axis,
  605. dtype=darray.dtype,
  606. keepdims=False, # match numpy version
  607. )
  608. def chunked_nanfirst(darray, axis):
  609. return _chunked_first_or_last(darray, axis, op=nputils.nanfirst)
  610. def chunked_nanlast(darray, axis):
  611. return _chunked_first_or_last(darray, axis, op=nputils.nanlast)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...