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'>}¶
Mapping from names to available models. To register additional models, add elements to this variable.
- ixmp.model.get_model(name, **model_options)¶
Return a model for name (or the default) with model_options.
- class ixmp.model.gams.GAMSModel(name_=None, **model_options)¶
General class for ixmp models using GAMS.
GAMSModel solves a Scenario using the following steps:
All Scenario data is written to a model input file in GDX format.
A GAMS program is run to perform calculations, producing output in a GDX file.
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. Thedefaults
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 theScenario
object passed torun()
. 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:
["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. DefaultFalse
, 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.
- defaults: Mapping[str, object] = {'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, 'solve_args': ['--in="{in_file}"', '--out="{out_file}"'], 'use_temp_dir': True, 'var_list': None}¶
Default values and format strings for options.
- format(value)¶
Helper for recursive formatting of model options.
value is formatted with replacements from the attributes of self.
- format_exception(exc, model_file)¶
Format a user-friendly exception when GAMS errors.
- format_option(name)¶
Retrieve the option name and format it.
- name = 'default'¶
Model name.
- remove_temp_dir(msg='after run()')¶
Remove the temporary directory, if any.
- run(scenario)¶
Execute the model.
- 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'}¶
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_version()¶
Return the GAMS version as a string, e.g. ‘24.7.4’.
- class ixmp.model.dantzig.DantzigModel(name_=None, **model_options)¶
Dantzig’s cannery/transport problem as a
GAMSModel
.Provided for testing
ixmp
code.
Model API¶
- class ixmp.model.base.Model(name, **kwargs)¶
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 REQURIED methods that MUST be overridden by subclasses:
Name of the model.
__init__
(name, **kwargs)Constructor.
initialize
(scenario)Set up scenario with required items.
initialize_items
(scenario, items)Helper for
initialize()
.run
(scenario)Execute the model.
- abstract __init__(name, **kwargs)¶
Constructor.
- Parameters
kwargs –
Model options, passed directly from
Scenario.solve()
.Model subclasses MUST document acceptable option values.
- classmethod initialize(scenario)¶
Set up scenario with required items.
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.
- Parameters
scenario (Scenario) – Object to initialize.
See also
- classmethod initialize_items(scenario, items)¶
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 (dict of (str -> dict)) – Each key is the name of an ixmp item (set, parameter, equation, or variable) to initialize. Each dict must have the key ‘ix_type’; one of ‘set’, ‘par’, ‘equ’, or ‘var’; any other entries are keyword arguments to the methods
init_set()
etc.
- Raises
ValueError – if scenario has a solution, i.e.
has_solution()
isTrue
.
- name = 'base'¶
Name of the model.