Container#

class gamspy.Container(load_from: str | os.PathLike | Container | gt.Container | None = None, system_directory: str | os.PathLike | None = None, working_directory: str | os.PathLike | None = None, debugging_level: Literal['keep', 'keep_on_error', 'delete'] = 'keep_on_error', options: Options | None = None, output: TextIO | None = None)[source]#

Bases: object

Central workspace for building, modifying, executing, and exchanging data with GAMS models.

https://gamspy.readthedocs.io/en/latest/reference/gamspy._container.html

A Container owns all GAMSPy symbols (sets, parameters, variables, equations, models) and manages synchronization with the GAMS execution engine.

A container can:

  • Create and store symbols

  • Load symbols and records from GDX/G00 files

  • Synchronize modified symbols with GAMS

  • Generate and persist GAMS code and data files

  • Act as a context manager.

Parameters:
load_fromstr, os.PathLike, Container, gt.Container, optional

Source to initialize the container from:

  • .gdx file: loads symbols and records from a GDX file.

  • .g00 file: restarts from a GAMS save file.

  • Container: Copies symbols from the given container into the new container.

system_directorystr, os.PathLike, optional

Path to the directory that holds the GAMS installation, by default None

working_directorystr, os.PathLike, optional

Directory used for temporary files (.gms, .lst, .gdx). If omitted, a temporary directory is created.

debugging_level{“keep”, “keep_on_error”, “delete”}, optional

Controls whether temporary files are retained:

  • "keep": Keep files and generated GAMS code.

  • "keep_on_error": Keep files only on errors (default).

  • "delete": Always clean up.

optionsOptions, optional

Global options for the overall execution

outputTextIO, optional

Stream to which GAMS output is written.

Attributes:
data

The dictionary that contains all symbols in the Container.

in_miro

Indicates whether the container is executed inside a GAMS MIRO context.

working_directory

Absolute path of the working directory used by this container.

Methods

addAlias([name, alias_with])

Creates a new Alias and adds it to the container

addEquation([name, type, domain, ...])

Creates an Equation and adds it to the Container

addGamsCode(gams_code)

Adds an arbitrary GAMS code to the generate .gms file.

addModel([name, description, problem, ...])

Creates a Model and adds it to the Container

addParameter([name, domain, records, ...])

Creates a Parameter and adds it to the Container

addSet([name, domain, is_singleton, ...])

Creates a Set and adds it to the container.

addUniverseAlias([name])

Creates a new UniverseAlias and adds it to the container

addVariable([name, type, domain, records, ...])

Creates a Variable and adds it to the Container

close()

Close the connection to the GAMS execution engine and release resources.

copy([working_directory])

Creates a copy of the Container.

describeAliases([symbols])

Provides a structural summary of the specified Alias symbols as a pandas DataFrame.

describeEquations([symbols])

Provides a statistical and structural summary of the specified Equation symbols as a pandas DataFrame.

describeParameters([symbols])

Provides a statistical summary of the specified Parameter symbols as a pandas DataFrame.

describeSets([symbols])

Provides a structural summary of the specified Set symbols as a pandas DataFrame.

describeVariables([symbols])

Provides a statistical and structural summary of the specified Variable symbols as a pandas DataFrame.

gamsJobName()

Returns the name of the latest GAMS job that was executed

gdxInputPath()

Path to the input GDX file

gdxOutputPath()

Path to the output GDX file

generateGamsString([path, show_raw])

Return the generated GAMS code executed by this container.

getAliases()

Retrieves all Alias and UniverseAlias symbols present in the Container.

getEquations()

Returns all equation symbols in the Container.

getParameters()

Retrieves all Parameter symbols present in the Container.

getSets()

Retrieves all Set symbols present in the Container.

getSymbols([symbols])

Retrieves specific symbols from the Container by their names.

getVariables([types])

Retrieves all Variable symbols in the Container, optionally filtering by variable type.

hasSymbols(symbols)

Checks if the specified symbol or symbols exist in the Container.

importExtrinsicLibrary(lib_path, functions)

Imports an extrinsic library to the GAMS environment.

listAliases()

Lists the names of all Alias and UniverseAlias symbols in the Container.

listEquations([types])

Lists the names of all equations in the Container, optionally filtering by equation type.

listParameters()

Lists the names of all Parameter symbols in the Container.

listSets()

Lists the names of all Set symbols in the Container.

listSymbols()

Lists the names of all symbols present in the Container.

listVariables([types])

Lists the names of all variables in the Container, optionally filtering by variable type.

loadRecordsFromGdx(load_from[, symbol_names])

Loads data of the given symbols from a GDX file.

read(load_from[, symbol_names, encoding, ...])

Read symbols and records from a GDX file or another container.

serialize(path)

Serializes the Container into a zip file.

setRecords(records, *[, uels_on_axes])

Set records for multiple symbols in a single batch operation.

write(write_to[, symbol_names, mode, ...])

Write symbols and records to a GDX file.

writeSolverOptions(solver, solver_options[, ...])

Writes solver options of the specified solver to the working directory.

Examples

Basic usage

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=["i1", "i2"])

Loading from an existing GDX

>>> m.write("data.gdx")
>>> m2 = gp.Container(load_from="data.gdx")
>>> list(m2.data.keys()) == list(m.data.keys())
True

Using as a context manager

>>> with gp.Container() as m:
...     i = gp.Set(m, "i")
...     j = gp.Set(m, "j", domain=i)
addAlias(name: str | None = None, alias_with: Set | Alias = None) Alias[source]#

Creates a new Alias and adds it to the container

Parameters:
namestr, optional

Name of the alias.

alias_withSet | Alias

Alias set object.

Returns:
Alias
Raises:
TypeError

In case the alias_with is different than a Set or an Alias

ValueError

If there is symbol with same name but different type in the Container

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = m.addSet("i")
>>> a = m.addAlias("a", i)
addEquation(name: str | None = None, type: str | EquationType = 'regular', domain: DomainType | None = None, definition: Variable | Operation | Expression | None = None, records: VarEquRecordsType | None = None, domain_forwarding: bool | list[bool] = False, description: str = '', uels_on_axes: bool = False, is_miro_output: bool = False, definition_domain: list | None = None) Equation[source]#

Creates an Equation and adds it to the Container

Parameters:
namestr, optional

Name of the equation. If omitted, a unique name is generated.

typestr

Type of the equation. “regular” by default.

domainSequence[Set | Alias] | Set | Alias, optional

Domain of the variable.

definition: Expression, optional

Definition of the equation.

recordsSequence | np.ndarray | int | float | pd.DataFrame | pd.Series | dict, optional

Records of the equation.

domain_forwardingbool | list[bool], optional

Whether the equation forwards the domain.

descriptionstr, optional

Description of the equation.

uels_on_axes: bool

Assume that symbol domain information is contained in the axes of the given records.

definition_domain: list, optional

Definiton domain of the equation.

is_miro_outputbool

Whether the symbol is a GAMS MIRO output symbol. See: https://gams.com/miro/tutorial.html

Returns:
Equation
Raises:
err

In case arguments are not valid

ValueError

If there is symbol with same name but different type in the Container

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = m.addEquation("i")
addGamsCode(gams_code: str) None[source]#

Adds an arbitrary GAMS code to the generate .gms file. Using addGAMSCode might result in a license error if no GAMSpy++ license is used.

Parameters:
gams_codestr

GAMS code that you want to insert.

Examples

>>> from gamspy import Container
>>> m = Container()
>>> m.addGamsCode("scalar piHalf / [pi/2] /;")
>>> m["piHalf"].toValue()
np.float64(1.5707963267948966)
addModel(name: str | None = None, description: str = '', problem: Problem | str = Problem.MIP, equations: Sequence[Equation] = [], sense: Sense | str = Sense.FEASIBILITY, objective: Variable | Expression | None = None, matches: dict[Equation | Sequence[Equation], Variable | Sequence[Variable]] | None = None, limited_variables: Sequence[ImplicitVariable] | None = None, external_module: str | None = None) Model[source]#

Creates a Model and adds it to the Container

Parameters:
namestr, optional

Name of the model. If omitted, a unique name is generated.

descriptionstr, optional

Description of the model.

equationsSequence[Equation]

Sequence of Equation objects.

problemProblem or str, optional

‘LP’, ‘NLP’, ‘QCP’, ‘DNLP’, ‘MIP’, ‘RMIP’, ‘MINLP’, ‘RMINLP’, ‘MIQCP’, ‘RMIQCP’, ‘MCP’, ‘CNS’, ‘MPEC’, ‘RMPEC’, ‘EMP’, or ‘MPSGE’, by default Problem.LP.

senseSense, optional

“MIN”, “MAX”, or “FEASIBILITY”.

objectiveVariable | Expression, optional

Objective variable to minimize or maximize or objective itself.

matchesdict[Equation | Sequence[Equation], Variable | Sequence[Variable]], optional

Equation - Variable matches for MCP models.

limited_variablesSequence[ImplicitVariable], optional

Allows limiting the domain of variables used in a model.

external_module: str, optional

The name of the external module in which the external equations are implemented

Returns:
Model

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> x = gp.Variable(m, "x")
>>> e = gp.Equation(m, "e", definition=x >= 1)
>>> model = m.addModel(name="demo", equations=[e], problem="LP", sense="MIN", objective=x)
addParameter(name: str | None = None, domain: DomainType | None = None, records: ParameterRecordsType | None = None, domain_forwarding: bool | list[bool] = False, description: str = '', uels_on_axes: bool = False, is_miro_input: bool = False, is_miro_output: bool = False, is_miro_table: bool = False) Parameter[source]#

Creates a Parameter and adds it to the Container

Parameters:
namestr, optional

Name of the parameter. If omitted, a unique name is generated.

domainSequence[Set | Alias | str] | Set | Alias | Dim | str, optional

Domain over which the parameter is defined.

recordsint | float | pd.DataFrame | np.ndarray | list, optional

Records of the parameter.

domain_forwardingbool | list[bool], optional

Whether the parameter forwards the domain.

descriptionstr, optional

Human-readable description.

uels_on_axesbool

Assume that symbol domain information is contained in the axes of the given records.

is_miro_inputbool

Whether the symbol is a GAMS MIRO input symbol. See: https://gams.com/miro/tutorial.html

is_miro_outputbool

Whether the symbol is a GAMS MIRO output symbol. See: https://gams.com/miro/tutorial.html

is_miro_tablebool

Whether the symbol is a GAMS MIRO table symbol. See: https://gams.com/miro/tutorial.html

Returns:
Parameter
Raises:
err

In case arguments are not valid

ValueError

If there is symbol with same name but different type in the Container

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> a = m.addParameter("a")
addSet(name: str | None = None, domain: DomainType | None = None, is_singleton: bool = False, records: SetRecordsType | None = None, domain_forwarding: bool | list[bool] = False, description: str = '', uels_on_axes: bool = False, is_miro_input: bool = False, is_miro_output: bool = False) Set[source]#

Creates a Set and adds it to the container.

Parameters:
namestr, optional

Name of the set. If omitted, a unique name is generated.

domainSequence[Set | Alias | str] | Set | Alias | str, optional

Domain over which the set is defined.

is_singletonbool, optional

If True, the set may contain at most one element.

recordspd.DataFrame | np.ndarray | list, optional

Initial elements of the set.

domain_forwardingbool | list[bool], optional

Enable domain forwarding.

descriptionstr, optional

Human-readable description.

uels_on_axesbool

Assume that symbol domain information is contained in the axes of the given records.

is_miro_inputbool

Whether the symbol is a GAMS MIRO input symbol. See: https://gams.com/miro/tutorial.html

is_miro_outputbool

Whether the symbol is a GAMS MIRO output symbol. See: https://gams.com/miro/tutorial.html

Returns:
Set
Raises:
err

In case arguments are not valid

ValueError

When there is symbol with same name in the Container

Examples

Simple set:

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = m.addSet("i", records=["a", "b"])

Indexed set:

>>> j = m.addSet("j", domain=i)

Singleton set:

>>> s = m.addSet("s", is_singleton=True, records=["s1"])
addUniverseAlias(name: str | None = None) UniverseAlias[source]#

Creates a new UniverseAlias and adds it to the container

Parameters:
namestr, optional

Name of the universe alias.

Returns:
UniverseAlias
Raises:
ValueError

If there is symbol with same name but different type in the Container

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> a = m.addUniverseAlias("a")
addVariable(name: str | None = None, type: str = 'free', domain: DomainType | None = None, records: VarEquRecordsType | None = None, domain_forwarding: bool | list[bool] = False, description: str = '', uels_on_axes: bool = False, is_miro_output: bool = False) Variable[source]#

Creates a Variable and adds it to the Container

Parameters:
namestr, optional

Name of the variable. If omitted, a unique name is generated.

typestr, optional

Type of the variable. “free” by default.

domainSequence[Set | Alias | str] | Set | Alias | Dim | str, optional

Domain of the variable.

recordsSequence | np.ndarray | int | float | pd.DataFrame | pd.Series | dict, optional

Records of the variable.

domain_forwardingbool | list[bool], optional

Whether the variable forwards the domain.

descriptionstr, optional

Description of the variable.

is_miro_outputbool

Whether the symbol is a GAMS MIRO output symbol. See: https://gams.com/miro/tutorial.html

Returns:
Variable
Raises:
err

In case arguments are not valid

ValueError

If there is symbol with same name but different type in the Container

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> v = m.addVariable("v")
close() None[source]#

Close the connection to the GAMS execution engine and release resources.

After calling this method, the container must not be used for further model execution or data synchronization. Symbol data remains accessible for read-only inspection.

Examples

>>> import gamspy as gp
>>> m = gp.Container()  # Starts running the GAMS execution engine.
>>> m.close()           # Closes the connection to the execution engine.
copy(working_directory: str | None = None) Container[source]#

Creates a copy of the Container. Should not be invoked after creating the model.

Parameters:
working_directorystr, optional

Working directory of the new Container, by default None

Returns:
Container
Raises:
ValidationError

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i")
>>> new_cont = m.copy(working_directory="test")
>>> new_cont.data.keys() == m.data.keys()
True
gamsJobName() str | None[source]#

Returns the name of the latest GAMS job that was executed

Returns:
str | None

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=["seattle", "san-diego"], description="canning plants")
>>> gams_file_name = f"{m.gamsJobName()}.gms"
gdxInputPath() str[source]#

Path to the input GDX file

Returns:
str

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=["seattle", "san-diego"], description="canning plants")
>>> gdx_path = m.gdxInputPath()
gdxOutputPath() str[source]#

Path to the output GDX file

Returns:
str

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"], description="canning plants")
>>> ii = gp.Set(m, name="ii", domain=i, description="seattle plant")
>>> ii['seattle'] = True
>>> gdx_path = m.gdxOutputPath()
generateGamsString(path: str | None = None, *, show_raw: bool = False) str[source]#

Return the generated GAMS code executed by this container.

Only available when debugging_level='keep' was specified at container creation time.

Parameters:
pathstr, optional

File path to write the generated GAMS code to.

show_rawbool, optional

If True, strips data-loading and auxiliary statements, leaving the core model formulation.

Returns:
str

Generated GAMS code.

Raises:
ValidationError

If debugging level is not "keep".

Examples

>>> import gamspy as gp
>>> m = gp.Container(debugging_level="keep")
>>> i = gp.Set(m, "i")
>>> gams = m.generateGamsString()
getEquations() list[Equation][source]#

Returns all equation symbols in the Container.

Returns:
list[Equation]

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> eq1 = gp.Equation(m, name="eq1")
>>> eq2 = gp.Equation(m, name="eq2")
>>> equation_objects = m.getEquations()
importExtrinsicLibrary(lib_path: str, functions: dict[str, str]) ExtrinsicLibrary[source]#

Imports an extrinsic library to the GAMS environment.

Parameters:
lib_pathstr

Path to the .so, .dylib or .dll file that contains the extrinsic library

functionsdict[str, str]

Names of the functions as a dictionary. Key is the desired function name in GAMSPy and value is the function name in the extrinsic library.

Returns:
ExtrinsicLibrary
Raises:
FileNotFoundError

In case the extrinsic library does not exist in the given path.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> # Assuming 'trilib.so' is a valid library path
>>> # lib = m.importExtrinsicLibrary("trilib.so", {"my_cos": "Cosine", "my_sin": "Sine"})
>>> # c = lib.my_cos(0)
loadRecordsFromGdx(load_from: str | Path, symbol_names: list[str] | dict[str, str] | None = None) None[source]#

Loads data of the given symbols from a GDX file. If no symbol names are given, data of all symbols are loaded.

Parameters:
load_fromstr

Path to the GDX file

symbol_nameslist[str], dict[str, str], optional

Symbol names whose data will be load from GDX, by default None. Default option loads records of all symbols in the GDX file. If given as a dict, keys are the symbol names in the GDX file, and values are the names of the GAMSPy symbols.

Examples

>>> from gamspy import Container, Set
>>> m = Container()
>>> i = Set(m, "i", records=["i1", "i2"])
>>> m.write("test.gdx")
>>> m2 = Container()
>>> i = Set(m2, "i")
>>> m2.loadRecordsFromGdx("test.gdx")
>>> print(i.records.equals(m2["i"].records))
True
read(load_from: str | PathLike | Container | Container, symbol_names: list[str] | None = None, encoding: str | None = None, *, load_records: bool = True) None[source]#

Read symbols and records from a GDX file or another container.

Parameters:
load_fromstr | os.PathLike | Container | gt.Container

Source to read from.

symbol_nameslist[str], optional

Names of symbols to read. If omitted, all symbols are read.

modestr, optional

GDX read mode (“category”, or “string”, default: “category”).

encodingstr, optional

Text encoding for symbol metadata.

load_recordsbool, optional

Whether to load symbol records (default: True).

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=["a", "b"])
>>> m.write("example.gdx")
>>> m2 = gp.Container()
>>> m2.read("example.gdx")
>>> "i" in m2.data
True

Reading selected symbols only

>>> m2 = gp.Container()
>>> m2.read("example.gdx", symbol_names=["i"])
serialize(path: str) None[source]#

Serializes the Container into a zip file.

Parameters:
pathstr

Path to the zip file.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=range(3))
>>> gp.serialize(m, "serialization_path.zip")
setRecords(records: dict[SymbolType, Any], *, uels_on_axes: bool | list[bool] = False) None[source]#

Set records for multiple symbols in a single batch operation.

This is functionally equivalent to calling symbol.setRecords for each symbol, but triggers only one synchronization with GAMS.

Parameters:
recordsdict[SymbolType, Any]

Mapping from symbols to their new records.

uels_on_axesbool | list[bool], optional

Whether domain labels (UELs) are stored on pandas axes. Either a single boolean applied to all symbols, or a list matching records order.

Raises:
ValidationError

If uels_on_axes length does not match records length.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i")
>>> j = gp.Set(m, "j")
>>> m.setRecords({i: ["a", "b"], j: [1, 2, 3]})
write(write_to: Path | str, symbol_names: list[str] | None = None, mode: str | None = None, *, compress: bool | None = None, eps_to_zero: bool = True) None[source]#

Write symbols and records to a GDX file.

Parameters:
write_toPath | str

Target GDX file path.

symbol_nameslist[str], optional

Symbols to write. If omitted, all symbols are written.

compressbool, optional

Whether to compress the GDX file.

modestr, optional

Write mode (passed to GAMS Transfer).

eps_to_zerobool, optional

Convert EPS values to zero before writing.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=["x", "y"])
>>> m.write("out.gdx")
writeSolverOptions(solver: str, solver_options: dict | str | Path, file_number: int = 1) None[source]#

Writes solver options of the specified solver to the working directory.

Parameters:
solverstr

Name of the solver.

solver_optionsdict | str | Path

Options of the specified solver or path to an existing solver options file.

file_numberint

Solver option file number. Equivalent to optfile option of GAMS. See https://gams.com/latest/docs/UG_GamsCall.html#GAMSAOoptfile for more details.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> m.writeSolverOptions("conopt", solver_options={"rtmaxv": "1.e12"})
property data: dict[str, SymbolType]#

The dictionary that contains all symbols in the Container. Keys are symbol names and values are the symbols themselves.

Returns:
dict[str, SymbolType]

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i")
>>> j = gp.Set(m, "j")
>>> m.data
{'i': Set(name='i', domain=['*']), 'j': Set(name='j', domain=['*'])}
property in_miro: bool#

Indicates whether the container is executed inside a GAMS MIRO context. When running under MIRO, input data is typically provided by MIRO itself. This flag can be used to skip expensive or redundant data-loading steps (e.g., reading Excel files).

Returns:
bool

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> if not m.in_miro:
...     pass # e.g. load data from files
property working_directory: str#

Absolute path of the working directory used by this container. The directory contains generated GAMS input/output files such as .gms, .lst, .gdx and temporary scratch files.

Returns:
str

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> m.working_directory
'...'