Mathematical models (ixmp.model)

By default, the ix modeling platform is installed with ixmp.model.gams.GAMSModel, which performs calculations by executing code stored in GAMS files.

However, ix modeling platform is extensible to support other methods of performing calculations or optimization. Developers wishing to add such capabilities may subclass ixmp.model.base.Model and implement its methods.

Provided models

ixmp.model.MODELS: dict[str, type] = {'dantzig': <class 'ixmp.model.dantzig.DantzigModel'>, 'default': <class 'ixmp.model.gams.GAMSModel'>, 'gams': <class 'ixmp.model.gams.GAMSModel'>}[source]

Mapping from names to available models. To register additional models, add elements to this variable.

ixmp.model.get_model(name, **model_options)[source]

Return a model for name (or the default) with model_options.

class ixmp.model.gams.GAMSInfo[source]

Information about the GAMS installation.

property java_api_dir: Path[source]

Java API files subdirectory of system_dir.

system_dir: Path[source]

System directory.

version: str | None[source]

GAMS version as a string, for instance “24.7.4”.

class ixmp.model.gams.GAMSModel(name_=None, **model_options)[source]

Generic base class for ixmp models using GAMS.

GAMSModel solves a Scenario using the following steps:

  1. All Scenario data is written to a model input file in GDX format.

  2. A GAMS program is run to perform calculations, producing output in a GDX file.

  3. Output, or solution, data is read from the GDX file and stored in the Scenario.

When created and run(), GAMSModel constructs file paths and other necessary values using format strings. The defaults may be overridden by the keyword arguments to the constructor:

Parameters:
  • name (str, optional) – Override the name attribute to provide the model_name for format strings.

  • model_file (str, optional) – Path to GAMS file, including .gms extension. Default: model_name.gms in the current directory.

  • case (str, optional) – Run or case identifier to use in GDX file names. Default: '{scenario.model}_{scenario.name}', where scenario is the Scenario object passed to run(). Formatted using model_name and scenario.

  • in_file (str, optional) – Path to write GDX input file. Default: '{model_name}_in.gdx'. Formatted using model_name, scenario, and case.

  • out_file (str, optional) – Path to read GDX output file. Default: '{model_name}_out.gdx'. Formatted using model_name, scenario, and case.

  • solve_args (list of str, optional) –

    Arguments to be passed to GAMS, e.g. to identify the model input and output files. Each formatted using model_file, scenario, case, in_file, and out_file. Default:

    • '--in="{in_file}"'

    • '--out="{out_file}"'

  • gams_args (list of str, optional) –

    Additional arguments passed directly to GAMS without formatting, e.g. to control solver options or behaviour. See the GAMS Documentation. For example:

    • gams_args=["iterLim=10"] limits the solver to 10 iterations.

  • quiet (bool, optional) – If True, add “LogOption=2” to gams_args to redirect most console output during the model run to the log file. Default False, so “LogOption=4” is added. Any “LogOption” value provided explicitly via gams_args takes precedence.

  • check_solution (bool, optional) – If True, raise an exception if the GAMS solver did not reach optimality. (Only for MESSAGE-scheme Scenarios.)

  • comment (str, optional) – Comment added to Scenario when importing the solution. If omitted, no comment is added.

  • equ_list (list of str, optional) – Equations to be imported from the out_file. Default: all.

  • var_list (list of str, optional) – Variables to be imported from the out_file. Default: all.

  • record_version_packages (list of str, optional) – Names of Python packages to record versions. Default: ["ixmp"]. See record_versions().

defaults: MutableMapping[str, Any] = {'case': '{scenario.model}_{scenario.scenario}', 'check_solution': True, 'comment': None, 'equ_list': None, 'gams_args': [], 'in_file': '{cwd}/{model_name}_in.gdx', 'model_file': '{model_name}.gms', 'out_file': '{cwd}/{model_name}_out.gdx', 'quiet': False, 'record_version_packages': ['ixmp'], 'solve_args': ['--in="{in_file}"', '--out="{out_file}"'], 'use_temp_dir': True, 'var_list': None}[source]

Default values and format strings for options.

format(value)[source]

Helper for recursive formatting of model options.

value is formatted with replacements from the attributes of self.

format_exception(exc: Exception, model_file: Path, backend_class: type) Exception[source]

Format a user-friendly exception when GAMS errors.

format_option(name)[source]

Retrieve the option name and format it.

name: str = 'default'[source]

Model name.

record_versions()[source]

Store Python package versions as set elements to be written to GDX.

The values are stored in a 2-dimensional set named ixmp_version, where the first element is the package name, and the second is its version according to importlib.metadata.version()). If the package is not installed, the string “(not installed)” is stored.

remove_temp_dir(msg='after run()')[source]

Remove the temporary directory, if any.

run(scenario)[source]

Execute the model.

Among other steps:

  • record_versions() is called.

  • Data is written to a GDX file using the associated Backend.

  • The ixmp_version set created by record_versions() is deleted.

  • gams is invoked to execute the model file.

  • If gams completes successfully:

    • GAMS output/model solution data is read from a GDX file.

ixmp.model.gams.RETURN_CODE = {0: 'Normal return', 1: 'Solver is to be called, the system should never return this number', 2: 'There was a compilation error', 3: 'There was an execution error', 4: 'System limits were reached', 5: 'There was a file error', 6: 'There was a parameter error', 7: 'There was a licensing error', 8: 'There was a GAMS system error', 9: 'GAMS could not be started', 10: 'Out of memory', 11: 'Out of disk', 109: 'Could not create process/scratch directory', 110: 'Too many process/scratch directories', 112: 'Could not delete the process/scratch directory', 113: 'Could not write the script gamsnext', 114: 'Could not write the parameter file', 115: 'Could not read environment variable', 136: 'Driver error: internal error: cannot load option handling library', 141: 'Cannot add path / unknown UNIX environment / cannot set environment variable', 144: 'Could not spawn the GAMS language compiler (gamscmex)', 145: 'Current directory (curdir) does not exist', 146: 'Cannot set current directory (curdir)', 148: 'Blank in system directory', 149: 'Blank in current directory', 150: 'Blank in scratch extension (scrext)', 151: 'Unexpected cmexRC', 152: 'Could not find the process directory (procdir)', 153: 'CMEX library not be found (experimental)', 154: 'Entry point in CMEX library could not be found (experimental)', 155: 'Blank in process directory', 156: 'Blank in scratch directory', 160: 'Driver error: internal error: GAMS compile and execute module not found', 184: 'Driver error: problems getting current directory', 208: 'Driver error: internal error: cannot install interrupt handler', 232: 'Driver error: incorrect command line parameters for gams'}[source]

Return codes used by GAMS, from https://www.gams.com/latest/docs/UG_GAMSReturnCodes.html . Values over 256 are only valid on Windows, and are returned modulo 256 on other platforms.

ixmp.model.gams.gams_info() GAMSInfo[source]

Return an instance of GAMSInfo.

ixmp.model.gams.gams_version() str | None[source]

Return GAMSInfo.version.

class ixmp.model.dantzig.DantzigModel(name_=None, **model_options)[source]

Dantzig’s cannery/transport problem as a GAMSModel.

Provided for testing ixmp code.

defaults: MutableMapping[str, Any] = ChainMap({'model_file': PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/iiasa-energy-program-ixmp/envs/latest/lib/python3.11/site-packages/ixmp/model/dantzig.gms')}, {'model_file': '{model_name}.gms', 'case': '{scenario.model}_{scenario.scenario}', 'in_file': '{cwd}/{model_name}_in.gdx', 'out_file': '{cwd}/{model_name}_out.gdx', 'solve_args': ['--in="{in_file}"', '--out="{out_file}"'], 'gams_args': [], 'check_solution': True, 'comment': None, 'equ_list': None, 'var_list': None, 'quiet': False, 'use_temp_dir': True, 'record_version_packages': ['ixmp']})[source]

Default values and format strings for options.

classmethod initialize(scenario, with_data=False)[source]

Initialize the problem.

If with_data is True (default: False), the set and parameter values from the original problem are also populated. Otherwise, the sets and parameters are left empty.

name: str = 'dantzig'[source]

Model name.

Model API

exception ixmp.model.base.ModelError[source]

Error in model code—that is, Model.run() or other code called by it.

class ixmp.model.base.Model(name, **kwargs)[source]

In the following, the words required, optional, etc. have specific meanings as described in IETF RFC 2119.

Model is an abstract class; this means it must be subclassed. It has two required methods that must be overridden by subclasses:

__init__(name, **kwargs)

Constructor.

run(scenario)

Execute the model.

The following attributes and methods are optional in subclasses. The default implementations are either empty or implement reasonable default behaviour.

enforce(scenario)

Enforce data consistency in scenario.

initialize(scenario)

Set up scenario with required items.

initialize_items(scenario, items)

Helper for initialize().

name

Name of the model.

abstract __init__(name, **kwargs)[source]

Constructor.

Required.

Parameters:

kwargs

Model options, passed directly from Scenario.solve().

Model subclasses MUST document acceptable option values.

static enforce(scenario)[source]

Enforce data consistency in scenario.

Optional; the default implementation does nothing. Subclass implementations of enforce():

  • should modify the contents of sets and parameters so that scenario contains structure and data that is consistent with the underlying model.

  • must not add or remove sets or parameters; for that, use initialize().

enforce() is always called by run() before the model is run or solved; it may be called manually at other times.

Parameters:

scenario (Scenario) – Object on which to enforce data consistency.

classmethod initialize(scenario)[source]

Set up scenario with required items.

Optional; the default implementation does nothing. Subclass implementations of initialize():

  • may add sets, set elements, and/or parameter values.

  • may accept any number of keyword arguments to control behaviour.

  • must not modify existing parameter data in scenario, either by deleting or overwriting values; for that, use enforce().

Parameters:

scenario (Scenario) – Object to initialize.

See also

initialize_items

classmethod initialize_items(scenario: Scenario, items: Mapping[str, dict]) None[source]

Helper for initialize().

All of the items are added to scenario. Existing items are not modified. Errors are logged if the description in items conflicts with the index set(s) and/or index name(s) of existing items.

initialize_items may perform one commit. scenario is in the same state (checked in, or checked out) after initialize_items is complete.

Parameters:
  • scenario (Scenario) – Object to initialize.

  • items – Keys are names of ixmp items (set, parameter, equation, or variable) to initialize. Values are dict, and each must have the key ‘ix_type’ (one of ‘set’, ‘par’, ‘equ’, or ‘var’); any other entries are keyword arguments to the corresponding methods such as init_set().

Raises:

ValueError – if scenario has a solution, i.e. has_solution() is True.

name: str = 'base'[source]

Name of the model.

abstract run(scenario)[source]

Execute the model.

Required. Implementations of run():

Parameters:

scenario (Scenario) – Scenario object to solve by running the Model.