[yt-svn] commit/yt: MatthewTurk: Merged in jzuhone/yt (pull request #1748)

commits-noreply at bitbucket.org commits-noreply at bitbucket.org
Mon Sep 14 11:06:25 PDT 2015


1 new commit in yt:

https://bitbucket.org/yt_analysis/yt/commits/98fd66d8cfb2/
Changeset:   98fd66d8cfb2
Branch:      yt
User:        MatthewTurk
Date:        2015-09-14 18:06:09+00:00
Summary:     Merged in jzuhone/yt (pull request #1748)

Roundtrip conversions between Pint and yt units
Affected #:  8 files

diff -r ad96b8c8f330750d9457710381e859419bb89a5b -r 98fd66d8cfb26fd6ab648b5ca2982bc177970f26 doc/source/analyzing/units/2)_Fields_and_unit_conversion.ipynb
--- a/doc/source/analyzing/units/2)_Fields_and_unit_conversion.ipynb
+++ b/doc/source/analyzing/units/2)_Fields_and_unit_conversion.ipynb
@@ -1,7 +1,7 @@
 {
  "metadata": {
   "name": "",
-  "signature": "sha256:4d19ee42177c60fb4b39550b5acd7a0f7e97f59f5c2da3565ff42cdd580454b0"
+  "signature": "sha256:6a06d5720eb6316ac0d322ef0898ec20f33d65ea3eeeacef35ae1d869af12607"
  },
  "nbformat": 3,
  "nbformat_minor": 0,
@@ -352,7 +352,7 @@
      "level": 3,
      "metadata": {},
      "source": [
-      "Round-Trip Conversions to and from AstroPy's Units System"
+      "Round-Trip Conversions to and from Other Unit Systems"
      ]
     },
     {
@@ -503,6 +503,58 @@
      "language": "python",
      "metadata": {},
      "outputs": []
+    },
+    {
+     "cell_type": "markdown",
+     "metadata": {},
+     "source": [
+      "We can also do the same thing with unitful quantities from the [Pint package](http://pint.readthedocs.org), using essentially the same procedure:"
+     ]
+    },
+    {
+     "cell_type": "code",
+     "collapsed": false,
+     "input": [
+      "from pint import UnitRegistry\n",
+      "ureg = UnitRegistry()\n",
+      "v = 1000.*ureg.km/ureg.s\n",
+      "w = yt.YTQuantity.from_pint(v)"
+     ],
+     "language": "python",
+     "metadata": {},
+     "outputs": []
+    },
+    {
+     "cell_type": "code",
+     "collapsed": false,
+     "input": [
+      "print v, type(v)\n",
+      "print w, type(w)"
+     ],
+     "language": "python",
+     "metadata": {},
+     "outputs": []
+    },
+    {
+     "cell_type": "code",
+     "collapsed": false,
+     "input": [
+      "ptemp = temp.to_pint()"
+     ],
+     "language": "python",
+     "metadata": {},
+     "outputs": []
+    },
+    {
+     "cell_type": "code",
+     "collapsed": false,
+     "input": [
+      "print temp, type(temp)\n",
+      "print ptemp, type(ptemp)"
+     ],
+     "language": "python",
+     "metadata": {},
+     "outputs": []
     }
    ],
    "metadata": {}

diff -r ad96b8c8f330750d9457710381e859419bb89a5b -r 98fd66d8cfb26fd6ab648b5ca2982bc177970f26 yt/units/pint_conversions.py
--- /dev/null
+++ b/yt/units/pint_conversions.py
@@ -0,0 +1,84 @@
+"""
+Stuff for pint conversions
+
+"""
+#-----------------------------------------------------------------------------
+# Copyright (c) 2015, 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.
+#-----------------------------------------------------------------------------
+
+pint_aliases = {
+    "meter": "m",
+    "second": "s",
+    "gram": "g",
+    "joule": "J",
+    "franklin": "esu",
+    "dyne": "dyn",
+    "parsec": "pc",
+    "mole": "mol",
+    "rankine": "R",
+    "watt": "W",
+    "pascal": "Pa",
+    "tesla": "T",
+    "kelvin": "K",
+    "year": "yr",
+    "minute": "min",
+    "hour": "hr",
+    "volt": "V",
+    "ampere": "A",
+    "foot": "ft",
+    "coulomb": "C",
+    "newton": "N",
+    "hertz": "Hz",
+    "arcsecond": "arcsec",
+    "arcminute": "arcmin",
+    "speed_of_light": "c",
+    "esu_per_second": "statA",
+    "atomic_mass_unit": "amu",
+    "astronomical_unit": "au",
+    "light_year": "ly",
+    "electron_mass": "me",
+    "proton_mass": "mp",
+}
+
+pint_prefixes = {
+    'yotta':'Y',
+    'zetta':'Z',
+    'exa':'E',
+    'peta':'P',
+    'tera':'T',
+    'giga':'G',
+    'mega':'M',
+    'kilo':'k',
+    'deci':'d',
+    'centi':'c',
+    'milli':'m',
+    'micro':'u',
+    'nano':'n',
+    'pico':'p',
+    'femto':'f',
+    'atto':'a',
+    'zepto':'z',
+    'yocto':'y',
+}
+
+def convert_pint_units(unit_expr):
+    uexpr = unit_expr
+    pfx = ''
+    for prefix in pint_prefixes:
+        if unit_expr.startswith(prefix):
+            pfx = pint_prefixes[prefix]
+            uexpr = uexpr[len(prefix):]
+            break
+    if uexpr in pint_aliases:
+        uexpr = pint_aliases[uexpr]
+        if pfx == '':
+            return uexpr
+        else:
+            return pfx+uexpr
+    # If we can't figure it out just pass it and see 
+    # what happens
+    return unit_expr

diff -r ad96b8c8f330750d9457710381e859419bb89a5b -r 98fd66d8cfb26fd6ab648b5ca2982bc177970f26 yt/units/tests/test_ytarray.py
--- a/yt/units/tests/test_ytarray.py
+++ b/yt/units/tests/test_ytarray.py
@@ -837,6 +837,33 @@
     yield assert_array_equal, yt_arr, YTArray.from_astropy(yt_arr.to_astropy())
     yield assert_equal, yt_quan, YTQuantity.from_astropy(yt_quan.to_astropy())
 
+ at requires_module("pint")
+def test_pint():
+    from pint import UnitRegistry
+
+    ureg = UnitRegistry()
+    
+    p_arr = np.arange(10)*ureg.km/ureg.hr
+    yt_arr = YTArray(np.arange(10), "km/hr")
+    yt_arr2 = YTArray.from_pint(p_arr)
+
+    p_quan = 10.*ureg.g**0.5/(ureg.mm**3)
+    yt_quan = YTQuantity(10., "sqrt(g)/mm**3")
+    yt_quan2 = YTQuantity.from_pint(p_quan)
+
+    yield assert_array_equal, p_arr, yt_arr.to_pint()
+    assert p_quan.units == yt_quan.to_pint().units
+    yield assert_array_equal, yt_arr, YTArray.from_pint(p_arr)
+    yield assert_array_equal, yt_arr, yt_arr2
+
+    yield assert_equal, p_quan.magnitude, yt_quan.to_pint().magnitude
+    assert p_quan.units == yt_quan.to_pint().units
+    yield assert_equal, yt_quan, YTQuantity.from_pint(p_quan)
+    yield assert_equal, yt_quan, yt_quan2
+
+    yield assert_array_equal, yt_arr, YTArray.from_pint(yt_arr.to_pint())
+    yield assert_equal, yt_quan, YTQuantity.from_pint(yt_quan.to_pint())
+
 def test_subclass():
 
     class YTASubclass(YTArray):

diff -r ad96b8c8f330750d9457710381e859419bb89a5b -r 98fd66d8cfb26fd6ab648b5ca2982bc177970f26 yt/units/unit_lookup_table.py
--- a/yt/units/unit_lookup_table.py
+++ b/yt/units/unit_lookup_table.py
@@ -21,7 +21,7 @@
     cm_per_ang, jansky_cgs, mass_jupiter_grams, mass_earth_grams, \
     kelvin_per_rankine, speed_of_light_cm_per_s, planck_length_cm, \
     planck_charge_esu, planck_energy_erg, planck_mass_grams, \
-    planck_temperature_K, planck_time_s
+    planck_temperature_K, planck_time_s, mass_hydrogen_grams
 import numpy as np
 
 # Lookup a unit symbol with the symbol string, and provide a tuple with the
@@ -101,7 +101,7 @@
     "arcsec": (np.pi/648000., dimensions.angle, 0.0,
                r"\rm{arcsec}"),  # arcseconds
     "mas": (np.pi/648000000., dimensions.angle, 0.0,
-            r"\rm{mas}"),  # millarcseconds
+            r"\rm{mas}"),  # milliarcseconds
     "hourangle": (np.pi/12., dimensions.angle, 0.0, r"\rm{HA}"),  # hour angle
     "steradian": (1.0, dimensions.solid_angle, 0.0, r"\rm{sr}"),
 
@@ -113,6 +113,8 @@
     "counts": (1.0, dimensions.dimensionless, 0.0, r"\rm{counts}"),
     "photons": (1.0, dimensions.dimensionless, 0.0, r"\rm{photons}"),
     "me": (mass_electron_grams, dimensions.mass, 0.0, r"m_e"),
+    "mp": (mass_hydrogen_grams, dimensions.mass, 0.0, r"m_p"),
+    "mol": (1.0/amu_grams, dimensions.dimensionless, 0.0, r"\rm{mol}"),
 
     # for AstroPy compatibility
     "solMass": (mass_sun_grams, dimensions.mass, 0.0, r"M_\odot"),

diff -r ad96b8c8f330750d9457710381e859419bb89a5b -r 98fd66d8cfb26fd6ab648b5ca2982bc177970f26 yt/units/yt_array.py
--- a/yt/units/yt_array.py
+++ b/yt/units/yt_array.py
@@ -44,6 +44,7 @@
     default_unit_symbol_lut
 from yt.units.equivalencies import equivalence_registry
 from yt.utilities.logger import ytLogger as mylog
+from .pint_conversions import convert_pint_units
 
 NULL_UNIT = Unit()
 
@@ -614,10 +615,17 @@
         return np.array(self)
 
     @classmethod
-    def from_astropy(cls, arr):
+    def from_astropy(cls, arr, unit_registry=None):
         """
-        Creates a new YTArray with the same unit information from an
-        AstroPy quantity *arr*.
+        Convert an AstroPy "Quantity" to a YTArray or YTQuantity.
+
+        Parameters
+        ----------
+        arr : AstroPy Quantity
+            The Quantity to convert from.
+        unit_registry : yt UnitRegistry, optional
+            A yt unit registry to use in the conversion. If one is not
+            supplied, the default one will be used.
         """
         # Converting from AstroPy Quantity
         u = arr.unit
@@ -630,9 +638,9 @@
             ap_units.append("%s**(%s)" % (unit_str, Rational(power)))
         ap_units = "*".join(ap_units)
         if isinstance(arr.value, np.ndarray):
-            return YTArray(arr.value, ap_units)
+            return YTArray(arr.value, ap_units, registry=unit_registry)
         else:
-            return YTQuantity(arr.value, ap_units)
+            return YTQuantity(arr.value, ap_units, registry=unit_registry)
 
 
     def to_astropy(self, **kwargs):
@@ -644,6 +652,70 @@
                               "an AstroPy quantity.")
         return self.value*_astropy.units.Unit(str(self.units), **kwargs)
 
+    @classmethod
+    def from_pint(cls, arr, unit_registry=None):
+        """
+        Convert a Pint "Quantity" to a YTArray or YTQuantity.
+
+        Parameters
+        ----------
+        arr : Pint Quantity
+            The Quantity to convert from.
+        unit_registry : yt UnitRegistry, optional
+            A yt unit registry to use in the conversion. If one is not
+            supplied, the default one will be used.
+
+        Examples
+        --------
+        >>> from pint import UnitRegistry
+        >>> import numpy as np
+        >>> ureg = UnitRegistry()
+        >>> a = np.random.random(10)
+        >>> b = ureg.Quantity(a, "erg/cm**3")
+        >>> c = yt.YTArray.from_pint(b)
+        """
+        p_units = []
+        for base, power in arr.units.items():
+            bs = convert_pint_units(base)
+            p_units.append("%s**(%s)" % (bs, Rational(power)))
+        p_units = "*".join(p_units)
+        if isinstance(arr.magnitude, np.ndarray):
+            return YTArray(arr.magnitude, p_units, registry=unit_registry)
+        else:
+            return YTQuantity(arr.magnitude, p_units, registry=unit_registry)
+
+    def to_pint(self, unit_registry=None):
+        """
+        Convert a YTArray or YTQuantity to a Pint Quantity.
+
+        Parameters
+        ----------
+        arr : YTArray or YTQuantity
+            The unitful quantity to convert from.
+        unit_registry : Pint UnitRegistry, optional
+            The Pint UnitRegistry to use in the conversion. If one is not
+            supplied, the default one will be used. NOTE: This is not
+            the same as a yt UnitRegistry object.
+            
+        Examples
+        --------
+        >>> a = YTQuantity(4.0, "cm**2/s")
+        >>> b = a.to_pint()
+        """
+        from pint import UnitRegistry
+        if unit_registry is None:
+            unit_registry = UnitRegistry()
+        powers_dict = self.units.expr.as_powers_dict()
+        units = []
+        for unit, pow in powers_dict.items():
+            # we have to do this because Pint doesn't recognize
+            # "yr" as "year" 
+            if str(unit).endswith("yr") and len(str(unit)) in [2,3]:
+                unit = str(unit).replace("yr","year")
+            units.append("%s**(%s)" % (unit, Rational(pow)))
+        units = "*".join(units)
+        return unit_registry.Quantity(self.value, units)
+
     #
     # End unit conversion methods
     #

diff -r ad96b8c8f330750d9457710381e859419bb89a5b -r 98fd66d8cfb26fd6ab648b5ca2982bc177970f26 yt/utilities/physical_constants.py
--- a/yt/utilities/physical_constants.py
+++ b/yt/utilities/physical_constants.py
@@ -10,7 +10,7 @@
 amu = amu_cgs
 Na = 1 / amu_cgs
 
-mass_hydrogen_cgs = 1.007947*amu_cgs
+mass_hydrogen_cgs = YTQuantity(mass_hydrogen_grams, 'g')
 mass_hydrogen = mass_hydrogen_cgs
 mp = mass_hydrogen_cgs
 mh = mp

diff -r ad96b8c8f330750d9457710381e859419bb89a5b -r 98fd66d8cfb26fd6ab648b5ca2982bc177970f26 yt/utilities/physical_ratios.py
--- a/yt/utilities/physical_ratios.py
+++ b/yt/utilities/physical_ratios.py
@@ -10,6 +10,7 @@
 # Elementary masses
 mass_electron_grams = 9.10938291e-28
 amu_grams         = 1.660538921e-24
+mass_hydrogen_grams = 1.007947*amu_grams
 
 # Solar values (see Mamajek 2012)
 # https://sites.google.com/site/mamajeksstarnotes/bc-scale

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