Ejemplo n.º 1
0
def test_format_mass(units_in, species_str, spec, output):
    # Quantity object can be formatted
    qty = registry.Quantity(3.5, units_in)
    assert format_mass(qty, species_str, spec) == output

    # Unit object can be formatted
    qty = registry.Unit(units_in)
    assert format_mass(qty, species_str, spec) == output
Ejemplo n.º 2
0
def convert_gwp(context, qty, to):
    """Helper for :meth:`convert_unit` to perform GWP conversions."""
    # Remove a leading 'gwp_' to produce the metric name
    metric = context.split('gwp_')[1] if context else context

    # Extract the species from *qty* and *to*, allowing supported aliases
    species_from, units_from = extract_species(qty[1])
    species_to, units_to = extract_species(to)

    try:
        # Convert using a (magnitude, unit) tuple with only units, and explicit
        # input and output units
        result = iam_units.convert_gwp(metric, (qty[0], units_from),
                                       species_from, species_to)
    except (AttributeError, ValueError):
        # Missing *metric*, or *species_to* contains invalid units. pyam
        # promises UndefinedUnitError in these cases. Use a subclass (above) to
        # add a usage hint.
        raise UndefinedUnitError(species_to) from None
    except pint.DimensionalityError:
        # Provide an exception with the user's inputs
        raise pint.DimensionalityError(qty[1], to) from None

    # Other exceptions are not caught and will pass up through convert_unit()

    if units_to:
        # Also convert the units
        result = result.to(units_to)
    else:
        # *to* was only a species name. Provide units based on input and the
        # output species name.
        to = iam_units.format_mass(result, species_to, spec=':~')

    return result, to
Ejemplo n.º 3
0
def convert_gwp(context, qty, to):
    """Helper for :meth:`convert_unit` to perform GWP conversions."""
    # Remove a leading 'gwp_' to produce the metric name
    metric = context.split('gwp_')[1]

    # Split *to* into a 1- or 3-tuple of str. This allows for *to* to be:
    _to = iam_units.emissions.pattern.split(to, maxsplit=1)
    if len(_to) == 1:
        # Only a species name ('CO2e') without any unit
        species_to = _to[0]
        units_to = None
    else:
        # An expression with both units and species name ('kg CO2e / year');
        # to[1] is the species
        species_to = _to[1]
        # Other elements are pre- and suffix, e.g. 'kg ' and ' / year'
        units_to = _to[0] + _to[2]

    # Convert GWP using the (magnitude, unit-and-species) tuple in *qty*
    result = iam_units.convert_gwp(metric, qty, species_to)

    if units_to:
        # Also convert the units
        result = result.to(units_to)
    else:
        # *to* was only a species name; provide units based on input and the
        # output species name
        to = iam_units.format_mass(result, species_to, spec=':~')

    return result, to