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:
ContainerCentral 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, os.PathLike, 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, 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
in_miroIndicates whether the container is executed inside a GAMS MIRO context.
- modified
summaryThis property returns a summary of the container.
system_directoryThis property returns the path to the GAMS system directory.
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
capitalizeUELs([symbols])This function capitalizes the UELs of specific symbols.
casefoldUELs([symbols])This function performs case folding on the UELs of specific symbols, converting them to lowercase.
close()Close the connection to the GAMS execution engine and release resources.
copy(working_directory)Creates a copy of the Container.
countDomainViolations([symbols])Count domain violations for one or more symbols in the Container.
countDuplicateRecords([symbols])Count duplicate records for one or more symbols in the Container.
describeAliases([symbols])Generate a DataFrame describing alias symbols in the Container.
describeEquations([symbols])Generate a DataFrame describing equation symbols in the Container.
describeParameters([symbols])Generate a DataFrame describing parameter symbols in the Container.
describeSets([symbols])Generate a DataFrame describing sets within the Container.
describeVariables([symbols])Generate a DataFrame describing variable symbols in the Container.
dropDomainViolations([symbols])Drop domain violations for one or more symbols in the Container.
dropDuplicateRecords([symbols, keep])Remove duplicate records from the specified symbols in the Container.
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.
getAliases([is_valid])Retrieve alias objects from the Container.
getDomainViolations([symbols])Get domain violations for one or more symbols in the Container.
Returns all equation symbols in the Container.
getParameters([is_valid])Retrieve parameter objects from the Container.
getSets([is_valid])Retrieve set objects from the Container.
getSymbols([symbols])Retrieve symbol objects from the Container.
getUELs([symbols, ignore_unused, unique_only])Retrieve the (UELs) associated with one or more symbols in the Container.
getVariables([is_valid, types])Retrieve variable objects from the Container.
hasDomainViolations([symbols])Check if domain violations exist for one or more symbols in the Container.
hasDuplicateRecords([symbols])Check if the Container has any duplicate records for one or more symbols.
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 Container.
listAliases([is_valid])Get a list of alias names in the Container.
listEquations([is_valid, types])Get a list of equation names in the Container.
listParameters([is_valid])Get a list of parameter names in the Container.
listSets([is_valid])Get a list of set names in the Container.
listSymbols([is_valid])Get a list of symbol names in the Container.
listVariables([is_valid, types])Get a list of variable names in the Container.
ljustUELs(length[, fill_character, symbols])This function left-justifies the UELs of specific symbols within the container, padding them with a specified fill character to reach the desired length.
loadRecordsFromGdx(load_from[, symbol_names])Loads data of the given symbols from a GDX file.
lowerUELs([symbols])This function converts the UELs of specific symbols to lowercase.
lstripUELs([symbols])This function removes leading whitespaces from the UELs of specific symbols.
read(load_from[, symbol_names, ...])Read symbols and records from a GDX file or another container.
removeSymbols([symbols])Remove symbols from the Container.
removeUELs([uels, symbols])Remove specific unique element labels (UELs) from one or more symbols in the Container.
renameSymbol(old_name, new_name)Rename a symbol in the Container
renameUELs(uels[, symbols, allow_merge])Rename unique element labels (UELs) associated with symbols in the Container.
reorderSymbols()Reorder symbols in order to avoid domain violations
rjustUELs(length[, fill_character, symbols])This function right-justifies the UELs of specific symbols within the container, padding them with a specified fill character to reach the desired length.
rstripUELs([symbols])This function removes trailing whitespaces from the UELs of specific symbols.
serialize(path)Serializes the Container into a zip file.
setRecords(records, *[, uels_on_axes])Set records for multiple symbols in a single batch operation.
stripUELs([symbols])This function removes leading and trailing whitespaces from the UELs of specific symbols.
titleUELs([symbols])This function capitalizes the UELs of specific symbols in title case.
upperUELs([symbols])This function converts the UELs of specific symbols to uppercase.
write(write_to[, symbol_names, compress, ...])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: Sequence[Set | Alias] | Set | Alias | None = None, definition: Variable | Operation | Expression | None = None, records: Any | 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.
- recordsAny, 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: Sequence[Set | Alias | str] | Set | Alias | Dim | str | None = None, records: Any | 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: Sequence[Set | Alias | str] | Set | Alias | str | None = None, is_singleton: bool = False, records: Any | 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: Sequence[Set | Alias | str] | Set | Alias | Dim | str | None = None, records: Any | 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.
- recordsAny, 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) 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: Iterable[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_namesIterable[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, load_records: bool = True, mode: str | None = None, encoding: str | None = None) 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.
- load_recordsbool, optional
Whether to load symbol records (default: True).
- 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"])
- 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.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.
- 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: str, symbol_names: list[str] | None = None, compress: bool = False, mode: str | None = None, eps_to_zero: bool = True) None[source]#
Write symbols and records to a GDX file.
- Parameters:
- write_tostr
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 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 '...'