-
Notifications
You must be signed in to change notification settings - Fork 271
/
data_containers.py
2047 lines (1817 loc) · 79.1 KB
/
data_containers.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
"""
Various non-grid data containers.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
import itertools
import uuid
import numpy as np
import weakref
import shelve
from collections import defaultdict
from contextlib import contextmanager
from yt.data_objects.particle_io import particle_handler_registry
from yt.fields.derived_field import \
DerivedField
from yt.frontends.ytdata.utilities import \
save_as_dataset
from yt.funcs import \
get_output_filename, \
mylog, \
ensure_list, \
fix_axis, \
iterable
from yt.units.unit_object import UnitParseError
from yt.units.yt_array import \
YTArray, \
YTQuantity
import yt.units.dimensions as ytdims
from yt.utilities.exceptions import \
YTUnitConversionError, \
YTFieldUnitError, \
YTFieldUnitParseError, \
YTSpatialFieldUnitError, \
YTCouldNotGenerateField, \
YTFieldNotParseable, \
YTFieldNotFound, \
YTFieldTypeNotFound, \
YTDataSelectorNotImplemented, \
YTDimensionalityError, \
YTBooleanObjectError, \
YTBooleanObjectsWrongDataset
from yt.utilities.lib.marching_cubes import \
march_cubes_grid, march_cubes_grid_flux
from yt.utilities.parallel_tools.parallel_analysis_interface import \
ParallelAnalysisInterface
from yt.utilities.parameter_file_storage import \
ParameterFileStore
from yt.utilities.amr_kdtree.api import \
AMRKDTree
from .derived_quantities import DerivedQuantityCollection
from yt.fields.field_exceptions import \
NeedsGridType
import yt.geometry.selection_routines
from yt.geometry.selection_routines import \
compose_selector
from yt.extern.six import add_metaclass, string_types
from yt.data_objects.field_data import YTFieldData
from yt.data_objects.profiles import create_profile
data_object_registry = {}
def force_array(item, shape):
try:
return item.copy()
except AttributeError:
if item:
return np.ones(shape, dtype='bool')
else:
return np.zeros(shape, dtype='bool')
def restore_field_information_state(func):
"""
A decorator that takes a function with the API of (self, grid, field)
and ensures that after the function is called, the field_parameters will
be returned to normal.
"""
def save_state(self, grid, field=None, *args, **kwargs):
old_params = grid.field_parameters
grid.field_parameters = self.field_parameters
tr = func(self, grid, field, *args, **kwargs)
grid.field_parameters = old_params
return tr
return save_state
def sanitize_weight_field(ds, field, weight):
field_object = ds._get_field_info(field)
if weight is None:
if field_object.particle_type is True:
weight_field = (field_object.name[0], 'particle_ones')
else:
weight_field = ('index', 'ones')
else:
weight_field = weight
return weight_field
class RegisteredDataContainer(type):
def __init__(cls, name, b, d):
type.__init__(cls, name, b, d)
if hasattr(cls, "_type_name") and not cls._skip_add:
data_object_registry[cls._type_name] = cls
@add_metaclass(RegisteredDataContainer)
class YTDataContainer(object):
"""
Generic YTDataContainer container. By itself, will attempt to
generate field, read fields (method defined by derived classes)
and deal with passing back and forth field parameters.
"""
_chunk_info = None
_num_ghost_zones = 0
_con_args = ()
_skip_add = False
_container_fields = ()
_tds_attrs = ()
_tds_fields = ()
_field_cache = None
_index = None
def __init__(self, ds, field_parameters):
"""
Typically this is never called directly, but only due to inheritance.
It associates a :class:`~yt.data_objects.api.Dataset` with the class,
sets its initial set of fields, and the remainder of the arguments
are passed as field_parameters.
"""
# ds is typically set in the new object type created in Dataset._add_object_class
# but it can also be passed as a parameter to the constructor, in which case it will
# override the default. This code ensures it is never not set.
if ds is not None:
self.ds = ds
else:
if not hasattr(self, "ds"):
raise RuntimeError("Error: ds must be set either through class type or parameter to the constructor")
self._current_particle_type = "all"
self._current_fluid_type = self.ds.default_fluid_type
self.ds.objects.append(weakref.proxy(self))
mylog.debug("Appending object to %s (type: %s)", self.ds, type(self))
self.field_data = YTFieldData()
self._default_field_parameters = {
'center': self.ds.arr(np.zeros(3, dtype='float64'), 'cm'),
'bulk_velocity': self.ds.arr(np.zeros(3, dtype='float64'), 'cm/s'),
'normal': self.ds.arr([0.0, 0.0, 1.0], ''),
}
if field_parameters is None: field_parameters = {}
self._set_default_field_parameters()
for key, val in field_parameters.items():
self.set_field_parameter(key, val)
@property
def pf(self):
return getattr(self, 'ds', None)
@property
def index(self):
if self._index is not None:
return self._index
self._index = self.ds.index
return self._index
def _debug(self):
"""
When called from within a derived field, this will run pdb. However,
during field detection, it will not. This allows you to more easily
debug fields that are being called on actual objects.
"""
import pdb
pdb.set_trace()
def _set_default_field_parameters(self):
self.field_parameters = {}
for k,v in self._default_field_parameters.items():
self.set_field_parameter(k,v)
def _is_default_field_parameter(self, parameter):
if parameter not in self._default_field_parameters:
return False
return self._default_field_parameters[parameter] is \
self.field_parameters[parameter]
def apply_units(self, arr, units):
return self.ds.arr(arr, input_units = units)
def _set_center(self, center):
if center is None:
self.center = None
return
elif isinstance(center, YTArray):
self.center = self.ds.arr(center.copy())
self.center.convert_to_units('code_length')
elif isinstance(center, (list, tuple, np.ndarray)):
if isinstance(center[0], YTQuantity):
self.center = self.ds.arr([c.copy() for c in center])
self.center.convert_to_units('code_length')
else:
self.center = self.ds.arr(center, 'code_length')
elif isinstance(center, string_types):
if center.lower() in ("c", "center"):
self.center = self.ds.domain_center
# is this dangerous for race conditions?
elif center.lower() in ("max", "m"):
self.center = self.ds.find_max(("gas", "density"))[1]
elif center.startswith("max_"):
self.center = self.ds.find_max(center[4:])[1]
else:
self.center = self.ds.arr(center, 'code_length', dtype='float64')
self.set_field_parameter('center', self.center)
def get_field_parameter(self, name, default=None):
"""
This is typically only used by derived field functions, but
it returns parameters used to generate fields.
"""
if name in self.field_parameters:
return self.field_parameters[name]
else:
return default
def set_field_parameter(self, name, val):
"""
Here we set up dictionaries that get passed up and down and ultimately
to derived fields.
"""
self.field_parameters[name] = val
def has_field_parameter(self, name):
"""
Checks if a field parameter is set.
"""
return name in self.field_parameters
def convert(self, datatype):
"""
This will attempt to convert a given unit to cgs from code units.
It either returns the multiplicative factor or throws a KeyError.
"""
return self.ds[datatype]
def clear_data(self):
"""
Clears out all data from the YTDataContainer instance, freeing memory.
"""
self.field_data.clear()
def has_key(self, key):
"""
Checks if a data field already exists.
"""
return key in self.field_data
def keys(self):
return self.field_data.keys()
def _reshape_vals(self, arr):
return arr
def __getitem__(self, key):
"""
Returns a single field. Will add if necessary.
"""
f = self._determine_fields([key])[0]
if f not in self.field_data and key not in self.field_data:
if f in self._container_fields:
self.field_data[f] = \
self.ds.arr(self._generate_container_field(f))
return self.field_data[f]
else:
self.get_data(f)
# fi.units is the unit expression string. We depend on the registry
# hanging off the dataset to define this unit object.
# Note that this is less succinct so that we can account for the case
# when there are, for example, no elements in the object.
rv = self.field_data.get(f, None)
if rv is None:
if isinstance(f, tuple):
fi = self.ds._get_field_info(*f)
elif isinstance(f, bytes):
fi = self.ds._get_field_info("unknown", f)
rv = self.ds.arr(self.field_data[key], fi.units)
return rv
def __setitem__(self, key, val):
"""
Sets a field to be some other value.
"""
self.field_data[key] = val
def __delitem__(self, key):
"""
Deletes a field
"""
if key not in self.field_data:
key = self._determine_fields(key)[0]
del self.field_data[key]
def _generate_field(self, field):
ftype, fname = field
finfo = self.ds._get_field_info(*field)
with self._field_type_state(ftype, finfo):
if fname in self._container_fields:
tr = self._generate_container_field(field)
if finfo.particle_type: # This is a property now
tr = self._generate_particle_field(field)
else:
tr = self._generate_fluid_field(field)
if tr is None:
raise YTCouldNotGenerateField(field, self.ds)
return tr
def _generate_fluid_field(self, field):
# First we check the validator
ftype, fname = field
finfo = self.ds._get_field_info(ftype, fname)
if self._current_chunk is None or \
self._current_chunk.chunk_type != "spatial":
gen_obj = self
else:
gen_obj = self._current_chunk.objs[0]
gen_obj.field_parameters = self.field_parameters
try:
finfo.check_available(gen_obj)
except NeedsGridType as ngt_exception:
rv = self._generate_spatial_fluid(field, ngt_exception.ghost_zones)
else:
rv = finfo(gen_obj)
return rv
def _generate_spatial_fluid(self, field, ngz):
finfo = self.ds._get_field_info(*field)
if finfo.units is None:
raise YTSpatialFieldUnitError(field)
units = finfo.units
rv = self.ds.arr(np.empty(self.ires.size, dtype="float64"), units)
ind = 0
if ngz == 0:
deps = self._identify_dependencies([field], spatial = True)
deps = self._determine_fields(deps)
for io_chunk in self.chunks([], "io", cache = False):
for i,chunk in enumerate(self.chunks([], "spatial", ngz = 0,
preload_fields = deps)):
o = self._current_chunk.objs[0]
with o._activate_cache():
ind += o.select(self.selector, self[field], rv, ind)
else:
chunks = self.index._chunk(self, "spatial", ngz = ngz)
for i, chunk in enumerate(chunks):
with self._chunked_read(chunk):
gz = self._current_chunk.objs[0]
gz.field_parameters = self.field_parameters
wogz = gz._base_grid
ind += wogz.select(
self.selector,
gz[field][ngz:-ngz, ngz:-ngz, ngz:-ngz],
rv, ind)
return rv
def _generate_particle_field(self, field):
# First we check the validator
ftype, fname = field
if self._current_chunk is None or \
self._current_chunk.chunk_type != "spatial":
gen_obj = self
else:
gen_obj = self._current_chunk.objs[0]
try:
finfo = self.ds._get_field_info(*field)
finfo.check_available(gen_obj)
except NeedsGridType as ngt_exception:
if ngt_exception.ghost_zones != 0:
raise NotImplementedError
size = self._count_particles(ftype)
rv = self.ds.arr(np.empty(size, dtype="float64"), finfo.units)
ind = 0
for io_chunk in self.chunks([], "io", cache = False):
for i, chunk in enumerate(self.chunks(field, "spatial")):
x, y, z = (self[ftype, 'particle_position_%s' % ax]
for ax in 'xyz')
if x.size == 0: continue
mask = self._current_chunk.objs[0].select_particles(
self.selector, x, y, z)
if mask is None: continue
# This requests it from the grid and does NOT mask it
data = self[field][mask]
rv[ind:ind+data.size] = data
ind += data.size
else:
with self._field_type_state(ftype, finfo, gen_obj):
rv = self.ds._get_field_info(*field)(gen_obj)
return rv
def _count_particles(self, ftype):
for (f1, f2), val in self.field_data.items():
if f1 == ftype:
return val.size
size = 0
for io_chunk in self.chunks([], "io", cache = False):
for i,chunk in enumerate(self.chunks([], "spatial")):
x, y, z = (self[ftype, 'particle_position_%s' % ax]
for ax in 'xyz')
if x.size == 0: continue
size += self._current_chunk.objs[0].count_particles(
self.selector, x, y, z)
return size
def _generate_container_field(self, field):
raise NotImplementedError
def _parameter_iterate(self, seq):
for obj in seq:
old_fp = obj.field_parameters
obj.field_parameters = self.field_parameters
yield obj
obj.field_parameters = old_fp
_key_fields = None
def write_out(self, filename, fields=None, format="%0.16e"):
if fields is None: fields=sorted(self.field_data.keys())
if self._key_fields is None: raise ValueError
field_order = self._key_fields[:]
for field in field_order: self[field]
field_order += [field for field in fields if field not in field_order]
fid = open(filename,"w")
fid.write("\t".join(["#"] + field_order + ["\n"]))
field_data = np.array([self.field_data[field] for field in field_order])
for line in range(field_data.shape[1]):
field_data[:,line].tofile(fid, sep="\t", format=format)
fid.write("\n")
fid.close()
def save_object(self, name, filename = None):
"""
Save an object. If *filename* is supplied, it will be stored in
a :mod:`shelve` file of that name. Otherwise, it will be stored via
:meth:`yt.data_objects.api.GridIndex.save_object`.
"""
if filename is not None:
ds = shelve.open(filename, protocol=-1)
if name in ds:
mylog.info("Overwriting %s in %s", name, filename)
ds[name] = self
ds.close()
else:
self.index.save_object(self, name)
def to_dataframe(self, fields = None):
r"""Export a data object to a pandas DataFrame.
This function will take a data object and construct from it and
optionally a list of fields a pandas DataFrame object. If pandas is
not importable, this will raise ImportError.
Parameters
----------
fields : list of strings or tuple field names, default None
If this is supplied, it is the list of fields to be exported into
the data frame. If not supplied, whatever fields presently exist
will be used.
Returns
-------
df : DataFrame
The data contained in the object.
Examples
--------
>>> dd = ds.all_data()
>>> df1 = dd.to_dataframe(["density", "temperature"])
>>> dd["velocity_magnitude"]
>>> df2 = dd.to_dataframe()
"""
import pandas as pd
data = {}
if fields is not None:
for f in fields:
data[f] = self[f]
else:
data.update(self.field_data)
df = pd.DataFrame(data)
return df
def save_as_dataset(self, filename=None, fields=None):
r"""Export a data object to a reloadable yt dataset.
This function will take a data object and output a dataset
containing either the fields presently existing or fields
given in the ``fields`` list. The resulting dataset can be
reloaded as a yt dataset.
Parameters
----------
filename : str, optional
The name of the file to be written. If None, the name
will be a combination of the original dataset and the type
of data container.
fields : list of string or tuple field names, optional
If this is supplied, it is the list of fields to be saved to
disk. If not supplied, all the fields that have been queried
will be saved.
Returns
-------
filename : str
The name of the file that has been created.
Examples
--------
>>> import yt
>>> ds = yt.load("enzo_tiny_cosmology/DD0046/DD0046")
>>> sp = ds.sphere(ds.domain_center, (10, "Mpc"))
>>> fn = sp.save_as_dataset(fields=["density", "temperature"])
>>> sphere_ds = yt.load(fn)
>>> # the original data container is available as the data attribute
>>> print (sds.data["density"])
[ 4.46237613e-32 4.86830178e-32 4.46335118e-32 ..., 6.43956165e-30
3.57339907e-30 2.83150720e-30] g/cm**3
>>> ad = sphere_ds.all_data()
>>> print (ad["temperature"])
[ 1.00000000e+00 1.00000000e+00 1.00000000e+00 ..., 4.40108359e+04
4.54380547e+04 4.72560117e+04] K
"""
keyword = "%s_%s" % (str(self.ds), self._type_name)
filename = get_output_filename(filename, keyword, ".h5")
data = {}
if fields is not None:
for f in self._determine_fields(fields):
data[f] = self[f]
else:
data.update(self.field_data)
# get the extra fields needed to reconstruct the container
tds_fields = tuple(self._determine_fields(list(self._tds_fields)))
for f in [f for f in self._container_fields + tds_fields \
if f not in data]:
data[f] = self[f]
data_fields = list(data.keys())
need_grid_positions = False
need_particle_positions = False
ptypes = []
ftypes = {}
for field in data_fields:
if field in self._container_fields:
ftypes[field] = "grid"
need_grid_positions = True
elif self.ds.field_info[field].particle_type:
if field[0] not in ptypes:
ptypes.append(field[0])
ftypes[field] = field[0]
need_particle_positions = True
else:
ftypes[field] = "grid"
need_grid_positions = True
# projections and slices use px and py, so don't need positions
if self._type_name in ["cutting", "proj", "slice"]:
need_grid_positions = False
if need_particle_positions:
for ax in "xyz":
for ptype in ptypes:
p_field = (ptype, "particle_position_%s" % ax)
if p_field in self.ds.field_info and p_field not in data:
data_fields.append(field)
ftypes[p_field] = p_field[0]
data[p_field] = self[p_field]
if need_grid_positions:
for ax in "xyz":
g_field = ("index", ax)
if g_field in self.ds.field_info and g_field not in data:
data_fields.append(g_field)
ftypes[g_field] = "grid"
data[g_field] = self[g_field]
g_field = ("index", "d" + ax)
if g_field in self.ds.field_info and g_field not in data:
data_fields.append(g_field)
ftypes[g_field] = "grid"
data[g_field] = self[g_field]
extra_attrs = dict([(arg, getattr(self, arg, None))
for arg in self._con_args + self._tds_attrs])
extra_attrs["con_args"] = self._con_args
extra_attrs["data_type"] = "yt_data_container"
extra_attrs["container_type"] = self._type_name
extra_attrs["dimensionality"] = self._dimensionality
save_as_dataset(self.ds, filename, data, field_types=ftypes,
extra_attrs=extra_attrs)
return filename
def to_glue(self, fields, label="yt", data_collection=None):
"""
Takes specific *fields* in the container and exports them to
Glue (http://www.glueviz.org) for interactive
analysis. Optionally add a *label*. If you are already within
the Glue environment, you can pass a *data_collection* object,
otherwise Glue will be started.
"""
from glue.core import DataCollection, Data
from glue.qt.glue_application import GlueApplication
gdata = Data(label=label)
for component_name in fields:
gdata.add_component(self[component_name], component_name)
if data_collection is None:
dc = DataCollection([gdata])
app = GlueApplication(dc)
app.start()
else:
data_collection.append(gdata)
# Numpy-like Operations
def argmax(self, field, axis=None):
r"""Return the values at which the field is maximized.
This will, in a parallel-aware fashion, find the maximum value and then
return to you the values at that maximum location that are requested
for "axis". By default it will return the spatial positions (in the
natural coordinate system), but it can be any field
Parameters
----------
field : string or tuple field name
The field to maximize.
axis : string or list of strings, optional
If supplied, the fields to sample along; if not supplied, defaults
to the coordinate fields. This can be the name of the coordinate
fields (i.e., 'x', 'y', 'z') or a list of fields, but cannot be 0,
1, 2.
Returns
-------
A list of YTQuantities as specified by the axis argument.
Examples
--------
>>> temp_at_max_rho = reg.argmax("density", axis="temperature")
>>> max_rho_xyz = reg.argmax("density")
>>> t_mrho, v_mrho = reg.argmax("density", axis=["temperature",
... "velocity_magnitude"])
>>> x, y, z = reg.argmax("density")
"""
if axis is None:
mv, pos0, pos1, pos2 = self.quantities.max_location(field)
return pos0, pos1, pos2
if isinstance(axis, string_types):
axis = [axis]
rv = self.quantities.sample_at_max_field_values(field, axis)
if len(rv) == 2:
return rv[1]
return rv[1:]
def argmin(self, field, axis=None):
r"""Return the values at which the field is minimized.
This will, in a parallel-aware fashion, find the minimum value and then
return to you the values at that minimum location that are requested
for "axis". By default it will return the spatial positions (in the
natural coordinate system), but it can be any field
Parameters
----------
field : string or tuple field name
The field to minimize.
axis : string or list of strings, optional
If supplied, the fields to sample along; if not supplied, defaults
to the coordinate fields. This can be the name of the coordinate
fields (i.e., 'x', 'y', 'z') or a list of fields, but cannot be 0,
1, 2.
Returns
-------
A list of YTQuantities as specified by the axis argument.
Examples
--------
>>> temp_at_min_rho = reg.argmin("density", axis="temperature")
>>> min_rho_xyz = reg.argmin("density")
>>> t_mrho, v_mrho = reg.argmin("density", axis=["temperature",
... "velocity_magnitude"])
>>> x, y, z = reg.argmin("density")
"""
if axis is None:
mv, pos0, pos1, pos2 = self.quantities.min_location(field)
return pos0, pos1, pos2
rv = self.quantities.sample_at_min_field_values(field, axis)
if len(rv) == 2:
return rv[1]
return rv[1:]
def _compute_extrema(self, field):
if self._extrema_cache is None:
self._extrema_cache = {}
if field not in self._extrema_cache:
# Note we still need to call extrema for each field, as of right
# now
mi, ma = self.quantities.extrema(field)
self._extrema_cache[field] = (mi, ma)
return self._extrema_cache[field]
_extrema_cache = None
def max(self, field, axis=None):
r"""Compute the maximum of a field, optionally along an axis.
This will, in a parallel-aware fashion, compute the maximum of the
given field. Supplying an axis will result in a return value of a
YTProjection, with method 'mip' for maximum intensity. If the max has
already been requested, it will use the cached extrema value.
Parameters
----------
field : string or tuple field name
The field to maximize.
axis : string, optional
If supplied, the axis to project the maximum along.
Returns
-------
Either a scalar or a YTProjection.
Examples
--------
>>> max_temp = reg.max("temperature")
>>> max_temp_proj = reg.max("temperature", axis="x")
"""
if axis is None:
rv = ()
fields = ensure_list(field)
for f in fields:
rv += (self._compute_extrema(f)[1],)
if len(fields) == 1:
return rv[0]
else:
return rv
elif axis in self.ds.coordinates.axis_name:
r = self.ds.proj(field, axis, data_source=self, method="mip")
return r
else:
raise NotImplementedError("Unknown axis %s" % axis)
def min(self, field, axis=None):
r"""Compute the minimum of a field.
This will, in a parallel-aware fashion, compute the minimum of the
given field. Supplying an axis is not currently supported. If the max
has already been requested, it will use the cached extrema value.
Parameters
----------
field : string or tuple field name
The field to minimize.
axis : string, optional
If supplied, the axis to compute the minimum along.
Returns
-------
Scalar.
Examples
--------
>>> min_temp = reg.min("temperature")
"""
if axis is None:
rv = ()
fields = ensure_list(field)
for f in ensure_list(fields):
rv += (self._compute_extrema(f)[0],)
if len(fields) == 1:
return rv[0]
else:
return rv
return rv
elif axis in self.ds.coordinates.axis_name:
raise NotImplementedError("Minimum intensity projection not"
" implemented.")
else:
raise NotImplementedError("Unknown axis %s" % axis)
def std(self, field, weight=None):
"""Compute the variance of a field.
This will, in a parallel-ware fashion, compute the variance of
the given field.
Parameters
----------
field : string or tuple field name
The field to calculate the variance of
weight : string or tuple field name
The field to weight the variance calculation by. Defaults to
unweighted if unset.
Returns
-------
Scalar
"""
weight_field = sanitize_weight_field(self.ds, field, weight)
return self.quantities.weighted_variance(field, weight_field)[0]
def ptp(self, field):
r"""Compute the range of values (maximum - minimum) of a field.
This will, in a parallel-aware fashion, compute the "peak-to-peak" of
the given field.
Parameters
----------
field : string or tuple field name
The field to average.
Returns
-------
Scalar
Examples
--------
>>> rho_range = reg.ptp("density")
"""
ex = self._compute_extrema(field)
return ex[1] - ex[0]
def profile(self, bin_fields, fields, n_bins=64,
extrema=None, logs=None, units=None,
weight_field="cell_mass",
accumulation=False, fractional=False,
deposition='ngp'):
r"""
Create a 1, 2, or 3D profile object from this data_source.
The dimensionality of the profile object is chosen by the number of
fields given in the bin_fields argument. This simply calls
:func:`yt.data_objects.profiles.create_profile`.
Parameters
----------
bin_fields : list of strings
List of the binning fields for profiling.
fields : list of strings
The fields to be profiled.
n_bins : int or list of ints
The number of bins in each dimension. If None, 64 bins for
each bin are used for each bin field.
Default: 64.
extrema : dict of min, max tuples
Minimum and maximum values of the bin_fields for the profiles.
The keys correspond to the field names. Defaults to the extrema
of the bin_fields of the dataset. If a units dict is provided, extrema
are understood to be in the units specified in the dictionary.
logs : dict of boolean values
Whether or not to log the bin_fields for the profiles.
The keys correspond to the field names. Defaults to the take_log
attribute of the field.
units : dict of strings
The units of the fields in the profiles, including the bin_fields.
weight_field : str or tuple field identifier
The weight field for computing weighted average for the profile
values. If None, the profile values are sums of the data in
each bin.
accumulation : bool or list of bools
If True, the profile values for a bin n are the cumulative sum of
all the values from bin 0 to n. If -True, the sum is reversed so
that the value for bin n is the cumulative sum from bin N (total bins)
to n. If the profile is 2D or 3D, a list of values can be given to
control the summation in each dimension independently.
Default: False.
fractional : If True the profile values are divided by the sum of all
the profile data such that the profile represents a probability
distribution function.
deposition : Controls the type of deposition used for ParticlePhasePlots.
Valid choices are 'ngp' and 'cic'. Default is 'ngp'. This parameter is
ignored the if the input fields are not of particle type.
Examples
--------
Create a 1d profile. Access bin field from profile.x and field
data from profile[<field_name>].
>>> ds = load("DD0046/DD0046")
>>> ad = ds.all_data()
>>> profile = ad.profile(ad, [("gas", "density")],
... [("gas", "temperature"),
... ("gas", "velocity_x")])
>>> print (profile.x)
>>> print (profile["gas", "temperature"])
>>> plot = profile.plot()
"""
p = create_profile(self, bin_fields, fields, n_bins,
extrema, logs, units, weight_field, accumulation,
fractional, deposition)
return p
def mean(self, field, axis=None, weight=None):
r"""Compute the mean of a field, optionally along an axis, with a
weight.
This will, in a parallel-aware fashion, compute the mean of the
given field. If an axis is supplied, it will return a projection,
where the weight is also supplied. By default the weight field will be
"ones" or "particle_ones", depending on the field being averaged,
resulting in an unweighted average.
Parameters
----------
field : string or tuple field name
The field to average.
axis : string, optional
If supplied, the axis to compute the mean along (i.e., to project
along)
weight : string, optional
The field to use as a weight.
Returns
-------
Scalar or YTProjection.
Examples
--------
>>> avg_rho = reg.mean("density", weight="cell_volume")
>>> rho_weighted_T = reg.mean("temperature", axis="y", weight="density")
"""
weight_field = sanitize_weight_field(self.ds, field, weight)
if axis in self.ds.coordinates.axis_name:
r = self.ds.proj(field, axis, data_source=self,
weight_field=weight_field)
elif axis is None:
r = self.quantities.weighted_average_quantity(field, weight_field)
else:
raise NotImplementedError("Unknown axis %s" % axis)
return r
def sum(self, field, axis=None):
r"""Compute the sum of a field, optionally along an axis.
This will, in a parallel-aware fashion, compute the sum of the given
field. If an axis is specified, it will return a projection (using
method type "sum", which does not take into account path length) along
that axis.
Parameters
----------
field : string or tuple field name
The field to sum.
axis : string, optional
If supplied, the axis to sum along.
Returns
-------
Either a scalar or a YTProjection.
Examples
--------
>>> total_vol = reg.sum("cell_volume")
>>> cell_count = reg.sum("ones", axis="x")
"""
# Because we're using ``sum`` to specifically mean a sum or a
# projection with the method="sum", we do not utilize the ``mean``
# function.
if axis in self.ds.coordinates.axis_name:
with self._field_parameter_state({'axis':axis}):
r = self.ds.proj(field, axis, data_source=self, method="sum")
elif axis is None:
r = self.quantities.total_quantity(field)
else:
raise NotImplementedError("Unknown axis %s" % axis)
return r
def integrate(self, field, weight=None, axis=None):
r"""Compute the integral (projection) of a field along an axis.
This projects a field along an axis.
Parameters
----------