Operators#
Elementary operators for genno.
Unless otherwise specified, these functions accept and return Quantity
objects for data arguments/return values.
The names and signatures of many operators match the corresponding methods on the Quantity
class, and thus also the xarray.DataArray
methods of the same names.
Genno’s compatibility modules each provide additional operators.
Numerical operators:
|
Sum across multiple quantities. |
|
Aggregate quantity by groups. |
|
Broadcast quantity using a map. |
|
Call |
|
Sum distinct quantities by weights. |
|
Deprecated: Disaggregate quantity by shares. |
|
Compute the ratio numerator / denominator. |
|
Group by dimension group, then sum across dimension sum. |
|
Compute an index of qty against certain of its values. |
|
Interpolate qty. |
|
Compute the product of any number of quantities. |
|
Compute a raised to the power of b. |
|
Alias of |
|
Alias of |
|
Like |
|
Subtract b from a. |
|
Sum quantity over dimensions, with optional weights. |
|
|
|
Call |
Data manipulation and transformation:
|
Apply units to qty. |
|
Convert various values to Quantity. |
|
Set the units of qty without changing magnitudes. |
|
Concatenate Quantity objs. |
|
Convert magnitude of qty from its current units to units. |
|
Return a Quantity with dropped variables (coordinates). |
|
Replace specific labels along dimensions of qty. |
|
Returns a new Quantity with renamed dimensions or a new name. |
|
Returns a new Quantity with renamed dimensions or a new name. |
|
Select from qty based on indexers. |
|
Assign |
Input and output:
|
Read the file at path and return its contents as a |
|
|
|
Write a quantity to a file. |
- genno.operator.add(*quantities: AttrSeries | SparseDataArray, fill_value: float = 0.0) AttrSeries | SparseDataArray [source]#
Sum across multiple quantities.
- Raises:
ValueError – if any of the quantities have incompatible units.
- Returns:
Units are the same as the first of quantities.
- Return type:
See also
- genno.operator.aggregate(quantity: AttrSeries | SparseDataArray, groups: Mapping[str, Mapping], keep: bool) AttrSeries | SparseDataArray [source]#
Aggregate quantity by groups.
- Parameters:
groups (
dict
ofdict
) – Top-level keys are the names of dimensions in quantity. Second-level keys are group names; second-level values are lists of labels along the dimension to sum into a group. Labels may be literal values, or compiledre.Pattern
objects; in the latter case, all matching labels (according tore.Pattern.fullmatch()
) are included in the group to be aggregated.keep (
bool
) – If True, the members that are aggregated into a group are returned with the group sums. If False, they are discarded.
- Returns:
Same dimensionality as quantity.
- Return type:
- genno.operator.apply_units(qty: AttrSeries | SparseDataArray, units: str | Unit | Quantity) AttrSeries | SparseDataArray [source]#
Apply units to qty.
If qty has existing units…
…with compatible dimensionality to units, the magnitudes are adjusted, i.e. behaves like
convert_units()
.…with incompatible dimensionality to units, the units attribute is overwritten and magnitudes are not changed, i.e. like
assign_units()
, with a log message on levelWARNING
.
To avoid ambiguities between the two cases, use
convert_units()
orassign_units()
instead.
- genno.operator.as_quantity(info: dict | float | str) AttrSeries | SparseDataArray [source]#
Convert various values to Quantity.
This operator can be useful when handling values from user input or various file formats.
Examples
>>> as_quantity("3.0 kg")
dict
:A ‘_dim’ key is removed and treated as
Quantity.dims
.A ‘_unit’ key is removed and treated as
Quantity.units
.
>>> value = { ... ("x0", "y0"): 1.0, ... ("x1", "y1"): 2.0, ... "_dim": ("x", "y"), ... "_unit": "km", ... } >>> as_quantity(value)
For other values, the
Quantity
constructor should be used directly:>>> Quantity(1.2)
- genno.operator.assign_units(qty: AttrSeries | SparseDataArray, units: str | Unit | Quantity) AttrSeries | SparseDataArray [source]#
Set the units of qty without changing magnitudes.
Logs on level
INFO
if qty has existing units.
- genno.operator.broadcast_map(quantity: AttrSeries | SparseDataArray, map: AttrSeries | SparseDataArray, rename: Mapping = {}, strict: bool = False) AttrSeries | SparseDataArray [source]#
Broadcast quantity using a map.
The map must be a 2-dimensional Quantity with dimensions (
d1
,d2
), such as returned byixmp.report.operator.map_as_qty()
. quantity must also have a dimensiond1
. Typicallylen(d2) > len(d1)
.quantity is ‘broadcast’ by multiplying it with map, and then summing on the common dimension
d1
. The result has the dimensions of quantity, but withd2
in place ofd1
.
- genno.operator.clip(qty: AnyQuantity, min: types.ScalarOrArray | None = None, max: types.ScalarOrArray | None = None, *, keep_attrs: bool | None = None) AnyQuantity [source]#
Call
Quantity.clip()
.
- genno.operator.combine(*quantities: AttrSeries | SparseDataArray, select: List[Mapping] | None = None, weights: List[float] | None = None) AttrSeries | SparseDataArray [source]#
Sum distinct quantities by weights.
- Parameters:
- Raises:
ValueError – If the quantities have mismatched units.
- genno.operator.concat(*objs: AttrSeries | SparseDataArray, **kwargs) AttrSeries | SparseDataArray [source]#
- genno.operator.concat(*args: IamDataFrame, **kwargs) IamDataFrame
Concatenate Quantity objs.
Any strings included amongst objs are discarded, with a logged warning; these usually indicate that a quantity is referenced which is not in the Computer.
- genno.operator.convert_units(qty: AttrSeries | SparseDataArray, units: str | Unit | Quantity) AttrSeries | SparseDataArray [source]#
Convert magnitude of qty from its current units to units.
- Parameters:
- Raises:
ValueError – if units does not match the dimensionality of the current units of qty.
Deprecated: Disaggregate quantity by shares.
This operator is identical to
mul()
; usemul()
and its helper instead.
- genno.operator.div(numerator: AttrSeries | SparseDataArray | float, denominator: AttrSeries | SparseDataArray) AttrSeries | SparseDataArray [source]#
Compute the ratio numerator / denominator.
See also
- genno.operator.drop_vars(qty: AttrSeries | SparseDataArray, names: str | Iterable[Hashable] | Callable[[AttrSeries | SparseDataArray], str | Iterable[Hashable]], *, errors='raise') AttrSeries | SparseDataArray [source]#
Return a Quantity with dropped variables (coordinates).
- genno.operator.group_sum(qty: AttrSeries | SparseDataArray, group: str, sum: str) AttrSeries | SparseDataArray [source]#
Group by dimension group, then sum across dimension sum.
The result drops the latter dimension.
- genno.operator.index_to(qty: AttrSeries | SparseDataArray, dim_or_selector: str | Mapping, label: Hashable | None = None) AttrSeries | SparseDataArray [source]#
Compute an index of qty against certain of its values.
If the label is not provided,
index_to()
uses the label in the first position along the identified dimension.- Parameters:
qty (
Quantity
)dim_or_selector (
str
orcollections.abc.Mapping
) – If a string, the ID of the dimension to index along. If a mapping, it must have only one element, mapping a dimension ID to a label.label (
Hashable
) – Label to select along the dimension, required if dim_or_selector is a string.
- Raises:
TypeError – if dim_or_selector is a mapping with length != 1.
- genno.operator.interpolate(qty: AnyQuantity, coords: Mapping[Hashable, Any] | None = None, method: types.InterpOptions = 'linear', assume_sorted: bool = True, kwargs: Mapping[str, Any] | None = None, **coords_kwargs: Any) AnyQuantity [source]#
Interpolate qty.
For the meaning of arguments, see
xarray.DataArray.interp()
. WhenCLASS
isAttrSeries
, only 1-dimensional interpolation (one key in coords) is tested/supported.
- genno.operator.load_file(path: Path, dims: Collection[Hashable] | Mapping[Hashable, Hashable] = {}, units: str | Unit | Quantity | None = None, name: str | None = None) Any [source]#
Read the file at path and return its contents as a
Quantity
.Some file formats are automatically converted into objects for direct use in genno computations:
.csv
:Converted to
Quantity
. CSV files must have a ‘value’ column; all others are treated as indices, except as given by dims. Lines beginning with ‘#’ are ignored.
User code may define an operator with the same name (“load_file”) in order to override this behaviour and/or add tailored support for others data file formats, for instance specific kinds of
.json
,.xml
,.yaml
,.ods
,.xlsx
, or other file types.- Parameters:
path (
pathlib.Path
) – Path to the file to read.dims (
collections.abc.Collection
orcollections.abc.Mapping
, optional) – If a collection of names, other columns besides these and ‘value’ are discarded. If a mapping, the keys are the column labels in path, and the values are the target dimension names.units (
str
orpint.Unit
) – Units to apply to the loaded Quantity.name (
str
) – Name for the loaded Quantity.
See also
- genno.operator.mul(*quantities: AttrSeries | SparseDataArray) AttrSeries | SparseDataArray [source]#
Compute the product of any number of quantities.
See also
- genno.operator.pow(a: AttrSeries | SparseDataArray, b: AttrSeries | SparseDataArray | int) AttrSeries | SparseDataArray [source]#
Compute a raised to the power of b.
- genno.operator.product(*quantities: AttrSeries | SparseDataArray) AttrSeries | SparseDataArray #
Alias of
mul()
, for backwards compatibility.Note
This may be deprecated and possibly removed in a future version.
- genno.operator.ratio(numerator: AttrSeries | SparseDataArray | float, denominator: AttrSeries | SparseDataArray) AttrSeries | SparseDataArray #
Alias of
div()
, for backwards compatibility.Note
This may be deprecated and possibly removed in a future version.
- genno.operator.relabel(qty: AttrSeries | SparseDataArray, labels: Mapping[Hashable, Mapping] | None = None, **dim_labels: Mapping) AttrSeries | SparseDataArray [source]#
Replace specific labels along dimensions of qty.
- Parameters:
labels – Keys are strings identifying dimensions of qty; values are further mappings from original labels to new labels. Dimensions and labels not appearing in qty have no effect.
dim_labels – Mappings given as keyword arguments, where argument name is the dimension.
- Raises:
ValueError – if both labels and dim_labels are given.
- genno.operator.rename(qty: AttrSeries | SparseDataArray, new_name_or_name_dict: Hashable | Mapping[Any, Hashable] | None = None, **names: Hashable) AttrSeries | SparseDataArray [source]#
Returns a new Quantity with renamed dimensions or a new name.
Like
xarray.DataArray.rename()
, and identical in behaviour torename_dims()
.
- genno.operator.rename_dims(qty: AttrSeries | SparseDataArray, name_dict: Hashable | Mapping[Any, Hashable] | None = None, **names: Hashable) AttrSeries | SparseDataArray [source]#
Returns a new Quantity with renamed dimensions or a new name.
Like
xarray.DataArray.rename()
, and identical in behaviour torename()
. The two names are provided for more expressive user code.
- genno.operator.round(qty: AttrSeries | SparseDataArray, *args, **kwargs) AttrSeries | SparseDataArray [source]#
Like
xarray.DataArray.round()
.
- genno.operator.select(qty: AttrSeries | SparseDataArray, indexers: Mapping[Hashable, Iterable[Hashable]], *, inverse: bool = False, drop: bool = False) AttrSeries | SparseDataArray [source]#
Select from qty based on indexers.
- Parameters:
indexers (
dict
) –Elements to be selected from qty. Mapping from dimension names (
str
) to either:list
of str: coords along the respective dimension of qty, orxarray.DataArray
: xarray-style indexers.
Values not appearing in the dimension coords are silently ignored.
inverse (
bool
, optional) – IfTrue
, remove the items in indexers instead of keeping them.drop (
bool
, optional) – IfTrue
, drop dimensions that are indexed by a scalar value (for instance,"foo"
or999
) in indexers. Note that dimensions indexed by a length-1 list of labels (for instance["foo"]
) are not dropped; this behaviour is consistent withxarray.DataArray
.
- genno.operator.sub(a: AttrSeries | SparseDataArray, b: AttrSeries | SparseDataArray) AttrSeries | SparseDataArray [source]#
Subtract b from a.
See also
- genno.operator.sum(quantity: AttrSeries | SparseDataArray, weights: AttrSeries | SparseDataArray | None = None, dimensions: List[str] | None = None) AttrSeries | SparseDataArray [source]#
Sum quantity over dimensions, with optional weights.
- genno.operator.unique_units_from_dim(qty: AttrSeries | SparseDataArray, dim: str, *, fail: str | int = 'raise') AttrSeries | SparseDataArray [source]#
Assign
Quantity.units
using coords from the dimension dim.The dimension dim is dropped from the result.
- Raises:
ValueError – if (a) fail is “raise” (the default) and (b) the dimension dim contains more than one unique value. If fail is anything else, a message is logged with level fail, and the returned Quantity is dimensionless.
- genno.operator.where(qty: ~genno.core.attrseries.AttrSeries | ~genno.core.sparsedataarray.SparseDataArray, cond: ~typing.Any, other: ~typing.Any = <NA>, drop: bool = False) AttrSeries | SparseDataArray [source]#
Call
Quantity.where()
.
- genno.operator.write_report(quantity: object, path: str | PathLike, kwargs: dict | None = None) None [source]#
- genno.operator.write_report(quantity: str, path: str | PathLike, kwargs: dict | None = None)
- genno.operator.write_report(quantity: DataFrame, path: str | PathLike, kwargs: dict | None = None) None
- genno.operator.write_report(quantity: AttrSeries | SparseDataArray, path: str | PathLike, kwargs: dict | None = None) None
- genno.operator.write_report(quantity: AttrSeries | SparseDataArray, path: str | PathLike, kwargs: dict | None = None) None
- genno.operator.write_report(obj: DataMessage, path, kwargs=None) None
- genno.operator.write_report(quantity: IamDataFrame, path, kwargs=None) None
Write a quantity to a file.
write_report()
is asingledispatch()
function. This means that user code can extend this operator to support different types for the quantity argument:import genno.operator @genno.operator.write_report.register def my_writer(qty: MyClass, path, kwargs): ... # Code to write MyClass to file
- Parameters:
quantity – Object to be written. The base implementation supports
Quantity
andpandas.DataFrame
.path (
str
orpathlib.Path
) – Path to the file to be written.kwargs –
Keyword arguments. For the base implementation, these are passed to
pandas.DataFrame.to_csv()
orpandas.DataFrame.to_excel()
(according to path), except for:”header_comment”: valid only for path ending in
.csv
. Multi-line text that is prepended to the file, with comment characters (”# “) before each line.
- Raises:
NotImplementedError – If quantity is of a type not supported by the base implementation or any overloads.
Helper functions for adding tasks to Computers#
- genno.operator.add_binop(func, c: Computer, key, *quantities, **kwargs) Key [source]#
Computer.add()
helper for binary operations.Add a computation that applies
add()
,div()
,mul()
, orsub()
to quantities.- Parameters:
- Returns:
The full key of the new quantity.
- Return type:
Example
>>> c = Computer() >>> x = c.add("x:a-b-c", ...) >>> y = c.add("y:c-d-e", ...) >>> z = c.add("z", "mul", x, y) >>> z <z:a-b-c-d-e>
- genno.operator.add_load_file(func, c: Computer, path, key=None, **kwargs)[source]#
Computer.add()
helper forload_file()
.Add a task to load an exogenous quantity from path. Computing the key or using it in other computations causes path to be loaded and converted to
Quantity
.- Parameters:
path (
os.PathLike
) – Path to the file, e.g. ‘/path/to/foo.ext’.key (
str
orKey
, optional) – Key for the quantity read from the file.dims (
dict
orlist
orset
) – Either a collection of names for dimensions of the quantity, or a mapping from names appearing in the input to dimensions.units (
str
orpint.Unit
) – Units to apply to the loaded Quantity.
- Returns:
Either key (if given) or e.g.
file foo.ext
based on the path name, without directory components.- Return type:
- genno.operator.add_sum(func, c: Computer, key, qty, weights=None, dimensions=None, **kwargs) Key | str | Tuple[Key | str, ...] [source]#
Computer.add()
helper forsum()
.If key has the name “*”, the returned key has name and dimensions inferred from qty and dimensions, and only the tag (if any) of key is preserved.