pygcam.units

This module contains functions and classes that support symbolic constants usable by the chart command (and user code) for on-the-fly data conversion.

API

This module includes a large number of pre-defined symbolic constants to support unit conversion. Values can be accessed, and additional values added, programmatically via this API.

Use getUnits() to get the singleton instance of the UnitNamespace class, and set values prior to use in, say, the API to the pygcam.chart module. For example,

from pygcam.units import getUnits

u = getUnits()
u.NewConstant = 123.456
class pygcam.units.UnitNamespace

UnitNamespace is a namespace-like class that stores the names of unit conversions, allowing these names to be used in the GCAM tool “chart” sub-command to specify values to multiply or divide by to convert units for plotting. Names can be set and accessed using ‘.’ notation. That is, after calling u = getUnits(), you can access a conversion named, for example, ‘MJ_to_EJ’ as u.MJ_to_EJ, or set a new value for, say, ‘foo’ simply by setting u.foo = value.

Note that the getUnits() method should generally be used rather than calling UnitNamespace() directly to ensure that the single instance of the class is returned.

convert(string, raiseError=True)

Convert the given string to its numerical value, either by direct type conversion, or if this fails, by look-up as the name of a defined unit conversion.

Parameters:
  • string – (str) a string representing a float or the name of a defined unit conversion.
  • raiseError – (bool) if True, an error is raised if the string is neither a number nor a defined unit conversion.
Returns:

(float or None) returns the converted value, or if raiseError is False and the string is not a recognized unit conversion, None is returned.

get(name, raiseError=True)

Get the value of a variable defined in the unitConversion module. Basically an “eval” operation.

Parameters:
  • name – (str) the name of a variable to look up.
  • raiseError – (bool) if True, raise an error if converter is not found.
Returns:

(float or None) the value of the named variable, or None if not found.

pygcam.units.getUnits(other=None)

Returns a singleton instance of a private namespace-like class that can set and get unit conversions.

Parameters:other – (dict-like) an object supporting the items() method that returns pairs of (name, value) that are added to the built-in unit conversion look-up table. Note that elements in other will overwrite existing entries of the same name.
Returns:(UnitNamespace) returns a singleton instance, i.e., subsequent calls will return the same object, though additional names can be passed on each call.