pythondata-analysisyt-project

How do I add a scalar value to a yt array?


I'm trying to add a numerical floor to one of my derived fields in yt. However, when I try: new_field = 1.0e-10 + data['metal_density']

I get the following error:

In [1]: ad = ds.all_data()

In [2]: floored_density = 1.0e-10 + ad['density'] yt : [INFO     ] 2014-09-26 10:15:21,901 Gathering a field list (this may take a moment.) yt : [INFO     ] 2014-09-26 10:15:22,275 Loading field plugins. yt : [INFO     ] 2014-09-26 10:15:22,275 Loaded angular_momentum (8 new fields) yt : [INFO     ] 2014-09-26 10:15:22,276 Loaded astro (14 new fields) yt : [INFO     ] 2014-09-26 10:15:22,276 Loaded cosmology (20 new fields) yt : [INFO     ] 2014-09-26 10:15:22,276 Loaded fluid (56 new fields) yt : [INFO     ] 2014-09-26 10:15:22,277 Loaded fluid_vector (88 new fields) yt : [INFO ] 2014-09-26 10:15:22,278 Loaded geometric (102 new fields) yt : [INFO ] 2014-09-26 10:15:22,278 Loaded local (102 new fields) yt : [INFO     ] 2014-09-26 10:15:22,278 Loaded magnetic_field (108 new fields) yt : [INFO     ] 2014-09-26 10:15:22,278 Loaded species (108 new fields)
--------------------------------------------------------------------------- YTUnitOperationError                      Traceback (most recent call last) /home/skillman/yt-x86_64/src/yt-3.0/yt/mods.pyc in <module>()
----> 1 floored_density = 1.0e-10 + ad['density']

/home/skillman/yt-x86_64/src/yt-3.0/yt/units/yt_array.pyc in
__radd__(self, left_object)
    674     def __radd__(self, left_object):
    675         """ See __add__. """
--> 676         lo = sanitize_units_add(self, left_object, "addition")
    677         return YTArray(super(YTArray, self).__radd__(lo))
    678 

/home/skillman/yt-x86_64/src/yt-3.0/yt/units/yt_array.pyc in sanitize_units_add(this_object, other_object, op_string)
    159     else:
    160         if not inp.units.is_dimensionless:
--> 161             raise YTUnitOperationError(op_string, inp.units, dimensionless)
    162     return ret
    163 

YTUnitOperationError: The addition operator for YTArrays with units (g/cm**3) and (1) is not well defined.

Solution

  • As long as you are careful that the scalar you are adding is in the same units as the yt array, you can do the following:

    ad = ds.all_data()
    
    floored_density = 1.0e-10 * ad['density'].uq + ad['density']
    

    The .uq stands for "unit quantity" and is equal to 1.0 in the units of the field in question. In this case ad['density'].uq is equal to 1.0 g/cm**3.

    Other useful attributes that hang off a yt array are described here: http://yt-project.org/doc/analyzing/units/symbolic_units.html?highlight=unit_quantity#Creating-arrays-and-quantities