Container#

class gamspy.Container(load_from: str | None = None, system_directory: str | None = None, working_directory: str | None = None, debugging_level: str = 'keep_on_error', options: Options | None = None, miro_protect: bool = True)[source]#

Bases: Container

A container is an object that holds all symbols and operates on them.

Parameters:
load_fromstr, optional

Path to the GDX file to be loaded from, by default None

system_directorystr, optional

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

working_directorystr, optional

Path to the working directory to store temporary files such .lst, .gms, .gdx, .g00 files.

debugging_levelstr, optional

Decides on keeping the temporary files generate by GAMS, by default “keep_on_error”

optionsOptions, optional

Global options for the overall execution

miro_protectbool, optional

Protects MIRO input symbol records from being re-assigned, by default True

Attributes:
summary

This property returns a summary of the container.

system_directory

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, problem[, equations, sense, ...])

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)

Add a Universe Alias to the GAMS container

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

Creates a Variable and adds it to the Container

close()

Stops the socket and releases resources.

copy(working_directory)

Creates a copy of the Container.

describeAliases([symbols])

Generate a DataFrame describing alias symbols in the GAMS Container.

describeEquations([symbols])

Generate a DataFrame describing equation symbols in the GAMS Container.

describeParameters([symbols])

Generate a DataFrame describing parameter symbols in the GAMS Container.

describeSets([symbols])

Generate a DataFrame describing sets within the GAMS Container.

describeVariables([symbols])

Generate a DataFrame describing variable symbols in the GAMS Container.

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([show_raw])

Generates the GAMS code

getAliases([is_valid])

Retrieve alias objects from the GAMS Container.

getEquations()

Returns all equation symbols in the Container.

getParameters([is_valid])

Retrieve parameter objects from the GAMS Container.

getSets([is_valid])

Retrieve set objects from the GAMS Container.

getSymbols([symbols])

Retrieve symbol objects from the GAMS Container.

getVariables([is_valid, types])

Retrieve variable objects from the GAMS Container.

hasSymbols(symbols)

Checks if specific symbol names exist in a Container

importExtrinsicLibrary(lib_path, functions)

Imports an extrinsic library to the GAMS environment.

isValid([symbols, verbose, force])

Check the validity of symbols in the GAMS Container.

loadRecordsFromGdx(load_from[, symbol_names])

Loads data of the given symbols from a gdx file.

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

Reads specified symbols from the gdx file.

removeSymbols([symbols])

Remove symbols from the Container.

renameSymbol(old_name, new_name)

Rename a symbol in the Container

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

Writes specified symbols to the gdx file.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i")
read(load_from: str, symbol_names: list[str] | None = None, load_records: bool = True, mode: str | None = None, encoding: str | None = None) None[source]#

Reads specified symbols from the gdx file. If symbol_names are not provided, it reads all symbols from the gdx file.

Parameters:
load_fromstr
symbol_namesList[str], optional
load_recordsbool
modestr, optional
encodingstr, optional

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=['i1', 'i2'])
>>> m.write("test.gdx")
>>> new_container = gp.Container()
>>> new_container.read("test.gdx")
>>> new_container.data.keys() == m.data.keys()
True
write(write_to: str, symbol_names: list[str] | None = None, compress: bool = False, mode: str | None = None, eps_to_zero: bool = True) None[source]#

Writes specified symbols to the gdx file. If symbol_names are not provided, it writes all symbols to the gdx file.

Parameters:
write_tostr
symbol_namesList[str], optional
compressbool
modestr, optional
eps_to_zerobool

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=['i1', 'i2'])
>>> m.write("test.gdx")
generateGamsString(show_raw: bool = False) str[source]#

Generates the GAMS code

Parameters:
show_rawbool, optional

Shows the raw model without data and other necessary GAMS statements, by default False.

Returns:
str

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i")
>>> gams_code = m.generateGamsString()
loadRecordsFromGdx(load_from: str, symbol_names: list[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

symbolsList[str], optional

Symbols whose data will be load from gdx, by default None

Examples

>>> from gamspy import Container, Set
>>> m = Container()
>>> i = Set(m, "i", records=["i1", "i2"])
>>> m.write("test.gdx")
>>> m2 = Container()
>>> m2.loadRecordsFromGdx("test.gdx")
>>> print(i.records.equals(m2["i"].records))
True
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 professional 08/09 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)
close() None[source]#

Stops the socket and releases resources.

addAlias(name: str, alias_with: Set | Alias) Alias[source]#

Creates a new Alias and adds it to the container

Parameters:
namestr
alias_withSet | Alias
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)
addSet(name: str, domain: list[Set | str] | None = None, is_singleton: bool = False, records: Any | None = None, domain_forwarding: bool = False, description: str = '', uels_on_axes: bool = False) Set[source]#

Creates a Set and adds it to the container

Parameters:
namestr
domainList[Set | str], optional
is_singletonbool, optional
recordsAny, optional
domain_forwardingbool, optional
descriptionstr, optional
uels_on_axesbool, optional
Returns:
Set
Raises:
err

In case arguments are not valid

ValueError

When there is symbol with same name in the Container

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = m.addSet("i")
addParameter(name: str, domain: list[str | Set] | None = None, records: Any | None = None, domain_forwarding: bool = False, description: str = '', uels_on_axes: bool = False) Parameter[source]#

Creates a Parameter and adds it to the Container

Parameters:
namestr
domainList[str | Set]], optional
recordsAny, optional
domain_forwardingbool, optional
descriptionstr, optional
uels_on_axesbool, optional
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")
addVariable(name: str, type: str = 'free', domain: list[str | Set] | None = None, records: Any | None = None, domain_forwarding: bool = False, description: str = '', uels_on_axes: bool = False) Variable[source]#

Creates a Variable and adds it to the Container

Parameters:
namestr
typestr, optional
domainList[str | Set]], optional
recordsAny, optional
domain_forwardingbool, optional
descriptionstr, optional
uels_on_axesbool, optional
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")
addEquation(name: str, type: str | EquationType = 'regular', domain: list[Set | str] | None = None, definition: Expression | None = None, records: Any | None = None, domain_forwarding: bool = False, description: str = '', uels_on_axes: bool = False, definition_domain: list[Set | str] | None = None) Equation[source]#

Creates an Equation and adds it to the Container

Parameters:
namestr
typestr
domainList[Set | str], optional
definitionDefinition, optional
recordsAny, optional
domain_forwardingbool, optional
descriptionstr, optional
uels_on_axesbool, optional
definition_domainList[Set | str], optional
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")
addModel(name: str, problem: str, equations: list[Equation] = [], sense: Literal['MIN', 'MAX'] | Sense | None = None, objective: Variable | Expression | None = None, matches: dict | None = None, limited_variables: list | None = None) Model[source]#

Creates a Model and adds it to the Container

Parameters:
namestr
equationsList[Equation]
problemstr
sense“MIN”, “MAX”, optional
objectiveVariable | Expression, optional
matchesdict, optional
limited_variableslist, optional
Returns:
Model

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> e = gp.Equation(m, "e")
>>> model = m.addModel("my_model", "LP", [e])
copy(working_directory: str) 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
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.

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()
addUniverseAlias(name: str) UniverseAlias[source]#

Add a Universe Alias to the GAMS container

Parameters:
namestr

The name of the Universe Alias symbol

Returns:
UniverseAlias

The Universe Alias object that was added

Examples

>>> import gams.transfer as gt
>>> m = gt.Container()
>>> i = m.addSet("i", records=['i1','i2'])
>>> j = m.addSet("j", records=['j1','j2','j3'])
>>> ij = m.addUniverseAlias("ij")
>>> print(ij.getUELs())
['i1', 'i2', 'j1', 'j2', 'j3']
getSymbols(symbols: str | Sequence[str] | None = None) List[AnyContainerSymbol]#

Retrieve symbol objects from the GAMS Container.

This method allows you to retrieve symbol objects from the GAMS Container based on their names.

Parameters:
symbolsstr | Sequence[str], optional

An optional parameter specifying the symbol names to retrieve. If None (default), Retrieve all symbols stored in the Container.

Returns:
List[AnyContainerSymbol]

A list of symbol objects that match the specified symbol names.

Raises:
ValueError
  • If the ‘symbols’ argument is not of type str, iterable, or NoneType.

  • If a symbol name specified in ‘symbols’ does not exist in the Container.

getSets(is_valid: bool | None = None) List[ABCSet]#

Retrieve set objects from the GAMS Container.

This method allows you to retrieve set objects from the GAMS Container based on their names.

Parameters:
is_validbool, optional

An optional boolean flag used to filter the list of sets. If None (default), all sets in the Container are returned. If True, only valid sets are included in the list. If False, only invalid sets are included in the list.

Returns:
List[ABCSet]

A list of set objects that match the specified names.

getAliases(is_valid: bool | None = None) List[ABCAlias]#

Retrieve alias objects from the GAMS Container.

This method allows you to retrieve alias objects from the GAMS Container based on their names.

Parameters:
is_validbool, optional

An optional boolean flag used to filter the list of aliases. If None (default), all aliases in the Container are returned. If True, only valid aliases are included in the list. If False, only invalid aliases are included in the list.

Returns:
List[ABCAlias]

A list of alias objects that match the specified names.

getParameters(is_valid: bool | None = None) List[ABCParameter]#

Retrieve parameter objects from the GAMS Container.

This method allows you to retrieve parameter objects from the GAMS Container based on their names.

Parameters:
is_validbool, optional

An optional boolean flag used to filter the list of parameters. If None (default), all parameters in the Container are returned. If True, only valid parameters are included in the list. If False, only invalid parameters are included in the list.

Returns:
List[ABCAlias]

A list of parameter objects that match the specified names.

getVariables(is_valid: bool | None = None, types: str | List[str] | None = None) List[ABCVariable]#

Retrieve variable objects from the GAMS Container.

This method allows you to retrieve variable objects from the GAMS Container based on their names.

Parameters:
is_validbool, optional

An optional boolean flag used to filter the list of variables. If None (default), all variables in the Container are returned. If True, only valid variables are included in the list. If False, only invalid variables are included in the list.

typesstr | List[str], optional

An optional string or list of strings specifying the types of variables to include in the list. If None (default), all variable types are included in the list. If a string or list of strings is provided, only variables of the specified types are included in the list.

Returns:
List[ABCVariable]

A list of variable objects that match the specified names.

describeSets(symbols: str | List[str] | None = None) DataFrame | None#

Generate a DataFrame describing sets within the GAMS Container.

This method creates a DataFrame that provides descriptive information about sets within the GAMS Container. You can specify the sets to describe using the ‘symbols’ parameter. If ‘symbols’ is None (default), all sets are described.

Parameters:
symbolsstr | List[str], optional

An optional parameter specifying which sets to describe.

Returns:
DataFrame | None

A Pandas DataFrame containing descriptive information about the specified sets. The DataFrame includes the following columns: - ‘name’: The name of the set. - ‘is_singleton’: Whether the set is a singleton set (True) or not (False). - ‘domain’: The domain of the set. - ‘domain_type’: The type of the set’s domain. - ‘dimension’: The dimension of the set. - ‘number_records’: The number of records (size) of the set. - ‘sparsity’: The sparsity of the set.

If ‘symbols’ includes alias sets, the DataFrame will also contain the following additional columns: - ‘is_alias’: Whether the set is an alias set (True) or not (False). - ‘alias_with’: The name of the set that the alias set is associated with (if it is an alias set).

The DataFrame is sorted by set name in ascending order.

Raises:
TypeError

If the ‘symbols’ argument is not of type str, list, or NoneType. If ‘symbols’ contains elements that are not of type str.

Notes

  • This method generates a descriptive summary of sets within the GAMS Container, including their properties and characteristics.

  • The ‘symbols’ parameter allows you to specify which sets to describe. If None (default), all sets are described.

  • The resulting DataFrame provides insights into each set’s attributes, such as dimensionality, size, and sparsity.

describeAliases(symbols: str | List[str] | None = None) DataFrame | None#

Generate a DataFrame describing alias symbols in the GAMS Container.

This method generates a DataFrame providing detailed information about alias symbols in the GAMS Container.

Parameters:
symbolsstr | List[str], optional

An optional parameter specifying the alias symbol names to describe. If None (default), Describe all alias symbols in the Container.

Returns:
DataFrame | None

A pandas DataFrame containing the description of alias symbols that match the specified symbol names. If no matching alias symbols are found, None is returned.

Raises:
ValueError
  • If the ‘symbols’ argument is not of type str, list, or NoneType.

  • If an alias symbol name specified in ‘symbols’ does not exist in the Container.

Notes

  • This method provides a tabular summary of alias symbols, including information such as alias relationships, dimension, sparsity, etc.

  • The ‘symbols’ parameter allows you to describe one or more alias symbols in the Container.

  • If ‘symbols’ is None (default), the method describes all alias symbols in the Container.

  • The method raises a ValueError if any alias symbol name specified in ‘symbols’ does not exist in the Container.

describeParameters(symbols: str | List[str] | None = None) DataFrame | None#

Generate a DataFrame describing parameter symbols in the GAMS Container.

This method generates a DataFrame providing detailed information about parameter symbols in the GAMS Container.

Parameters:
symbolsstr | List[str], optional

An optional parameter specifying the parameter symbol names to describe. If None (default), Describe all parameter symbols in the Container.

Returns:
DataFrame | None

A pandas DataFrame containing the description of parameter symbols that match the specified symbol names. If no matching parameter symbols are found, None is returned.

Raises:
ValueError
  • If the ‘symbols’ argument is not of type str, iterable, or NoneType.

  • If a parameter symbol name specified in ‘symbols’ does not exist in the Container.

Notes

  • This method provides a tabular summary of parameter symbols, including information such as domain, dimension, sparsity, etc.

  • The ‘symbols’ parameter allows you to describe one or more parameter symbols in the Container.

  • If ‘symbols’ is None (default), the method describes all parameter symbols in the Container.

  • The method raises a ValueError if any parameter symbol name specified in ‘symbols’ does not exist in the Container.

describeVariables(symbols: str | List[str] | None = None) DataFrame | None#

Generate a DataFrame describing variable symbols in the GAMS Container.

This method generates a DataFrame providing detailed information about variable symbols in the GAMS Container.

Parameters:
symbolsstr | List[str], optional

An optional parameter specifying the variable symbol names to describe. If None (default), Describe all variable symbols in the Container.

Returns:
DataFrame | None

A pandas DataFrame containing the description of variable symbols that match the specified symbol names. If no matching variable symbols are found, None is returned.

Raises:
ValueError
  • If the ‘symbols’ argument is not of type str, iterable, or NoneType.
  • If a variable symbol name specified in ‘symbols’ does not exist in the Container.

Notes

  • This method provides a tabular summary of variable symbols, including information such as type, domain, dimension, sparsity, etc.

  • The ‘symbols’ parameter allows you to describe one or more variable symbols in the Container.

  • If ‘symbols’ is None (default), the method describes all variable symbols in the Container.

  • The method raises a ValueError if any variable symbol name specified in ‘symbols’ does not exist in the Container.

describeEquations(symbols: str | List[str] | None = None) DataFrame | None#

Generate a DataFrame describing equation symbols in the GAMS Container.

This method generates a DataFrame providing detailed information about equation symbols in the GAMS Container.

Parameters:
symbolsstr | List[str], optional

An optional parameter specifying the equation symbol names to describe. If None (default), Describe all equation symbols in the Container.

Returns:
DataFrame | None

A pandas DataFrame containing the description of equation symbols that match the specified symbol names. If no matching equation symbols are found, None is returned.

Raises:
ValueError
  • If the ‘symbols’ argument is not of type str, iterable, or NoneType.
  • If an equation symbol name specified in ‘symbols’ does not exist in the Container.

Notes

  • This method provides a tabular summary of equation symbols, including information such as type, domain, dimension, sparsity, etc.

  • The ‘symbols’ parameter allows you to describe one or more equation symbols in the Container.

  • If ‘symbols’ is None (default), the method describes all equation symbols in the Container.

  • The method raises a ValueError if any equation symbol name specified in ‘symbols’ does not exist in the Container.

hasSymbols(symbols: List[str] | str) List[bool] | bool[source]#

Checks if specific symbol names exist in a Container

Parameters:
symbolsList[str] | str

Symbols to check from the Container

Returns:
List[bool] | bool

Flag to indicate whether a symbol exists or not

isValid(symbols: str | List[str] | None = None, verbose: bool = False, force: bool = False) bool#

Check the validity of symbols in the GAMS Container.

This method checks the validity of symbols in the GAMS Container to ensure that they are consistent and correctly defined. It can check the validity of specific symbols or all symbols in the Container.

Parameters:
symbolsstr | List[str], optional

A list of symbol names or a single symbol name to be checked for validity. If None, all symbols in the Container will be checked.

verbosebool, by default False

A boolean flag indicating whether to raise an exception if an invalid symbol is found. If True, an exception is raised; if False, the method returns False for invalid symbols.

forcebool, by default False

A boolean flag indicating whether to force a recheck of the symbols’ validity.

Returns:
bool

Returns True if specified symbols (or all symbols in the Container) are valid. If any symbol is invalid and verbose is False, it returns False. If verbose is True, an exception is raised for the first invalid symbol encountered.

removeSymbols(symbols: str | List[str] | None = None) None[source]#

Remove symbols from the Container. If symbols=None, it will remove all symbols.

Parameters:
symbolsList[str] | str, optional

Symbols to remove from the Container, also sets the symbols container to None. If symbols=None, will remove all symbols.

renameSymbol(old_name: str, new_name: str) None[source]#

Rename a symbol in the Container

Parameters:
old_namestr

Old name of the symbol

new_namestr

New name of the symbol

property summary: dict#

This property returns a summary of the container.

Returns:
dict

A summary including the container’s system directory and its number of symbols.

property system_directory#

!! processed by numpydoc !!