-
Notifications
You must be signed in to change notification settings - Fork 306
/
grids.py
1435 lines (1187 loc) · 49.1 KB
/
grids.py
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
"""
Defines the AbstractGrid class and child classes.
"""
from collections.abc import Sequence
__all__ = [
"AbstractGrid",
"CartesianGrid",
"NonUniformCartesianGrid",
]
import contextlib
import warnings
from abc import ABC, abstractmethod
from collections import namedtuple
from functools import cached_property
from typing import Union
import astropy.units as u
import numpy as np
import pandas as pd
import scipy.interpolate as interp
import xarray as xr
from scipy.spatial import distance
from plasmapy.utils.decorators.helpers import modify_docstring
def _detect_is_uniform_grid(pts0, pts1, pts2, tol: float = 1e-6):
r"""
Determine whether a grid is uniform (uniformly spaced) by computing the
variance of the grid gradients.
"""
variance = np.zeros([3])
dx = np.gradient(pts0, axis=0)
variance[0] = np.std(dx) / np.mean(dx)
dy = np.gradient(pts1, axis=1)
variance[1] = np.std(dy) / np.mean(dy)
dz = np.gradient(pts2, axis=2)
variance[2] = np.std(dz) / np.mean(dz)
return np.allclose(variance, 0.0, atol=tol)
class AbstractGrid(ABC):
r"""
Abstract grid represents a 3D grid of positions. The grid is stored
as an `~numpy.ndarray`, while the units associated with each
dimension are stored separately.
There are two preferred methods to creating a grid object:
1. Initializing the grid by providing three 3D
`~astropy.units.Quantity` arrays of positions along each axis
(``xpoints``, ``ypoints``, ``zpoints``)
.. code-block:: python
AbstractGrid(xpoints, ypoints, zpoints)
2. A new grid can also be created using a syntax similar to
`numpy.linspace` by providing two three-element
`~astropy.units.Quantity` arrays of start and stop values and
setting the ``num`` keyword to the number of points along each axis.
.. code-block:: python
AbstractGrid(
start=[x0, y0, z0],
stop=[x1, y1, z1],
num=[Nx, Ny, Nz],
**kwargs,
)
In this case, any additional keyword arguments ``**kwargs`` provided
will be passed directly to `~numpy.linspace`.
"""
def __init__(self, *seeds: Sequence[int], num: int = 100, **kwargs) -> None:
# Initialize some variables
self._interpolator = None
self._is_uniform = None
# If three inputs are given, assume it's a user-provided grid
if len(seeds) == 3:
self._load_grid(seeds[0], seeds[1], seeds[2])
# If two inputs are given, assume they are start and stop arrays
# to create a new grid
# kwargs are passed to np.linspace in _make_grid()
elif len(seeds) == 2:
self._make_grid(seeds[0], seeds[1], num=num, **kwargs)
else:
raise TypeError(
f"{self.__class__.__name__} takes 2 or 3 "
f"positional arguments but {len(seeds)} were given"
)
def _validate(self) -> bool:
r"""
Checks to make sure that the grid parameters are
consistent with the coordinate system and units selected.
"""
return True
# A named tuple describing a key recognized by PlasmaPy to correspond to
# a particular physical quantity
RecognizedQuantity = namedtuple(
"RecognizedQuantities", ["key", "description", "unit"]
)
# These standard keys are used to refer to certain
# physical quantities. This dictionary also provides the expected unit.
_recognized_quantities_list = [
RecognizedQuantity("x", "x spatial position", u.m),
RecognizedQuantity("y", "y spatial position", u.m),
RecognizedQuantity("z", "z spatial position", u.m),
RecognizedQuantity("rho", "Mass density", u.kg / u.m**3),
RecognizedQuantity("E_x", "Electric field (x component)", u.V / u.m),
RecognizedQuantity("E_y", "Electric field (y component)", u.V / u.m),
RecognizedQuantity("E_z", "Electric field (z component)", u.V / u.m),
RecognizedQuantity("B_x", "Magnetic field (x component)", u.T),
RecognizedQuantity("B_y", "Magnetic field (y component)", u.T),
RecognizedQuantity("B_z", "Magnetic field (z component)", u.T),
RecognizedQuantity("phi", "Electric Scalar Potential", u.V),
]
# Create a dict of recognized quantities for fast access by key
_recognized_quantities = {}
for _rq in _recognized_quantities_list:
_recognized_quantities[_rq.key] = _rq
@property
def recognized_quantities(self):
r"""
A dictionary of standard key names representing particular physical
quantities. Using these keys allows these
quantities to be recognized automatically by other PlasmaPy functions.
Each entry contains a tuple containing a description and the unit
associated with the quantity.
"""
return self._recognized_quantities
def require_quantities(self, req_quantities, replace_with_zeros: bool = False):
r"""
Check to make sure that a list of required quantities are present.
Optionally, can create missing quantities and fill them with
an array of zeros.
Parameters
----------
req_quantities : `list` of `str`
A list of quantity keys that are required.
replace_with_zeros : `bool`, optional
If true, missing quantities will be replaced with an array
of zeros. If false, an exception will be raised instead.
The default is False.
Raises
------
KeyError
If ``replace_with_zeros`` is `False` and a required quantity
is missing.
KeyError
If ``replace_with_zeros`` is `True` but the
`~astropy.units.Quantity` is not in the list of recognized
quantities. In this case the units for the quantity are unknown,
so an array of zeros cannot be constructed.
"""
for rq in req_quantities:
# Error check that grid contains E and B variables required
if rq not in self.quantities:
# If missing, warn user and then replace with an array of zeros
if not replace_with_zeros:
raise KeyError(
f"{rq} is not specified for the provided "
"grid but is required."
)
elif rq not in self.recognized_quantities:
raise KeyError(
f"{rq} is not a recognized key, and "
"so cannot be automatically assumed "
"to be zero."
)
warnings.warn(
f"{rq} is not specified for the provided grid."
"This quantity will be assumed to be zero.",
RuntimeWarning,
)
unit = self.recognized_quantities[rq].unit
arg = {rq: np.zeros(self.shape) * unit}
self.add_quantities(**arg)
# *************************************************************************
# Fundamental properties of the grid
# *************************************************************************
def __repr__(self) -> str:
line_sep = "-----------------------------\n"
shape = list(self.shape)
coords = list(self.ds.coords.keys())
ax_units = self.units
ax_dtypes = [self.ds[i].dtype for i in coords]
coord_lbls = [f"{i}: {j}" for i, j in zip(coords, shape)]
s = f"*** Grid Summary ***\n{type(self)}\n"
s += f"Dimensions: ({', '.join(coord_lbls)})\n"
if self.is_uniform:
s += (
"Uniformly Spaced: (dax0, dax1, dax2) = "
f"({self.dax0:.3f}, {self.dax1:.3f}, {self.dax2:.3f})\n"
)
else:
s += "Non-Uniform Spacing\n"
s += line_sep + "Coordinates:\n"
for i in range(len(self.shape)):
s += f"\t-> {coords[i]} ({ax_units[i]}) {ax_dtypes[i]} ({shape[i]},)\n"
keys = self.quantities
rkeys = [k for k in keys if k in list(self.recognized_quantities.keys())]
nrkeys = [k for k in keys if k not in list(self.recognized_quantities.keys())]
s += line_sep + "Recognized Quantities:\n"
if not rkeys:
s += "-None-\n"
else:
for key in rkeys:
unit = self.ds[key].attrs["unit"]
dtype = self.ds[key].dtype
shape = self.ds[key].shape
s += f"\t-> {key} ({unit}) {dtype} {shape} \n"
s += line_sep + "Unrecognized Quantities:\n"
if not nrkeys:
s += "-None-\n"
else:
for key in nrkeys:
unit = self.ds[key].attrs["unit"]
dtype = self.ds[key].dtype
shape = self.ds[key].shape
s += f"\t-> {key} ({unit}) {dtype} {shape} \n"
return s
def __getitem__(self, key):
"""
Given a key, return the corresponding array as a `~astropy.units.Quantity`.
Returning with ``copy=False`` means that the array returned is a direct
reference to the underlying DataArray, so changes made will be reflected
in the underlying DataArray.
"""
return u.Quantity(self.ds[key].data, self.ds[key].attrs["unit"], copy=False)
@property
def is_uniform(self) -> bool:
"""
A boolean value reflecting whether or not the grid points are
uniformly spaced.
"""
if self._is_uniform is None:
raise ValueError(
"The `is_uniform` attribute is not accessible "
"before a grid has been loaded."
)
return self._is_uniform
@property
def shape(self):
r"""Shape of the grid."""
if self.is_uniform:
return (self.ax0.size, self.ax1.size, self.ax2.size)
return self.ds.coords["ax0"].shape
@property
def grids(self):
r"""
Three grids of vertex positions (in each coordinate), each having
shape (N0, N1, N2).
"""
if not self.is_uniform:
return (
self.ds["ax0"].data * self.unit0,
self.ds["ax1"].data * self.unit1,
self.ds["ax2"].data * self.unit2,
)
pts0, pts1, pts2 = np.meshgrid(self.ax0, self.ax1, self.ax2, indexing="ij")
return pts0, pts1, pts2
@property
def grid(self):
r"""
A single grid of vertex positions of shape (N0, N1, N2, 3).
Only defined for grids for which the ``unit`` property is defined.
"""
pts0, pts1, pts2 = self.grids
if self.is_uniform:
n0, n1, n2 = pts0.shape
grid = np.zeros([n0, n1, n2, 3]) * self.unit
else:
n = pts0.size
grid = np.zeros([n, 3]) * self.unit
grid[..., 0] = pts0
grid[..., 1] = pts1
grid[..., 2] = pts2
return grid
@property
def pts0(self):
r"""Array of positions in dimension 1."""
return self.grids[0]
@property
def pts1(self):
r"""Array of positions in dimension 2."""
return self.grids[1]
@property
def pts2(self):
r"""Array of positions in dimension 3."""
return self.grids[2]
@property
def units(self) -> list:
r"""A `list` of the units of each dimension."""
return self.ds.attrs["axis_units"]
@property
def unit0(self):
r"""Unit of dimension 1."""
return self.units[0]
@property
def unit1(self):
r"""Unit of dimension 2."""
return self.units[1]
@property
def unit2(self):
r"""Unit of dimension 3."""
return self.units[2]
@property
def unit(self):
r"""
The unit for the entire grid. Only valid if all dimensions of the
grid have the same units.
Raises
------
`ValueError`
If all grid dimensions do not have identical units.
"""
if self.units[0] == self.units[1] == self.units[2]:
return self.units[0]
else:
raise ValueError(
f"Array dimensions do not all have the same units: {self.units}"
)
# *************************************************************************
# 1D axes and step sizes (valid only for uniform grids)
# *************************************************************************
@property
def si_scale_factors(self) -> list[float]:
"""
3-element list containing unitless scale factors for converting
the corresponding axis from its stored units to SI.
"""
return self._si_factors
def _get_ax(self, *, axis: int, si: bool = False):
"""
Helper function for retrieving axis values.
Parameters
----------
axis: int
Axis index for axis of interest (e.g. ``0`` for :attr:`ax0`).
si: bool
(Default: `False`) If `True` then convert the axis values to
their SI equivalent.
Returns
-------
~numpy.ndarray or `~astropy.units.Quantity`
If ``si==True`` then return a unitless `~numpy.ndarray`.
If ``si==False`` then return a `~astropy.units.Quantity`
array with the original units.
Raises
------
ValueError
If the grid is not uniform.
"""
ax_name = f"ax{axis}"
if not self.is_uniform:
raise ValueError(
"The axis properties are only valid on uniformly spaced grids."
)
vals = self.ds.coords[ax_name].to_numpy()
return vals * self.si_scale_factors[axis] if si else vals * self.units[axis]
def _get_dax(self, *, axis: int, si: bool = False):
"""
Helper function for calculating grid spacing.
See Also
--------
plasmapy.plasma.grids.AbstractGrid._get_ax
"""
ax = self._get_ax(axis=axis, si=si)
return np.mean(np.gradient(ax))
@property
def _ax0_si(self):
"""
The :attr:`ax0` axis without units, but scaled such that its values
correspond to SI values.
Only valid for uniform grids.
"""
return self._get_ax(axis=0, si=True)
@property
def ax0(self):
r"""
First axis of the grid.
Only valid for uniform grids.
"""
return self._get_ax(axis=0)
@property
def _ax1_si(self):
"""
The :attr:`ax1` axis without units, but scaled such that its values
correspond to SI values.
Only valid for uniform grids.
"""
return self._get_ax(axis=1, si=True)
@property
def ax1(self):
r"""
Second axis of the grid.
Only valid for uniform grids.
"""
return self._get_ax(axis=1)
@property
def _ax2_si(self):
"""
The :attr:`ax2` axis without units, but scaled such that its values
correspond to SI values.
Only valid for uniform grids.
"""
return self._get_ax(axis=2, si=True)
@property
def ax2(self):
r"""
Third axis of the grid.
Only valid for uniform grids.
"""
return self._get_ax(axis=2)
@property
def _dax0_si(self):
"""
Grid step size along axis :attr:`ax0` without units and scaled such
that its values correspond to SI values.
Only valid for uniform grids.
"""
return self._get_dax(axis=0, si=True)
@property
def dax0(self):
r"""
Grid step size along axis :attr:`ax0`.
Only valid for uniform grids.
"""
return self._get_dax(axis=0)
@property
def _dax1_si(self):
"""
Grid step size along axis :attr:`ax1` without units and scaled such
that its values correspond to SI values.
Only valid for uniform grids.
"""
return self._get_dax(axis=1, si=True)
@property
def dax1(self):
r"""
Grid step size along axis :attr:`ax1`.
Only valid for uniform grids.
"""
return self._get_dax(axis=1)
@property
def _dax2_si(self):
"""
Grid step size along axis :attr:`ax2` without units and scaled such
that its values correspond to SI values.
Only valid for uniform grids.
"""
return self._get_dax(axis=2, si=True)
@property
def dax2(self):
r"""
Grid step size along axis :attr:`ax2`.
Only valid for uniform grids.
"""
return self._get_dax(axis=2)
# *************************************************************************
# Loading and creating grids
# *************************************************************************
def _load_grid(
self,
pts0: u.Quantity,
pts1: u.Quantity,
pts2: u.Quantity,
):
r"""
Initialize the grid object from a user-supplied grid.
Parameters
----------
grid{0,1,2} : `~astropy.units.Quantity` array, shape (n0, n1, n2)
Grids of coordinate positions.
**kwargs : `~astropy.units.Quantity` array, shape (n0, n1, n2)
Quantities defined on the grid.
"""
# Validate input
if pts0.shape != pts1.shape or pts0.shape != pts2.shape:
raise ValueError(
"Provided arrays of grid points are of unequal "
f"shape: pts0 = {pts0.shape}, "
f"pts1 = {pts1.shape}, "
f"pts2 = {pts2.shape}."
)
self._is_uniform = _detect_is_uniform_grid(pts0, pts1, pts2)
# Create dataset
self.ds = xr.Dataset()
self.ds.attrs["axis_units"] = [pts0.unit, pts1.unit, pts2.unit]
# Store the conversion factors for each axis to SI
self._si_factors = [
pts0.unit.si.scale,
pts1.unit.si.scale,
pts2.unit.si.scale,
]
if self.is_uniform:
self.ds.coords["ax0"] = pts0[:, 0, 0]
self.ds.coords["ax1"] = pts1[0, :, 0]
self.ds.coords["ax2"] = pts2[0, 0, :]
else:
mdx = pd.MultiIndex.from_arrays(
[pts0.flatten(), pts1.flatten(), pts2.flatten()],
names=["ax0", "ax1", "ax2"],
)
self.ds.coords["ax"] = mdx
# Check to make sure that the object created satisfies any
# requirements: eg. units correspond to the coordinate system
self._validate()
def add_quantities(self, **kwargs):
r"""
Adds a quantity to the dataset as a new DataArray.
Parameters
----------
**kwargs : key, array pairs
The key will be used as the dataset key, while the array holds the
quantity.
"""
for key, quantity in kwargs.items():
# Check key against a list of "known" keys with pre-defined
# meanings (eg. E_x, n_e) and raise a warning if a "non-standard"
# key is being used so the user is aware.
if key in self.recognized_quantities:
try:
quantity.to(self.recognized_quantities[key].unit)
except u.UnitConversionError as ex:
raise ValueError(
f"Units provided for {key} ({quantity.unit}) "
"are not compatible with the correct units "
f"for that recognized key ({self.recognized_quantities[key]})."
) from ex
else:
warnings.warn(
f"Warning: {key} is not recognized quantity key", stacklevel=2
)
if self.is_uniform:
dims = ["ax0", "ax1", "ax2"]
coords = {
"ax0": self.ds.coords["ax0"],
"ax1": self.ds.coords["ax1"],
"ax2": self.ds.coords["ax2"],
}
# If grid is non-uniform, flatten quantity
else:
quantity = quantity.flatten() # noqa: PLW2901
dims = ["ax"]
coords = {"ax": self.ds.coords["ax"]}
if quantity.shape != self.shape:
raise ValueError(
f"Shape of quantity '{key}' {quantity.shape} "
f"does not match the grid shape {self.shape}."
)
data = xr.DataArray(
quantity, dims=dims, coords=coords, attrs={"unit": quantity.unit}
)
self.ds[key] = data
@property
def quantities(self):
r"""
A list of the keys corresponding to the quantities currently
defined on the grid.
"""
return list(self.ds.data_vars)
def _make_grid( # noqa: C901, PLR0912
self,
start: Union[float, u.Quantity],
stop: Union[float, u.Quantity],
num: int = 100,
units=None,
**kwargs,
):
r"""
Creates a grid based on ``start``, ``stop``, and ``num`` values
in a manner that mirrors the interface of the `numpy.linspace`
function.
Parameters
----------
start : number (`~astropy.units.Quantity`) or an array, list, or
tuple of three of the same.
Starting values for each dimension. If one value is given,
the same value will be used for all three dimensions.
stop : number (`~astropy.units..Quantity`) or an array, list, or
tuple of three of the same.
End values for each dimension. If one value is given,
the same value will be used for all three dimensions.
num : `int` or `list` or `tuple` of three `int` objects, optional
The number of points in each dimension. If a single integer is
given, the same number of points will be used in each dimension.
The default is 100.
**kwargs : Additional arguments
Any additional arguments will be passed directly to
`numpy.linspace`.
"""
# Store variables in dict for validation
var = {"stop": stop, "start": start, "num": num}
# Ensure that start and stop end up as a list of three u.Quantity objs
# and num a list of three integers
# TODO: python3.10: simplify using structural pattern matching
for k in ("start", "stop"):
# Convert tuple to list
if isinstance(var[k], tuple):
var[k] = list(var[k])
if isinstance(var[k], list):
if len(var[k]) == 1:
var[k] = var[k] * 3
# Make sure it's a list of quantities
if not all(isinstance(v, u.Quantity) for v in var[k]):
raise TypeError(
f"The argument `{k}` must be an "
"`astropy.units.Quantity` or a list of same, "
f"but a {type(var[k])} was given."
)
elif isinstance(var[k], u.Quantity):
# Extend to 3 elements if only one is given
# Case of >1 but != 3 is handled later
var[k] = [var[k]] * 3 if var[k].size == 1 else list(var[k])
else:
raise TypeError(
f"The argument `{k}` must be an "
"`astropy.units.Quantity` or a list of same, "
f"but a {type(var[k])} was given."
)
# Convert tuple to list
if isinstance(var["num"], tuple):
var["num"] = list(var["num"])
if isinstance(var["num"], list):
if len(var["num"]) == 1:
var["num"] = var["num"] * 3
elif isinstance(var["num"], int):
var["num"] = [var["num"]] * 3
else:
raise TypeError(
f"The argument `num` must be an int or list of "
f"same, but a {type(var[k])} was given."
)
# Check to make sure all lists now contain three values
# (throws exception if user supplies a list of two, say)
for k in var:
if len(var[k]) != 3:
raise TypeError(
f"{k} must be either a single value or a "
"list of three values, but "
f"({len(var[k])} values were given)."
)
# Take variables back out of dict
start = var["start"]
stop = var["stop"]
num = var["num"]
# Extract units from input arrays (if they are there), then
# remove the units from those arrays
units = []
for i in range(3):
# Determine unit for dimension
unit = start[i].unit
units.append(unit)
# Attempt to convert stop unit to start unit
try:
stop[i] = stop[i].to(unit)
except u.UnitConversionError as ex:
raise ValueError(
f"Units of {stop[i]} and {unit} are not compatible"
) from ex
# strip units
stop[i] = stop[i].value
start[i] = start[i].value
# Create coordinate mesh
pts0, pts1, pts2 = self._make_mesh(start, stop, num, **kwargs)
# Load into the dataset using the _load_grid function
self._load_grid(
pts0 * units[0],
pts1 * units[1],
pts2 * units[2],
)
def _make_mesh(self, start, stop, num: int, **kwargs):
r"""
Creates mesh as part of _make_grid(). Separated into its own function
so it can be re-implemented to make non-uniformly spaced meshes.
"""
# Construct the axis arrays
ax0 = np.linspace(start[0], stop[0], num=num[0], **kwargs)
ax1 = np.linspace(start[1], stop[1], num=num[1], **kwargs)
ax2 = np.linspace(start[2], stop[2], num=num[2], **kwargs)
# Construct the coordinate arrays
pts0, pts1, pts2 = np.meshgrid(ax0, ax1, ax2, indexing="ij")
return pts0, pts1, pts2
# *************************************************************************
# Methods
# *************************************************************************
def on_grid(self, pos):
r"""
Given a list of positions, determines which are in the region
bounded by the grid points.
For non-uniform grids, "on grid" is defined as being bounded by
grid points in all axes.
Parameters
----------
pos : `~numpy.ndarray` or `~astropy.units.Quantity` array, shape (n,3)
An array of positions in space, where the second dimension
corresponds to the three dimensions of the grid.
"""
if hasattr(pos, "unit"):
pos = pos.si.value
# Find the bounds
if self.is_uniform:
ax0_min, ax0_max = np.min(self.ax0.si.value), np.max(self.ax0.si.value)
ax1_min, ax1_max = np.min(self.ax1.si.value), np.max(self.ax1.si.value)
ax2_min, ax2_max = np.min(self.ax2.si.value), np.max(self.ax2.si.value)
else:
pts0, pts1, pts2 = self.grids
ax0_min, ax0_max = np.min(self.pts0).si.value, np.max(self.pts0).si.value
ax1_min, ax1_max = np.min(self.pts1).si.value, np.max(self.pts1).si.value
ax2_min, ax2_max = np.min(self.pts2).si.value, np.max(self.pts2).si.value
# Check each point elementwise against the bounds
on_grid = (
np.greater(ax0_min, pos[:, 0]).astype(np.int8)
+ np.less(ax0_max, pos[:, 0]).astype(np.int8)
+ np.greater(ax1_min, pos[:, 1]).astype(np.int8)
+ np.less(ax1_max, pos[:, 1]).astype(np.int8)
+ np.greater(ax2_min, pos[:, 2]).astype(np.int8)
+ np.less(ax2_max, pos[:, 2]).astype(np.int8)
)
return np.where(on_grid == 0, True, False) # noqa: FBT003
@abstractmethod
def vector_intersects(self, p1, p2):
r"""
`True` if the vector from ``p1`` to ``p2`` intersects the grid,
and `False` otherwise.
The definition of 'intersects' is determined by the implementation
for each subclass.
"""
...
# *************************************************************************
# Interpolators
# *************************************************************************
# This property holds the list of quantity keys currently being interpolated
# It's used in the following cached properties
_interp_args = []
@cached_property
def _interp_quantities(self):
r"""Create a dimensionless array of quantities to be interpolated."""
nargs = len(self._interp_args)
# Load the arrays to be interpolated from and their units
if self.is_uniform:
nx, ny, nz = self.shape
_interp_quantities = np.zeros([nx, ny, nz, nargs])
else:
npoints = self.shape[0]
_interp_quantities = np.zeros([npoints, nargs])
for j, arg in enumerate(self._interp_args):
_interp_quantities[..., j] = self.ds[arg].to_numpy()
return _interp_quantities
@cached_property
def _interp_units(self):
r"""
Create a list of the units corresponding to the last dimension
in the `_interp_quantities` array.
"""
return [self.ds[arg].attrs["unit"] for arg in self._interp_args]
@abstractmethod
def nearest_neighbor_interpolator(
self, pos: Union[np.ndarray, u.Quantity], *args, persistent: bool = False
):
r"""
Interpolate values on the grid using a nearest-neighbor scheme with
no higher-order weighting.
Parameters
----------
pos : `~numpy.ndarray` or `~astropy.units.Quantity` array, shape (n,3)
An array of positions in space, where the second dimension
corresponds to the three dimensions of the grid. If an
`~numpy.ndarray` is provided, units will be assumed to match
those of the grid.
*args : `str`
Strings that correspond to DataArrays in the dataset
persistent : `bool`
If `True`, the interpolator will assume the grid and its
contents have not changed since the last interpolation. This
substantially speeds up the interpolation when many
interpolations are performed on the same grid in a loop.
``persistent`` overrides to `False` if the arguments list
has changed since the last call.
"""
...
def _persistent_interpolator_setup(self, pos, args, persistent):
r"""
Setup common to all persistent interpolators.
Parameters
----------
pos : `~numpy.ndarray` or `~astropy.units.Quantity` array, shape (n,3)
An array of positions in space, where the second dimension
corresponds to the three dimensions of the grid. If a
`~numpy.ndarray` is provided, units will be assumed to match
those of the grid.
args : `str`
Strings that correspond to DataArrays in the dataset
persistent : `bool`
If `True`, the interpolator will assume the grid and its
contents have not changed since the last interpolation. This
substantially speeds up the interpolation when many
interpolations are performed on the same grid in a loop.
``persistent`` overrides to `False` if the arguments list
has changed since the last call.
Returns
-------
pos: `~numpy.ndarray`
Position array with dimensions fixed, units converted to
standard and stripped.
args : `str`
Strings that correspond to DataArrays in the dataset
persistent : `bool`
If `True`, the interpolator will assume the grid and its
contents have not changed since the last interpolation. This
substantially speeds up the interpolation when many
interpolations are performed on the same grid in a loop.
``persistent`` overrides to `False` if the arguments list
has changed since the last call.
Raises
------
KeyError
A KeyError is raised if one of the args does not correspond
to a DataArray in the DataSet.
"""
# Condition pos
if isinstance(pos, u.Quantity):
pos = pos.to(u.m).value
elif self.unit != u.m:
pos *= self.unit.si.scale
# If a single point was given, add empty dimension
if pos.ndim == 1:
pos = np.reshape(pos, [1, 3])
# -- Validate args --
# must be np.ndarray or u.Quantity arrays of same shape as grid
for arg in args:
if arg not in self.quantities:
raise KeyError(
"Quantity arguments must correspond to "
"DataArrays in the DataSet. "
f"{arg} was not found. "
f"Existing keys are: {self.quantities}"
)