[yt-svn] commit/yt: atmyers: Merged in jzuhone/yt-3.x (pull request #1613)

commits-noreply at bitbucket.org commits-noreply at bitbucket.org
Thu Jun 11 22:49:59 PDT 2015


1 new commit in yt:

https://bitbucket.org/yt_analysis/yt/commits/b9f567104484/
Changeset:   b9f567104484
Branch:      yt
User:        atmyers
Date:        2015-06-12 05:49:50+00:00
Summary:     Merged in jzuhone/yt-3.x (pull request #1613)

Adding gradient fields on the fly
Affected #:  5 files

diff -r aaf2b4a8a1587a380805bd6aa9e6c4a362ffeede -r b9f567104484ec0bbc409106d2f7e9e37588561c doc/source/analyzing/fields.rst
--- a/doc/source/analyzing/fields.rst
+++ b/doc/source/analyzing/fields.rst
@@ -271,6 +271,29 @@
 
 For a practical application of this, see :ref:`cookbook-radial-velocity`.
 
+Gradient Fields
+---------------
+
+yt provides a way to compute gradients of spatial fields using the
+:meth:`~yt.frontends.flash.data_structures.FLASHDataset.add_gradient_fields` 
+method. If you have a spatially-based field such as density or temperature, 
+and want to calculate the gradient of that field, you can do it like so:
+
+.. code-block:: python
+
+    ds = yt.load("GasSloshing/sloshing_nomag2_hdf5_plt_cnt_0150")
+    grad_fields = ds.add_gradient_fields(("gas","temperature"))
+
+where the ``grad_fields`` list will now have a list of new field names that can be used
+in calculations, representing the 3 different components of the field and the magnitude
+of the gradient, e.g., ``"temperature_gradient_x"``, ``"temperature_gradient_y"``,
+``"temperature_gradient_z"``, and ``"temperature_gradient_magnitude"``. To see an example
+of how to create and use these fields, see :ref:`cookbook-complicated-derived-fields`.
+
+.. note::
+
+    ``add_gradient_fields`` currently only supports Cartesian geometries!
+
 General Particle Fields
 -----------------------
 

diff -r aaf2b4a8a1587a380805bd6aa9e6c4a362ffeede -r b9f567104484ec0bbc409106d2f7e9e37588561c doc/source/cookbook/calculating_information.rst
--- a/doc/source/cookbook/calculating_information.rst
+++ b/doc/source/cookbook/calculating_information.rst
@@ -82,6 +82,17 @@
 
 .. yt_cookbook:: derived_field.py
 
+.. _cookbook-complicated-derived-fields:
+
+Complicated Derived Fields
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+This recipe demonstrates how to use the 
+:meth:`~yt.frontends.flash.data_structures.FLASHDataset.add_gradient_fields` method
+to generate gradient fields and use them in a more complex derived field. 
+
+.. yt_cookbook:: hse_field.py
+
 Using Particle Filters to Calculate Star Formation Rates
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

diff -r aaf2b4a8a1587a380805bd6aa9e6c4a362ffeede -r b9f567104484ec0bbc409106d2f7e9e37588561c doc/source/cookbook/hse_field.py
--- a/doc/source/cookbook/hse_field.py
+++ b/doc/source/cookbook/hse_field.py
@@ -1,44 +1,32 @@
 import numpy as np
 import yt
 
-from yt.fields.field_plugin_registry import \
-    register_field_plugin
-from yt.fields.fluid_fields import \
-    setup_gradient_fields
-
-
-# Define the components of the gravitational acceleration vector field by
-# taking the gradient of the gravitational potential
- at register_field_plugin
-def setup_my_fields(registry, ftype="gas", slice_info=None):
-    setup_gradient_fields(registry, (ftype, "gravitational_potential"),
-                          "cm ** 2 / s ** 2", slice_info)
-
-# Define the "degree of hydrostatic equilibrium" field
-
-
- at yt.derived_field(name='HSE', units=None, take_log=False,
-                  display_name='Hydrostatic Equilibrium')
-def HSE(field, data):
-
-    gx = data["density"] * data["gravitational_potential_gradient_x"]
-    gy = data["density"] * data["gravitational_potential_gradient_y"]
-    gz = data["density"] * data["gravitational_potential_gradient_z"]
-
-    hx = data["pressure_gradient_x"] - gx
-    hy = data["pressure_gradient_y"] - gy
-    hz = data["pressure_gradient_z"] - gz
-
-    h = np.sqrt((hx * hx + hy * hy + hz * hz) / (gx * gx + gy * gy + gz * gz))
-
-    return h
-
-
 # Open a dataset from when there's a lot of sloshing going on.
 
 ds = yt.load("GasSloshingLowRes/sloshing_low_res_hdf5_plt_cnt_0350")
 
-# gradient operator requires periodic boundaries.  This dataset has
+# Define the components of the gravitational acceleration vector field by
+# taking the gradient of the gravitational potential
+grad_fields = ds.add_gradient_fields(("gas","gravitational_potential"))
+
+# We don't need to do the same for the pressure field because yt already
+# has pressure gradient fields. Now, define the "degree of hydrostatic 
+# equilibrium" field.
+
+def _hse(field, data):
+    # Remember that g is the negative of the potential gradient
+    gx = -data["density"] * data["gravitational_potential_gradient_x"]
+    gy = -data["density"] * data["gravitational_potential_gradient_y"]
+    gz = -data["density"] * data["gravitational_potential_gradient_z"]
+    hx = data["pressure_gradient_x"] - gx
+    hy = data["pressure_gradient_y"] - gy
+    hz = data["pressure_gradient_z"] - gz
+    h = np.sqrt((hx * hx + hy * hy + hz * hz) / (gx * gx + gy * gy + gz * gz))
+    return h
+ds.add_field(('gas','HSE'), function=_hse, units="", take_log=False,
+             display_name='Hydrostatic Equilibrium')
+
+# The gradient operator requires periodic boundaries.  This dataset has
 # open boundary conditions.  We need to hack it for now (this will be fixed
 # in future version of yt)
 ds.periodicity = (True, True, True)

diff -r aaf2b4a8a1587a380805bd6aa9e6c4a362ffeede -r b9f567104484ec0bbc409106d2f7e9e37588561c yt/data_objects/static_output.py
--- a/yt/data_objects/static_output.py
+++ b/yt/data_objects/static_output.py
@@ -35,6 +35,8 @@
     ValidateSpatial
 from yt.fields.field_info_container import \
     FieldInfoContainer, NullFunc
+from yt.fields.fluid_fields import \
+    setup_gradient_fields
 from yt.data_objects.particle_filters import \
     filter_registry
 from yt.data_objects.particle_unions import \
@@ -965,6 +967,50 @@
             validators=[ValidateSpatial()])
         return ("deposit", field_name)
 
+    def add_gradient_fields(self, input_field):
+        """Add gradient fields. 
+
+        Creates four new grid-based fields that represent the components of
+        the gradient of an existing field, plus an extra field for the magnitude
+        of the gradient. Currently only supported in Cartesian geometries. The 
+        gradient is computed using second-order centered differences. 
+
+        Parameters
+        ----------
+        input_field : tuple
+           The field name tuple of the particle field the deposited field will
+           be created from.  This must be a field name tuple so yt can
+           appropriately infer the correct field type.
+
+        Returns
+        -------
+        A list of field name tuples for the newly created fields.
+        
+        Examples
+        --------
+        >>> grad_fields = ds.add_gradient_fields(("gas","temperature"))
+        >>> print(grad_fields)
+        [('gas', 'temperature_gradient_x'), 
+         ('gas', 'temperature_gradient_y'), 
+         ('gas', 'temperature_gradient_z'), 
+         ('gas', 'temperature_gradient_magnitude')]
+        """
+        self.index
+        if isinstance(input_field, tuple):
+            ftype, input_field = input_field[0], input_field[1]
+        else:
+            raise RuntimeError
+        units = self.field_info[ftype, input_field].units
+        setup_gradient_fields(self.field_info, (ftype, input_field), units)
+        # Now we make a list of the fields that were just made, to check them
+        # and to return them
+        grad_fields = [(ftype,input_field+"_gradient_%s" % suffix)
+                       for suffix in "xyz"]
+        grad_fields.append((ftype,input_field+"_gradient_magnitude"))
+        deps, _ = self.field_info.check_derived_fields(grad_fields)
+        self.field_dependencies.update(deps)
+        return grad_fields
+
 def _reconstruct_ds(*args, **kwargs):
     datasets = ParameterFileStore()
     ds = datasets.get_ds_hash(*args)

diff -r aaf2b4a8a1587a380805bd6aa9e6c4a362ffeede -r b9f567104484ec0bbc409106d2f7e9e37588561c yt/fields/tests/test_fields.py
--- a/yt/fields/tests/test_fields.py
+++ b/yt/fields/tests/test_fields.py
@@ -194,6 +194,18 @@
     ret = ad[fn]
     assert_equal(ret.sum(), ad['particle_ones'].sum())
 
+def test_add_gradient_fields():
+    gfields = base_ds.add_gradient_fields(("gas","density"))
+    field_list = [('gas', 'density_gradient_x'),
+                  ('gas', 'density_gradient_y'),
+                  ('gas', 'density_gradient_z'),
+                  ('gas', 'density_gradient_magnitude')]
+    assert_equal(gfields, field_list)
+    ad = base_ds.all_data()
+    for field in field_list:
+        ret = ad[field]
+        assert str(ret.units) == "g/cm**4"
+
 def get_data(ds, field_name):
     # Need to create a new data object otherwise the errors we are
     # intentionally raising lead to spurious GenerationInProgress errors

Repository URL: https://bitbucket.org/yt_analysis/yt/

--

This is a commit notification from bitbucket.org. You are receiving
this because you have the service enabled, addressing the recipient of
this email.


More information about the yt-svn mailing list