Building models (model.build)

apply_spec() can be used to be build (compose, assemble, construct, …) models given three pieces of information:

  • A scenario to be used as a basis.

  • A specification, or spec, which is a dict of ScenarioInfo objects; see below.

  • An optional function that adds or produces data to add to the scenario.

The spec is applied as follows:

  1. For each set that exists in scenario:

    1. Required elements from spec['require'], if any, are checked.

      If they are missing, apply_spec() raises ValueError. This indicates that spec is not compatible with the given scenario.

    2. Elements from spec['remove'], if any, are removed.

      Any parameter values which reference these set elements are also removed, using strip_par_data().

    3. New set elements from spec['add'] are added.

  2. Elements in spec['add'].set['unit'] are added to the Platform on which scenario is stored.

  3. The data argument, a function, is called with scenario as the first argument, and a keyword argument dry_run from apply_spec(). data may either add to scenario directly (by calling Scenario.add_par() and similar methods); or it can return a dict that can be passed to apply_par_data().

The following modules use this workflow and can be examples for developing similar code:

Code reference

message_ix_models.model.build.apply_spec(scenario: message_ix.core.Scenario, spec: Mapping[str, message_ix_models.util.scenarioinfo.ScenarioInfo], data: Optional[Callable] = None, **options)[source]

Apply spec to scenario.

Parameters
  • spec – A ‘specification’: dict with ‘require’, ‘remove’, and ‘add’ keys and ScenarioInfo objects as values.

  • data (callable, optional) – Function to add data to scenario. data can either manipulate the scenario directly, or return a dict compatible with add_par_data().

  • dry_run (bool) – Don’t modify scenario; only show what would be done. Default False. Exceptions will still be raised if the elements from spec['required'] are missing; this serves as a check that the scenario has the required features for applying the spec.

  • fast (bool) – Do not remove existing parameter data; increases speed on large scenarios.

  • quiet (bool) – Only show log messages at level ERROR and higher. If False (default), show log messages at level DEBUG and higher.

  • message (str) – Commit message.

See also

add_par_data, strip_par_data, Code, ScenarioInfo

message_ix_models.model.build.ellipsize(elements: List) str[source]

Generate a short string representation of elements.

If the list has more than 5 elements, only the first two and last two are shown, with “…” between.