Model#

class gamspy.Model(container: Container | None = None, name: str | None = None, description: str = '', problem: Problem | str = Problem.MIP, equations: Sequence[Equation] | None = None, sense: Sense | str = Sense.FEASIBILITY, objective: Variable | Expression | Operation | None = None, matches: dict[Equation | Sequence[Equation], Variable | Sequence[Variable]] | None = None, limited_variables: Sequence[ImplicitVariable] | 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.

descriptionstr, optional

Description of the model.

equationsSequence[Equation]

Sequence 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 | 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

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

convert(path, file_format[, options])

Converts the model to one or more specified file formats.

freeze(modifiables[, options])

Instantiates a model instance.

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, dump_gams_state])

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>.tex

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", problem="LP", equations=[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
convert(path: str | Path, file_format: FileFormat | Sequence[FileFormat], options: ConvertOptions | None = None) None[source]#

Converts the model to one or more specified file formats.

Parameters:
pathstr | Path

Path to the directory where the converted model files will be saved.

file_formatFileFormat | Sequence[FileFormat]

File format(s) to convert the model to. Can be a single FileFormat or a list of FileFormats.

optionsConvertOptions, optional

Additional options to customize the conversion process.

Raises:
ValueError

If the specified file format is not supported.

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", problem="LP", equations=[e])
>>> my_model.convert("output_directory", gp.FileFormat.GAMS)
>>> my_model.convert("output_directory", [gp.FileFormat.GAMS, gp.FileFormat.AMPL])
freeze(modifiables: list[Parameter | ImplicitParameter], options: Options | None = None) None[source]#

Instantiates a model instance. After calling freeze, only modifiables can be modified.

Parameters:
modifiableslist[Parameter | ImplicitParameter]

Modifiable symbols.

optionsOptions | None, optional

GAMSPy options, by default None

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", problem="LP", equations=[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, freeze_options: FreezeOptions | 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

GAMSPy options.

solver_optionsdict, optional

Solver options.

model_instance_optionsModelInstanceOptions, optional

Options to solve a frozen model. This argument will be deprecated in GAMSPy 1.10.0. Please use freeze_options instead.

freeze_optionsFreezeOptions, optional

Options to solve a frozen model.

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", problem="LP", equations=[e], sense="max", objective=v)
>>> solved = my_model.solve()
toGams(path: str | Path, options: Options | None = None, *, dump_gams_state: bool = False) None[source]#

Generates GAMS model under path/<model_name>.gms.

Parameters:
pathstr | Path

Path to the directory which will contain the GAMS model.

optionsOptions | None, optional

GAMSPy options, by default None

dump_gams_statebool, optional

Whether to dump the state as a GAMS save file, by default False

Raises:
ValidationError

In case the given options is not of type gp.Options.

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

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

Parameters:
pathstr | Path

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#

An error occurred and no solution has been returned. No solution will be returned to GAMS because of errors in the solution process.

ErrorUnknown = 12#

After a solver error the model status is unknown.

Feasible = 7#

A feasible solution to a problem without discrete variables has been found.

InfeasibleGlobal = 4#

The problem has been proven to be infeasible. If this was not intended, something is probably misspecified in the logic or the data.

InfeasibleIntermed = 6#

The current solution is not feasible, but the solver stopped, either because of a limit (for example, iteration or resource) or because of some sort of difficulty. The solver status will give more information.

InfeasibleLocal = 5#

No feasible point could be found for the NLP problem from the given starting point. It does not necessarily mean that no feasible point exists.

InfeasibleNoSolution = 19#

The model is infeasible and no solution can be provided.

Integer = 8#

A feasible solution to a problem with discrete variables has been found.

IntegerInfeasible = 10#

It has been proven that there is no feasible solution to a problem with discrete variables.

LicenseError = 11#

The solver cannot find the appropriate license key needed to use a specific subsolver.

NoSolutionReturned = 14#

A solution is not expected for this solve. For example, the CONVERT solver only reformats the model but does not give a solution.

NonIntegerIntermed = 9#

An incomplete solution to a problem with discrete variables. A feasible solution has not yet been found.

OptimalGlobal = 1#

The solution is optimal, that is, it is feasible (within tolerances) and it has been proven that no other feasible solution with better objective value exists.

OptimalLocal = 2#

A local optimum for an NLP has been found. That is, a solution that is feasible (within tolerances) and it has been proven that there exists a neighborhood of this solution in which no other feasible solution with better objective value exists.

Solved = 16#

used for CNS models. The solution might or might not be unique. If the solver uses status SOLVED SINGULAR wherever possible then this status implies that the Jacobian is non-singular, i.e. that the solution is at least locally unique.

Type:

Indicates the model has been solved

SolvedSingular = 17#

Indicates the CNS model has been solved, but the Jacobian is singular at the solution. This can indicate that other solutions exist, either along a line (for linear models) or a curve (for nonlinear models) including the solution returned.

SolvedUnique = 15#

Indicates the solution returned is unique, i.e. no other solution exists. Used for CNS models. Examples where this status could be returned include non-singular linear models, triangular models with constant non-zero elements on the diagonal, and triangular models where the functions are monotone in the variable on the diagonal.

Unbounded = 3#

The solution is unbounded. This message is reliable if the problem is linear, but occasionally it appears for difficult nonlinear problems that are not truly unbounded, but that lack some strategically placed bounds to limit the variables to sensible values.

UnboundedNoSolution = 18#

The model is unbounded and no solution can be provided.

class gamspy.SolveStatus(value)[source]#

Bases: Enum

An enumeration for solve status types

CapabilityError = 6#

The solver does not have the capability required by the model. For example, some solvers do not support certain types of discrete variables or support a more limited set of functions than other solvers.

EvaluationInterrupt = 5#

Too many evaluations of nonlinear terms at undefined values. We recommend to use variable bounds to prevent forbidden operations, such as division by zero. The rows in which the errors occur are listed just before the solution.

InternalError = 11#

The solver encountered an internal fatal error.

IterationInterrupt = 2#

The solver was interrupted because it used too many iterations. The option iteration_limit may be used to increase the iteration limit if everything seems normal.

LicenseError = 7#

The solver cannot find the appropriate license key needed to use a specific subsolver.

NormalCompletion = 1#

The solver terminated in a normal way.

ResourceInterrupt = 3#

The solver was interrupted because it used too much time. The option time_limit may be used to increase the time limit if everything seems normal.

SetupError = 9#

The solver encountered a fatal failure during problem set-up time.

Skipped = 12#

The entire solve step has been skipped.

SolverError = 10#

The solver encountered a fatal error.

SystemError = 13#

This indicates a completely unknown or unexpected error condition.

TerminatedBySolver = 4#

The solver encountered some difficulty and was unable to continue.

UserInterrupt = 8#

The user has sent a signal to interrupt the solver.

class gamspy.FileFormat(value)[source]#

Bases: Enum

An enumeration for file format types

AMPL = 'ampl.mod'#

AMPL input format.

AMPLNL = 'ampl.nl'#

AMPL nl format.

CPLEXLP = 'cplex.lp'#

CPLEX LP format.

CPLEXMPS = 'cplex.mps'#

CPLEX MPS format.

FileList = 'files.txt'#

List of file formats generated.

FixedMPS = 'fixed.mps'#

Fixed format mps file.

GAMS = 'gams.gms'#

GAMS scalar model.

GAMSDict = 'dict.txt'#

GAMS dictionary format.

GAMSDictMap = 'dictmap.gdx'#

GAMS dictionary map format.

GAMSJacobian = 'jacobian.gms'#

Jacobian in GAMS.

GAMSPyJacobian = 'jacobian.py'#

Jacobian in GAMSPy.

GDXJacobian = 'jacobian.gdx'#

GDX file with model data incl. Jacobian and Hessian evaluated at current point.

JuMP = 'jump.jl'#

JuMP scalar model.

LINGO = 'lingo.lng'#

Lingo format.

OSiL = 'osil.xml'#

Optimization Services instance Language (OSiL) format.

Pyomo = 'pyomo.py'#

Pyomo concrete scalar model.