コード例 #1
0
def from_lal_unit(lunit):
    """Convert a LALUnit` into a `~astropy.units.Unit`

    Parameters
    ----------
    aunit : `LALUnit`
        the input unit

    Returns
    -------
    unit : `~astropy.units.Unit`
        the Astropy representation of the input

    Raises
    ------
    ValueError
        if Astropy doesn't understand the base units for the input
    """
    try:
        lunit = lal.Unit(lunit)
    except RuntimeError:
        raise TypeError("Cannot convert %r to lal.Unit" % lunit)
    aunit = units.Unit("")
    for power, lalbase in zip(lunit.unitNumerator, LAL_UNIT_INDEX):
        # if not used, continue
        if not power:
            continue
        # convert to astropy unit
        try:
            u = units.Unit(lal_unit_to_str(lalbase))
        except ValueError:
            raise ValueError("Astropy has no unit corresponding to %r" %
                             lalbase)
        aunit *= u**power
    return aunit
コード例 #2
0
def to_lal_unit(aunit):
    """Convert the input unit into a `LALUnit`

    For example::

       >>> u = to_lal_unit('m**2 / kg ** 4')
       >>> print(u)
       m^2 kg^-4

    Parameters
    ----------
    aunit : `~astropy.units.Unit`, `str`
        the input unit

    Returns
    -------
    unit : `LALUnit`
        the LALUnit representation of the input

    Raises
    ------
    ValueError
        if LAL doesn't understand the base units for the input
    """
    if isinstance(aunit, string_types):
        aunit = units.Unit(aunit)
    aunit = aunit.decompose()
    lunit = lal.Unit()
    for base, power in zip(aunit.bases, aunit.powers):
        # try this base
        try:
            lalbase = LAL_UNIT_FROM_ASTROPY[base]
        except KeyError:
            lalbase = None
            # otherwise loop through the equivalent bases
            for eqbase in base.find_equivalent_units():
                try:
                    lalbase = LAL_UNIT_FROM_ASTROPY[eqbase]
                except KeyError:
                    continue
        # if we didn't find anything, raise an exception
        if lalbase is None:
            raise ValueError("LAL has no unit corresponding to %r" % base)
        lunit *= lalbase**power
    return lunit