Low-level utilities (util)¶
Submodules:
Command-line utilities. |
|
Context and settings for |
|
Load model and project code from |
|
Logging utilities. |
|
|
Commonly used:
|
Convert data to a |
|
Fill missing data in df by broadcasting. |
|
For use with |
|
Forward-fill df on dim to cover values. |
|
Load a |
|
Load a private data file from |
|
Return input and output data frames for a 1-to-1 technology. |
|
Return data frames derived from base for multiple parameters. |
|
Return parameter data for a ‘source’ technology. |
|
Merge dictionaries of DataFrames together into base. |
|
Construct a path to a file under |
|
Construct a path to a file under |
|
Fill ‘node_origin’/’node_dest’ in df from ‘node_loc’. |
|
Context and settings for |
|
Information about a |
-
message_ix_models.util.PACKAGE_DATA: Dict[str, Any] = {}¶ Package data already loaded with
load_package_data().
-
message_ix_models.util.PRIVATE_DATA: Dict[str, Any] = {}¶ Data already loaded with
load_private_data().
-
message_ix_models.util.add_par_data(scenario: message_ix.core.Scenario, data: Mapping[str, pandas.core.frame.DataFrame], dry_run: bool = False)[source]¶ Add data to scenario.
- Parameters
data – Dict with keys that are parameter names, and values are pd.DataFrame or other arguments
dry_run (optional) – Only show what would be done.
See also
-
message_ix_models.util.as_codes(data: Union[List[str], Dict[str, Dict]]) → List[sdmx.model.Code][source]¶ Convert data to a
listofCodeobjects.Various inputs are accepted:
-
message_ix_models.util.broadcast(df, **kwargs)[source]¶ Fill missing data in df by broadcasting.
- Parameters
kwargs – Keys are dimensions. Values are labels along that dimension to fill.
-
message_ix_models.util.copy_column(column_name)[source]¶ For use with
pandas.DataFrame.assign().Examples
Modify df by filling the column ‘baz’ with the value
3, and copying the column ‘bar’ into column ‘foo’.>>> df.assign(foo=copy_column('bar'), baz=3)
-
message_ix_models.util.eval_anno(obj: sdmx.model.AnnotableArtefact, id: str)[source]¶ Retrieve the annotation id from obj, run
eval()on its contents.This can be used for unpacking Python values (e.g.
dict) stored as an annotation on aCode.Returns
Noneif no attribute exists with the given id.
-
message_ix_models.util.ffill(df: pandas.core.frame.DataFrame, dim: str, values: Sequence[Union[str, sdmx.model.Code]], expr: Optional[str] = None) → pandas.core.frame.DataFrame[source]¶ Forward-fill df on dim to cover values.
- Parameters
df (DataFrame) – Data to fill forwards.
dim (str) – Dimension to fill along. Must be a column in df.
values (list of str) – Labels along dim that must be present in the returned data frame.
expr (str, optional) – If provided,
DataFrame.eval()is called. This can be used to assign one column to another. For instance, if dim == “year_vtg” and expr is “year_act = year_vtg”, then forward filling is performed along the “year_vtg” dimension/ column, and then the filled values are copied to the “year_act” column.
-
message_ix_models.util.iter_parameters(set_name)[source]¶ Iterate over MESSAGEix parameters with set_name as a dimension.
- Parameters
set_name (str) – Name of a set.
- Yields
str – Names of parameters that have set_name indexing ≥1 dimension.
-
message_ix_models.util.load_package_data(*parts: str, suffix: Optional[str] = '.yaml') → Any[source]¶ Load a
message_ix_modelspackage data file and return its contents.Data is re-used if already loaded.
Example
The single call:
>>> info = load_package_data("node", "R11")
loads the metadata file
data/node/R11.yaml, parsing its contents,stores those values at
PACKAGE_DATA["node R11"]for use by other code, andreturns the loaded values.
-
message_ix_models.util.load_private_data(*parts: str) → Mapping[source]¶ Load a private data file from
message_dataand return its contents.Analogous to
load_package_data, but for non-public data.- Parameters
parts (iterable of str) – Used to construct a path under
data/in themessage_datarepository.- Returns
Configuration values that were loaded.
- Return type
- Raises
RuntimeError – if
message_datais not installed.
-
message_ix_models.util.make_io(src, dest, efficiency, on='input', **kwargs)[source]¶ Return input and output data frames for a 1-to-1 technology.
- Parameters
dest (tuple (str, str, str)) – Output commodity, level, unit.
efficiency (float) – Conversion efficiency.
on ('input' or 'output') – If ‘input’, efficiency applies to the input, and the output, thus the activity level of the technology, is in dest[2] units. If ‘output’, the opposite.
kwargs – Passed to
make_df().
- Returns
Keys are ‘input’ and ‘output’; values are data frames.
- Return type
dict (str -> pd.DataFrame)
-
message_ix_models.util.make_matched_dfs(base, **par_value)[source]¶ Return data frames derived from base for multiple parameters.
par_values maps from parameter names (e.g. ‘fix_cost’) to values. make_matched_dfs returns a
dictofpandas.DataFrame, one for each parameter in par_value. The contents of base are used to populate the columns of each data frame, and the values of par_value overwrite the ‘value’ column. Duplicates—which occur when the target parameter has fewer dimensions than base—are dropped.Examples
>>> input = make_df('input', ...) >>> cf_tl = make_matched_dfs( >>> input, >>> capacity_factor=1, >>> technical_lifetime=1, >>> )
-
message_ix_models.util.make_source_tech(info, common, **values) → Dict[str, pandas.core.frame.DataFrame][source]¶ Return parameter data for a ‘source’ technology.
The technology has no inputs; its output commodity and/or level are determined by common; either single values, or
Noneif the result will bepipe()’d throughbroadcast().- Parameters
info (ScenarioInfo) –
common (dict) – Passed to
make_df().**values – Values for ‘capacity_factor’ (optional; default 1.0), ‘output’, ‘var_cost’, and optionally ‘technical_lifetime’.
- Returns
Suitable for
add_par_data().- Return type
-
message_ix_models.util.merge_data(base, *others)[source]¶ Merge dictionaries of DataFrames together into base.
-
message_ix_models.util.package_data_path(*parts) → pathlib.Path[source]¶ Construct a path to a file under
message_ix_models/data/.
-
message_ix_models.util.private_data_path(*parts) → pathlib.Path[source]¶ Construct a path to a file under
data/inmessage_data.
-
message_ix_models.util.strip_par_data(scenario, set_name, value, dry_run=False, dump: Optional[Dict[str, pandas.core.frame.DataFrame]] = None)[source]¶ Remove data from parameters of scenario where value in set_name.
- Returns
- Return type
Total number of rows removed across all parameters.
See also
util.click¶
Command-line utilities.
These are used for building CLIs using click.
-
message_ix_models.util.click.PARAMS= {'dest': <Option dest>, 'dry_run': <Option dry_run>, 'force': <Option force>, 'output_model': <Option output_model>, 'platform_dest': <Option platform_dest>, 'policy_path': <Option policy_path>, 'quiet': <Option quiet>, 'regions': <Option regions>, 'rep_out_path': <Option rep_out_path>, 'rep_template': <Option rep_template>, 'run_reporting_only': <Option run_reporting_only>, 'ssp': <Argument ssp>, 'verbose': <Option verbose>}¶ Common command-line parameters (arguments and options). See
common_params().
-
message_ix_models.util.click.common_params(param_names: str)[source]¶ Decorate a click.command with common parameters param_names.
param_names must be a space-separated string of names appearing in
PARAMS, e.g."ssp force output_model". The decorated function receives keyword arguments with these names:@click.command() @common_params("ssp force output_model") def mycmd(ssp, force, output_model) # ...
-
message_ix_models.util.click.default_path_cb(*default_parts)[source]¶ Return a callback function for click.Option handling.
If no option value is given, the callback uses
Context.get_local_path()and default_parts to provide a path that is relative to local data directory, e.g. the current working directory (see Data, metadata, and configuration).
util.context¶
Context and settings for message_ix_models code.
-
class
message_ix_models.util.context.Context(*args, **kwargs)[source]¶ Context and settings for
message_ix_modelscode.Context is a subclass of
dict, so common methods likecopy()andsetdefault()may be used to handle settings. To be forgiving, it also provides attribute access;context.foois equivalent tocontext["foo"].Context provides additional methods to do common tasks that depend on configurable settings:
Return a scenario based on the
--destcommand-line option.close_db()delete()Hide the current Context from future
get_instance()calls.get_cache_path(*parts)Return a path to a local cache file.
get_local_path(*parts[, suffix])Return a path under
local_data.get_platform([reload])Return a
ixmp.Platformfromplatform_info.Return a
message_ix.Scenariofromscenario_info.handle_cli_args([url, platform, model_name, …])Handle command-line arguments.
only()Return the only
Contextinstance.use_defaults(settings)Update from settings.
The following Context methods and attribute are deprecated:
get_config_file(*parts[, ext])Return a path under
metadata_path.get_path(*parts)Return a path under
message_data_pathby joining parts.load_config(*parts[, suffix])Load configuration from
message_ix_models.Access the unit registry.
-
clone_to_dest() → Tuple[message_ix.core.Scenario, ixmp.core.Platform][source]¶ Return a scenario based on the
--destcommand-line option.- Returns
To prevent the scenario from being garbage collected. Keep a reference to its Platform:
- Return type
Scenario
See also
create_resTo use this method, either decorate a command with
common_params():from message_data.tools.cli import common_params @click.command() @common_params("dest") @click.pass_obj def foo(context, dest): scenario, mp = context.clone_to_dest()
or, store the settings
dest_scenarioanddest_platformon context:c = Context.get_instance() c.dest_scenario = dict(model="foo model", scenario="foo scenario") scenario_mp = context.clone_to_dest()
The resulting scenario has the indicated model- and scenario names.
If
--url(or--platform,--model,--scenario, and optionally--version) are given, the identified scenario is used as a ‘base’ scenario, and is cloned. If--url/--platformand--destrefer to different Platform instances, then this is a two-platform clone.If no base scenario can be loaded,
bare.create_res()is called to generate a base scenario.
-
delete()[source]¶ Hide the current Context from future
get_instance()calls.
-
get_cache_path(*parts) → pathlib.Path[source]¶ Return a path to a local cache file.
-
get_config_file(*parts, ext='yaml') → pathlib.Path[source]¶ Return a path under
metadata_path.The suffix “.{ext}” is added; defaulting to “.yaml”.
Deprecated since version 2021.2.28: Use
package_data_path()instead. Will be removed on or after 2021-05-28.
-
classmethod
get_instance(index=0) → message_ix_models.util.context.Context[source]¶ Return a Context instance; by default, the first created.
- Parameters
index (int, optional) – Index of the Context instance to return, e.g.
-1for the most recently created.
-
get_path(*parts) → pathlib.Path[source]¶ Return a path under
message_data_pathby joining parts.parts may include directory names, or a filename with extension.
Deprecated since version 2021.2.28: Use
private_data_path()instead. Will be removed on or after 2021-05-28.
-
get_platform(reload=False) → ixmp.core.Platform[source]¶ Return a
ixmp.Platformfromplatform_info.When used through the CLI,
platform_infois a ‘base’ platform as indicated by the –url or –platform options.If a Platform has previously been instantiated with
get_platform(), the same object is returned unless reload=True.
-
get_scenario() → message_ix.core.Scenario[source]¶ Return a
message_ix.Scenariofromscenario_info.When used through the CLI,
scenario_infois a ‘base’ scenario for an operation, indicated by the--urlor--platform/--model/--scenariooptions.
-
handle_cli_args(url=None, platform=None, model_name=None, scenario_name=None, version=None, local_data=None, _store_as=('platform_info', 'scenario_info'))[source]¶ Handle command-line arguments.
May update the
data_path,platform_info,scenario_info, and/orurlsettings.
-
load_config(*parts, suffix=None)[source]¶ Load configuration from
message_ix_models.Deprecated since version 2021.2.28: Use
load_package_data()instead. Will be removed on or after 2021-05-28.
-
classmethod
only() → message_ix_models.util.context.Context[source]¶ Return the only
Contextinstance.- Raises
IndexError – If there is more than one instance.
-
property
units¶ Access the unit registry.
Deprecated since version 2021.2.28: Instead, use:
from iam_units import registry
Will be removed on or after 2021-05-28.
-
util.importlib¶
Load model and project code from message_data.
util._logging¶
Logging utilities.
-
class
message_ix_models.util._logging.Formatter(colorama)[source]¶ Formatter for log records.
- Parameters
colorama (module) – If provided,
coloramais used to colour log messages printed to stdout.
-
message_ix_models.util._logging.make_formatter()[source]¶ Return a
Formatterinstance for themessage_ix_modelslogger.See also
util.scenarioinfo¶
ScenarioInfo class.
-
class
message_ix_models.util.scenarioinfo.ScenarioInfo(scenario=None)[source]¶ Information about a
Scenarioobject.Code that prepares data for a target Scenario can accept a ScenarioInfo instance. This avoids the need to load a Scenario, which can be slow under some conditions.
ScenarioInfo objects can also be used (e.g. by
apply_spec()) to describe the contents of a Scenario before it is created.ScenarioInfo objects have the following convenience attributes:
Elements of
ixmp/message_ixsets.Trueif a MESSAGE-MACRO scenario.Elements of the set ‘node’.
Elements of the set ‘year’ that are >= the first model year.
First model year, if set, else
Y[0].pandas.DataFramewith validyear_vtg,year_actpairs.- Parameters
scenario (message_ix.Scenario) – If given,
setis initialized from this existing scenario.
-
property
N¶ Elements of the set ‘node’.
-
property
Y¶ Elements of the set ‘year’ that are >= the first model year.
-
year_from_codes(codes: List[sdmx.model.Code])[source]¶ Update using a list of codes.
The following are updated:
Any existing values are discarded.
After this, the attributes
y0andYgive the first model year and model years, respectively.Examples
Get a particular code list, create a ScenarioInfo instance, and update using the codes:
>>> years = get_codes("year/A") >>> info = ScenarioInfo() >>> info.year_from_codes(years)
Use populated values:
>>> info.y0 2020 >>> info.Y[:3] [2020, 2030, 2040] >>> info.Y[-3:] [2090, 2100, 2110]
-
property
yv_ya¶ pandas.DataFramewith validyear_vtg,year_actpairs.