Container#
- class gamspy.Container(load_from: str | Path | Container | gt.Container | None = None, system_directory: str | Path | None = None, working_directory: str | Path | None = None, debugging_level: Literal['keep', 'keep_on_error', 'delete'] = 'keep_on_error', options: Options | None = None, output: TextIO | None = None)[source]#
Bases:
objectCentral workspace for building, modifying, executing, and exchanging data with GAMS models.
https://gamspy.readthedocs.io/en/latest/reference/gamspy._container.html
A
Containerowns 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, Path, Container, gt.Container, optional
Source to initialize the container from:
.gdxfile: loads symbols and records from a GDX file..g00file: restarts from a GAMS save file.Container: Copies symbols from the given container into the new container.
- system_directorystr, Path, optional
Path to the directory that holds the GAMS installation, by default None
- working_directorystr, Path, 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:
dataThe dictionary that contains all symbols in the Container.
in_miroIndicates whether the container is executed inside a GAMS MIRO context.
working_directoryAbsolute 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.
Returns the name of the latest GAMS job that was executed
Path to the input GDX file
Path to the output GDX file
generateGamsString([path, show_raw])Return the generated GAMS code executed by this container.
getAlias(name)Retrieves the Alias with the given name from the Container.
Retrieves all Alias and UniverseAlias symbols present in the Container.
getEquation(name)Retrieves the Equation with the given name from the Container.
Returns all equation symbols in the Container.
getParameter(name)Retrieves the Parameter with the given name from the Container.
Retrieves all Parameter symbols present in the Container.
getSet(name)Retrieves the Set with the given name from the Container.
getSets()Retrieves all Set symbols present in the Container.
getSymbol(-> SymbolType)Retrieves the symbol with the given name from the Container.
getSymbols([symbols])Retrieves specific symbols from the Container by their names.
getUniverseAlias(name)Retrieves the UniverseAlias with the given name from the Container.
getVariable(name)Retrieves the Variable with the given name from the Container.
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.
Save the state of the GAMS execution engine and stop it.
importExtrinsicLibrary(lib_path, functions)Imports an extrinsic library to the GAMS environment.
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.
Lists the names of all Parameter symbols in the Container.
listSets()Lists the names of all Set symbols in the Container.
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, *, drop_domain_violations: bool = False) 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.
- domainDomainType, optional
Domain of the equation. Use
UNIVERSEfor the universe set.- 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
- drop_domain_violationsbool, optional
If True, records with labels outside the domain are dropped instead of raising
DomainViolationError. Default is False.
- 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, *, drop_domain_violations: 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.
- domainDomainType, optional
Domain over which the parameter is defined. Use
UNIVERSEfor the universe set.- 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
- drop_domain_violationsbool, optional
If True, records with labels outside the domain are dropped instead of raising
DomainViolationError. Default is False.
- 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, *, drop_domain_violations: 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.
- domainDomainType, optional
Domain over which the set is defined. Use
UNIVERSEfor the universe set.- 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
- drop_domain_violationsbool, optional
If True, records with labels outside the domain are dropped instead of raising
DomainViolationError. Default is False.
- 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, *, drop_domain_violations: 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.
- domainDomainType, optional
Domain of the variable. Use
UNIVERSEfor the universe set.- 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
- drop_domain_violationsbool, optional
If True, records with labels outside the domain are dropped instead of raising
DomainViolationError. Default is False.
- 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
- describeAliases(symbols: str | list[str] | None = None) DataFrame | None[source]#
Provides a structural summary of the specified Alias symbols as a pandas DataFrame.
- Parameters:
- symbolsstr | list[str] | None, optional
Name or list of names of the Alias symbols to describe. If None, describes all Aliases in the Container.
- Returns:
- DataFrame | None
A pandas DataFrame describing the Aliases (e.g., alias_with, domain, number of records), or None if no matching Aliases are found.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> i = m.addSet("i", records=["a", "b"]) >>> a = m.addAlias("a", i) >>> df = m.describeAliases()
- describeEquations(symbols: str | list[str] | None = None) DataFrame | None[source]#
Provides a statistical and structural summary of the specified Equation symbols as a pandas DataFrame.
- Parameters:
- symbolsstr | list[str] | None, optional
Name or list of names of the Equation symbols to describe. If None, describes all Equations in the Container.
- Returns:
- DataFrame | None
A pandas DataFrame describing the Equations (e.g., type, min/max level, sparsity, dimension), or None if no matching Equations are found.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> e = m.addEquation("e") >>> df = m.describeEquations()
- describeParameters(symbols: str | list[str] | None = None) DataFrame | None[source]#
Provides a statistical summary of the specified Parameter symbols as a pandas DataFrame.
- Parameters:
- symbolsstr | list[str] | None, optional
Name or list of names of the Parameter symbols to describe. If None, describes all Parameters in the Container.
- Returns:
- DataFrame | None
A pandas DataFrame describing the Parameters (e.g., domain, min/mean/max values, sparsity), or None if no matching Parameters are found.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> p = m.addParameter("p", records=5) >>> df = m.describeParameters()
- describeSets(symbols: str | list[str] | None = None) DataFrame | None[source]#
Provides a structural summary of the specified Set symbols as a pandas DataFrame.
- Parameters:
- symbolsstr | list[str] | None, optional
Name or list of names of the Set symbols to describe. If None, describes all Sets in the Container.
- Returns:
- DataFrame | None
A pandas DataFrame describing the Sets (e.g., dimension, domain, sparsity, number of records), or None if no matching Sets are found.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> i = m.addSet("i", records=["a", "b"]) >>> df = m.describeSets()
- describeVariables(symbols: str | list[str] | None = None) DataFrame | None[source]#
Provides a statistical and structural summary of the specified Variable symbols as a pandas DataFrame.
- Parameters:
- symbolsstr | list[str] | None, optional
Name or list of names of the Variable symbols to describe. If None, describes all Variables in the Container.
- Returns:
- DataFrame | None
A pandas DataFrame describing the Variables (e.g., type, min/max level, sparsity, dimension), or None if no matching Variables are found.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> v = m.addVariable("v") >>> df = m.describeVariables()
- gamsJobName() str[source]#
Returns the name of the latest GAMS job that was executed
- Returns:
- str
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()
- getAlias(name: str) Alias[source]#
Retrieves the Alias with the given name from the Container.
- Parameters:
- namestr
Name of the alias.
- Returns:
- Alias
- Raises:
- KeyError
If there is no symbol with the given name in the Container.
- ValidationError
If the symbol with the given name is not an Alias.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> i = gp.Set(m, "i", records=["seattle", "san-diego"]) >>> _ = gp.Alias(m, "ip", alias_with=i) >>> ip = m.getAlias("ip") >>> ip.toList() ['seattle', 'san-diego']
- getAliases() list[Alias | UniverseAlias][source]#
Retrieves all Alias and UniverseAlias symbols present in the Container.
- Returns:
- list[Alias | UniverseAlias]
A list containing all Alias and UniverseAlias objects in the Container.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> i = m.addSet("i") >>> a = m.addAlias("a", i) >>> aliases = m.getAliases()
- getEquation(name: str) Equation[source]#
Retrieves the Equation with the given name from the Container.
- Parameters:
- namestr
Name of the equation.
- Returns:
- Equation
- Raises:
- KeyError
If there is no symbol with the given name in the Container.
- ValidationError
If the symbol with the given name is not an Equation.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> _ = gp.Equation(m, "cost") >>> cost = m.getEquation("cost") >>> cost.name 'cost'
- 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()
- getParameter(name: str) Parameter[source]#
Retrieves the Parameter with the given name from the Container.
- Parameters:
- namestr
Name of the parameter.
- Returns:
- Parameter
- Raises:
- KeyError
If there is no symbol with the given name in the Container.
- ValidationError
If the symbol with the given name is not a Parameter.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> _ = gp.Parameter(m, "f", records=90) >>> f = m.getParameter("f") >>> float(f.toValue()) 90.0
- getParameters() list[Parameter][source]#
Retrieves all Parameter symbols present in the Container.
- Returns:
- list[Parameter]
A list containing all Parameter objects in the Container.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> p = m.addParameter("p") >>> parameters = m.getParameters()
- getSet(name: str) Set[source]#
Retrieves the Set with the given name from the Container.
- Parameters:
- namestr
Name of the set.
- Returns:
- Set
- Raises:
- KeyError
If there is no symbol with the given name in the Container.
- ValidationError
If the symbol with the given name is not a Set.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> _ = gp.Set(m, "i", records=["seattle", "san-diego"]) >>> i = m.getSet("i") >>> i.toList() ['seattle', 'san-diego']
- getSets() list[Set][source]#
Retrieves all Set symbols present in the Container.
- Returns:
- list[Set]
A list containing all Set objects in the Container.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> i = m.addSet("i") >>> sets = m.getSets()
- getSymbol(name: str) SymbolType[source]#
- getSymbol(name: str, type: type[_SymbolT]) _SymbolT
Retrieves the symbol with the given name from the Container.
Giving the expected symbol type narrows down the return type, which allows editors and type checkers to know which attributes are available on the returned symbol. Without it, the return type is the union of all symbol types, exactly as in
container[name].- Parameters:
- namestr
Name of the symbol.
- typetype[Set] | type[Alias] | type[UniverseAlias] | type[Parameter] | type[Variable] | type[Equation] | None, optional
Expected type of the symbol. If given, the symbol is verified to be of that type and the return type is narrowed accordingly.
- Returns:
- Set | Alias | UniverseAlias | Parameter | Variable | Equation
The requested symbol. Its static type is type if one was given.
- Raises:
- KeyError
If there is no symbol with the given name in the Container.
- ValidationError
If the symbol with the given name is not of the expected type.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> _ = gp.Variable(m, "x", records={"level": 5}) >>> x = m.getSymbol("x", gp.Variable) >>> float(x.toValue()) 5.0
- getSymbols(symbols: str | Iterable[str] | None = None) list[SymbolType][source]#
Retrieves specific symbols from the Container by their names.
- Parameters:
- symbolsstr | Iterable[str] | None, optional
Name or iterable of names of the symbols to retrieve. If None, retrieves all symbols in the Container.
- Returns:
- list[SymbolType]
A list containing the requested symbol objects.
- Raises:
- TypeError
If the ‘symbols’ argument is not a str, Iterable, or None.
- KeyError
If a specified symbol name does not exist in the Container.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> i = m.addSet("i") >>> p = m.addParameter("p") >>> syms = m.getSymbols(["i", "p"])
- getUniverseAlias(name: str) UniverseAlias[source]#
Retrieves the UniverseAlias with the given name from the Container.
- Parameters:
- namestr
Name of the universe alias.
- Returns:
- UniverseAlias
- Raises:
- KeyError
If there is no symbol with the given name in the Container.
- ValidationError
If the symbol with the given name is not a UniverseAlias.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> _ = gp.UniverseAlias(m, "h") >>> h = m.getUniverseAlias("h") >>> h.name 'h'
- getVariable(name: str) Variable[source]#
Retrieves the Variable with the given name from the Container.
- Parameters:
- namestr
Name of the variable.
- Returns:
- Variable
- Raises:
- KeyError
If there is no symbol with the given name in the Container.
- ValidationError
If the symbol with the given name is not a Variable.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> _ = gp.Variable(m, "x", records={"level": 5}) >>> x = m.getVariable("x") >>> float(x.toValue()) 5.0
- getVariables(types: str | list[str] | None = None) list[Variable][source]#
Retrieves all Variable symbols in the Container, optionally filtering by variable type.
- Parameters:
- typesstr | list[str] | None, optional
The variable type(s) to filter by (e.g., “free”, “positive”, “binary”). If None, retrieves all variables.
- Returns:
- list[Variable]
A list containing the filtered Variable objects.
- Raises:
- TypeError
If the ‘types’ argument is not of type str, list, or None.
- ValueError
If an unrecognized variable type is provided.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> v = m.addVariable("v", type="free") >>> variables = m.getVariables()
- hasSymbols(symbols: list[str] | str) list[bool] | bool[source]#
Checks if the specified symbol or symbols exist in the Container.
- Parameters:
- symbolsstr | list[str]
Name of the symbol or a list of symbol names to check for existence.
- Returns:
- bool | list[bool]
A boolean value if a single string is provided, or a list of boolean values corresponding to the list of strings provided, indicating whether each symbol is present in the Container.
- Raises:
- TypeError
If the ‘symbols’ argument is not of type str or list.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> i = m.addSet("i") >>> m.hasSymbols("i") True >>> m.hasSymbols(["i", "j"]) [True, False]
- hibernate() None[source]#
Save the state of the GAMS execution engine and stop it. The engine is restarted from the saved state by the next statement that needs it, so the container stays usable.
- Raises:
- ValidationError
If a loop context manager (gp.For, gp.While, gp.Loop) is active.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> i = gp.Set(m, "i", records=range(3)) >>> p = gp.Parameter(m, "p", domain=i, records=[(str(n), 1) for n in range(3)]) >>> m.hibernate() # The execution engine is stopped, the state is saved. >>> p[i] = p[i] + 1 # The engine is restarted from the saved state. >>> p.toList() [('0', 2.0), ('1', 2.0), ('2', 2.0)]
- 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)
- listAliases() list[str][source]#
Lists the names of all Alias and UniverseAlias symbols in the Container.
- Returns:
- list[str]
A list containing the names of all aliases.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> i = m.addSet("i") >>> a = m.addAlias("a", i) >>> m.listAliases() ['a']
- listEquations(types: str | list[str] | None = None) list[str][source]#
Lists the names of all equations in the Container, optionally filtering by equation type.
- Parameters:
- typesstr | list[str] | None, optional
The equation type(s) to filter by (e.g., “regular”). If None, all equations are listed.
- Returns:
- list[str]
A list containing the names of the filtered equations.
- Raises:
- TypeError
If the ‘types’ argument is not of type str, list, or None.
- ValueError
If an unrecognized equation type is provided.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> e = m.addEquation("e", type="regular") >>> m.listEquations() ['e']
- listParameters() list[str][source]#
Lists the names of all Parameter symbols in the Container.
- Returns:
- list[str]
A list containing the names of all parameters.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> p = m.addParameter("p") >>> m.listParameters() ['p']
- listSets() list[str][source]#
Lists the names of all Set symbols in the Container.
- Returns:
- list[str]
A list containing the names of all sets.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> i = m.addSet("i") >>> m.listSets() ['i']
- listSymbols() list[str][source]#
Lists the names of all symbols present in the Container.
- Returns:
- list[str]
A list containing the names of all symbols.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> i = m.addSet("i") >>> v = m.addVariable("v") >>> m.listSymbols() ['i', 'v']
- listVariables(types: str | list[str] | None = None) list[str][source]#
Lists the names of all variables in the Container, optionally filtering by variable type.
- Parameters:
- typesstr | list[str] | None, optional
The variable type(s) to filter by (e.g., “free”, “positive”, “binary”). If None, all variables are listed.
- Returns:
- list[str]
A list containing the names of the filtered variables.
- Raises:
- TypeError
If the ‘types’ argument is not of type str, list, or None.
- ValueError
If an unrecognized variable type is provided.
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> v1 = m.addVariable("v1", type="free") >>> v2 = m.addVariable("v2", type="binary") >>> m.listVariables(types="binary") ['v2']
- 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 | Path | Container | Container, symbol_names: list[str] | dict[str, 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 | Path | Container | gt.Container
Source to read from.
- symbol_nameslist[str], dict[str, str], optional
Names of symbols to read. If omitted, all symbols are read. If given as a dict, keys are the symbol names in the source, and values are the names of the symbols to create in this container (i.e. the symbols are renamed on read).
- modestr, optional
GDX read mode (“category”, or “string”, default: “category”).
- encodingstr, optional
Text encoding for symbol metadata.
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"])
Reading and renaming symbols
>>> m2 = gp.Container() >>> m2.read("example.gdx", symbol_names={"i": "j"}) >>> "j" in m2.data True
- 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, drop_domain_violations: bool = False) None[source]#
Set records for multiple symbols in a single batch operation.
This is functionally equivalent to calling
symbol.setRecordsfor 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
recordsorder.- drop_domain_violationsbool, optional
If True, records with labels outside the domain are dropped instead of raising
DomainViolationError. Default is False.
- Raises:
- ValidationError
If
uels_on_axeslength does not matchrecordslength.
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: CasePreservingDict[SymbolType]#
The dictionary that contains all symbols in the Container. Keys are symbol names and values are the symbols themselves. Lookups are case insensitive.
- Returns:
- CasePreservingDict[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,.gdxand temporary scratch files.- Returns:
- str
Examples
>>> import gamspy as gp >>> m = gp.Container() >>> m.working_directory '...'