Model#

class gamspy.Model(container: Container, name: str | None = None, problem: Problem | str = Problem.MIP, equations: Iterable[Equation] = [], sense: Sense | str = Sense.FEASIBILITY, objective: Variable | Expression | None = None, matches: dict[Equation, Variable] | None = None, limited_variables: Iterable[Variable] | None = None, external_module: str | None = None)[source]#

Bases: object

Represents a list of equations to be solved.

Parameters:
containerContainer

Container of the model.

namestr, optional

Name of the model. Name is autogenerated by default.

equationsIterable[Equation]

Iterable of Equation objects.

problemProblem | str, optional

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

senseSense | str, optional

“MIN”, “MAX”, or “FEASIBILITY”. By default, Sense.FEASIBILITY

objectiveVariable | Expression, optional

Objective variable to minimize or maximize or objective itself.

matchesdict[Equation, Variable]

Equation - Variable matches for MCP models.

limited_variablesIterable, 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

Attributes:
algorithm_time

Solver dependent timing information.

external_module

Name of the external module in which the external equations are implemented.

marginals

Indicates whether there are marginals.

max_infeasibility

Maximum of infeasibilities

mean_infeasibility

Mean of infeasibilities

model_generation_time

Time GAMS took to generate the model in wall-clock seconds.

num_bound_projections

Number of bound projections during model generation.

num_dependencies

Number of dependencies in a CNS model.

num_discrete_variables

Number of discrete variables.

num_domain_violations

Number of domain violations.

num_equations

Number of equations.

num_infeasibilities

Number of infeasibilities.

num_iterations

Number of iterations used.

num_mcp_redefinitions

Number of MCP redefinitions.

num_nodes_used

Number of nodes used by the MIP solver.

num_nonlinear_insts

Number of nonlinear instructions.

num_nonlinear_zeros

Number of nonlinear nonzeros.

num_nonoptimalities

Number of nonoptimalities.

num_nonzeros

Number of nonzero entries in the model coefficient matrix.

num_variables

Number of variables.

objective_estimation

Estimate of the best possible solution for a mixed-integer model

objective_value

Objective function value

solve_model_time

Time the solver used to solve the model in seconds

solve_number

Number of the last solve.

solve_status

Indicates the solver termination condition.

solver_version

Solver version.

status

Model status after solve.

sum_infeasibilities

Sum of infeasibilities.

total_solve_time

Elapsed time it took to execute a solve statement in total.

total_solver_time

Elapsed time taken by the solver only.

used_model_type

Integer number that indicates the used model type.

Methods

computeInfeasibilities()

Computes infeasabilities for all equations of the model

freeze(modifiables[, options])

Freezes all symbols except modifiable symbols.

getDeclaration()

Declaration of the Model in GAMS

getEquationListing([infeasibility_threshold])

Returns the generated equations.

getVariableListing()

Returns the variable listing.

interrupt()

Sends interrupt signal to the running job.

solve([solver, options, solver_options, ...])

Solves the model with given options.

toGams(path[, options])

Generates GAMS model under path/<model_name>.gms

toLatex(path[, generate_pdf])

Generates a latex file that contains the model definition under path/<model_name>.gms

unfreeze()

Unfreezes the model

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> v = gp.Variable(m, "v")
>>> e = gp.Equation(m, "e", definition= v == 5)
>>> my_model = gp.Model(m, "my_model", "LP", [e])
computeInfeasibilities() dict[str, pd.DataFrame][source]#

Computes infeasabilities for all equations of the model

Returns:
dict[str, pd.DataFrame]

Dictionary of infeasibilities where equation names are keys and infeasibilities are values

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["i1", "i2"])
>>> j = gp.Set(m, name="j", records=["j1", "j2", "j3"])
>>> a = gp.Parameter(m, name="a", domain=i, records=[("i1", 350), ("i2", 600)])
>>> b = gp.Parameter(m, name="b", domain=j, records=[("j1", 400), ("j2", 450), ("j3", 420)])
>>> x = gp.Variable(m, name="x", domain=[i,j], type="Positive")
>>> s = gp.Equation(m, name="s", domain=i)
>>> d = gp.Equation(m, name="d", domain=j)
>>> s[i] = gp.Sum(j, x[i, j]) <= a[i]
>>> d[j] = gp.Sum(i, x[i, j]) >= b[j]
>>> my_model = gp.Model(m, name="my_model", equations=m.getEquations(), problem="LP", sense="min", objective=gp.Sum((i, j), x[i, j]))
>>> summary = my_model.solve()
>>> infeasibilities = my_model.computeInfeasibilities()
>>> infeasibilities["s"].infeasibility.item()
320.0
freeze(modifiables: list[Parameter | ImplicitParameter], options: Options | None = None) None[source]#

Freezes all symbols except modifiable symbols.

Parameters:
modifiablesList[Parameter | ImplicitParameter]
freeze_optionsdict, optional

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> a = gp.Parameter(m, name="a", records=10)
>>> x = gp.Variable(m, name="x")
>>> e = gp.Equation(m, name="e", definition= x <= a)
>>> my_model = gp.Model(m, name="my_model", equations=m.getEquations(), problem="LP", sense="max", objective=x)
>>> solved = my_model.solve()
>>> float(x.toValue())
10.0
>>> my_model.freeze(modifiables=[a])
>>> a.setRecords(35)
>>> solved = my_model.solve()
>>> float(x.toValue())
35.0
getDeclaration() str[source]#

Declaration of the Model in GAMS

Returns:
str

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> v = gp.Variable(m, "v")
>>> e = gp.Equation(m, "e", definition= v == 5)
>>> my_model = gp.Model(m, "my_model", "LP", [e])
>>> my_model.getDeclaration()
'Model my_model / e,my_model_objective /;'
getEquationListing(infeasibility_threshold: float | None = None) str[source]#

Returns the generated equations.

Parameters:
infeasibility_threshold: float, optional

Filters out equations with infeasibilities that are above this value.

Returns:
str
getVariableListing() str[source]#

Returns the variable listing.

Returns:
str
interrupt() None[source]#

Sends interrupt signal to the running job.

solve(solver: str | None = None, options: Options | None = None, solver_options: dict | None = None, model_instance_options: ModelInstanceOptions | None = None, output: io.TextIOWrapper | None = None, backend: Literal['local', 'engine', 'neos'] = 'local', client: EngineClient | NeosClient | None = None, load_symbols: list[Symbol] | None = None) pd.DataFrame | None[source]#

Solves the model with given options.

Parameters:
solverstr, optional

Solver name

optionsOptions, optional

GAMS options

solver_optionsdict, optional

Solver options

model_instance_optionsModelInstanceOptions, optional

Model instance options

outputTextIOWrapper, optional

Output redirection target

backendstr, optional

Backend to run on

clientEngineClient, NeosClient, optional

EngineClient to communicate with GAMS Engine or NEOS Client to communicate with NEOS Server

load_symbolslist[Symbol], optional

Specifies the symbols that need to be loaded. If not given, all symbols are loaded after solve.

Returns:
DataFrame, optional

Summary of the solve

Raises:
ValidationError

In case engine_config is not provided for engine backend or neos_client is not provided for neos backend.

ValueError

In case problem is not in possible problem types

ValueError

In case sense is different than “MIN” or “MAX”

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> v = gp.Variable(m, "v")
>>> e = gp.Equation(m, "e", definition= v == 5)
>>> my_model = gp.Model(m, "my_model", "LP", [e], "max", v)
>>> solved = my_model.solve()
toGams(path: str, options: Options | None = None) None[source]#

Generates GAMS model under path/<model_name>.gms

Parameters:
pathstr

Path to the directory which will contain the GAMS model.

toLatex(path: str, generate_pdf: bool = False) None[source]#

Generates a latex file that contains the model definition under path/<model_name>.gms

Parameters:
pathstr

Path to the directory which will contain the .tex file.

unfreeze() None[source]#

Unfreezes the model

property algorithm_time: float | None#

Solver dependent timing information. This attribute was intended to allow solvers to return the elapsed time used by the solve algorithm without including any model generation, communication, or setup time. However, solvers are free to adapt this convention and return time-related information (but not necessarily elapsed time) for executing the solve algorithm. Please inspect your solver manual for the actual meaning of the value returned in this attribute.

Returns:
float | None
property external_module: str | None#

Name of the external module in which the external equations are implemented. By default, this parameter is set to None. When provided, it triggers the opening of the specified file using a File statement and incorporates the file into the model by adding it as an external module.

This feature requires a solid understanding of programming, compilation, and linking processes. For more information, please refer to the https://gamspy.readthedocs.io/en/latest/user/advanced/external_equations.html .

Returns:
str | None
property marginals: float | None#

Indicates whether there are marginals.

Returns:
float | None
property max_infeasibility: float | None#

Maximum of infeasibilities

Returns:
float | None
property mean_infeasibility: float | None#

Mean of infeasibilities

Returns:
float | None
property model_generation_time: float | None#

Time GAMS took to generate the model in wall-clock seconds.

Returns:
float | None
property num_bound_projections: float | None#

Number of bound projections during model generation.

Returns:
float | None
property num_dependencies: float | None#

Number of dependencies in a CNS model.

Returns:
float | None
property num_discrete_variables: float | None#

Number of discrete variables.

Returns:
float | None
property num_domain_violations: float | None#

Number of domain violations.

Returns:
float | None
property num_equations: float | None#

Number of equations.

Returns:
float | None
property num_infeasibilities: float | None#

Number of infeasibilities.

Returns:
float | None
property num_iterations: float | None#

Number of iterations used.

Returns:
float | None
property num_mcp_redefinitions: float | None#

Number of MCP redefinitions.

Returns:
float | None
property num_nodes_used: float | None#

Number of nodes used by the MIP solver.

Returns:
float | None
property num_nonlinear_insts: float | None#

Number of nonlinear instructions.

Returns:
float | None
property num_nonlinear_zeros: float | None#

Number of nonlinear nonzeros.

Returns:
float | None
property num_nonoptimalities: float | None#

Number of nonoptimalities.

Returns:
float | None
property num_nonzeros: float | None#

Number of nonzero entries in the model coefficient matrix.

Returns:
float | None
property num_variables: float | None#

Number of variables.

Returns:
float | None
property objective_estimation: float | None#

Estimate of the best possible solution for a mixed-integer model

Returns:
float | None
property objective_value: float | None#

Objective function value

Returns:
float | None
property solve_model_time: float | None#

Time the solver used to solve the model in seconds

Returns:
float | None
property solve_number: float | None#

Number of the last solve.

Returns:
float | None
property solve_status: SolveStatus | None#

Indicates the solver termination condition.

Returns:
SolveStatus | None
property solver_version: float | None#

Solver version.

Returns:
float | None
property status: ModelStatus | None#

Model status after solve.

Returns:
ModelStatus | None
property sum_infeasibilities: float | None#

Sum of infeasibilities.

Returns:
float | None
property total_solve_time: float | None#

Elapsed time it took to execute a solve statement in total. This model attribute returns the elapsed time it took to execute a solve statement in total. This time includes the model generation time, the time to read and write files, the time to create the solution report and the time taken by the actual solve. The time is expressed in seconds of wall-clock time.

Returns:
float | None
property total_solver_time: float | None#

Elapsed time taken by the solver only. This model attribute returns the elapsed time taken by the solver only. This does not include the GAMS model generation time and the time taken to report and load the solution back into the GAMS database. The time is expressed in seconds of wall-clock time.

Returns:
float | None
property used_model_type: float | None#

Integer number that indicates the used model type.

Returns:
float | None
class gamspy.ModelStatus(value)[source]#

Bases: Enum

An enumeration for model status types

ErrorNoSolution = 13#
ErrorUnknown = 12#
Feasible = 7#
InfeasibleGlobal = 4#
InfeasibleIntermed = 6#
InfeasibleLocal = 5#
InfeasibleNoSolution = 19#
Integer = 8#
IntegerInfeasible = 10#
LicenseError = 11#
NoSolutionReturned = 14#
NonIntegerIntermed = 9#
OptimalGlobal = 1#
OptimalLocal = 2#
Solved = 16#
SolvedSingular = 17#
SolvedUnique = 15#
Unbounded = 3#
UnboundedNoSolution = 18#
class gamspy.SolveStatus(value)[source]#

Bases: Enum

An enumeration for solve status types

CapabilityError = 6#
EvaluationInterrupt = 5#
InternalError = 11#
IterationInterrupt = 2#
LicenseError = 7#
NormalCompletion = 1#
ResourceInterrupt = 3#
SetupError = 9#
Skipped = 12#
SolverError = 10#
SystemError = 13#
TerminatedBySolver = 4#
UserInterrupt = 8#