Variable#

class gamspy.Variable(container: Container | None = None, 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)[source]#

Bases: Operable, VarEquSymbol

Represents a Variable symbol in GAMS.

Variables are the decision entities in a mathematical model. They can be free, positive, binary, integer, etc. See https://gamspy.readthedocs.io/en/latest/user/basics/variable.html

Parameters:
containerContainer

The Container object that this variable belongs to.

namestr, optional

Name of the variable. If not provided, a unique name is generated automatically.

typestr, optional

Type of the variable. Options: “free”, “positive”, “negative”, “binary”, “integer”, “sos1”, “sos2”, “semicont”, “semiint”. Default is “free”.

domainDomainType, optional

The domain of the variable. Can be a list of Sets/Aliases, a single Set/Alias, or strings representing set names. Use “*” for the universe set. Default is [] (scalar).

recordsSequence | pd.DataFrame | pd.Series | np.ndarray | int | float | dict, optional

Initial records (level/marginal/bounds) to populate the variable.

domain_forwardingbool | list[bool], optional

If True, adding records to this variable will implicitly add new elements to the domain sets (if they are dynamic). Default is False.

descriptionstr, optional

A human-readable description of the variable.

is_miro_outputbool, optional

If True, flags this variable as an output symbol for GAMS MIRO. Default is False.

Attributes:
container

Container of the symbol

description

Description of the symbol

dimension

The dimension of symbol

domain

List of domains given either as string (* for universe set) or as reference to the Set/Alias object

domain_labels

The column headings for the records DataFrame

domain_names

String version of domain names

domain_type

State of the domain links

fx

Fixed value of the variable.

is_scalar

Returns True if the len(self.domain) = 0

l

The Level of the variable (its current value).

lo

The Lower Bound of the variable.

m

The Marginal (dual value) of the variable.

number_records

Number of records

prior

Branching Priority.

records

Returns the records (data) of the Variable as a DataFrame.

scale

The Scale factor of the variable.

shape
stage

Branching Stage.

summary
synchronize

Synchronization state of the symbol.

type
up

The Upper Bound of the variable.

Methods

computeInfeasibilities()

Computes infeasibilities of the variable.

dropDefaults()

Drops records from the symbol that are equal to their default values.

dropEps()

Drops records from the symbol that contain EPS (Epsilon) values.

dropMissing()

Drops records from the symbol that contain missing (NaN) values.

dropNA()

Drops records from the symbol that contain NA (Not Available) values.

dropUndef()

Drops records from the symbol that contain UNDEF (Undefined) values.

equals(other[, columns, check_meta_data, ...])

Compares this symbol with another symbol to evaluate structural and numerical equality across specified attributes.

gamsRepr()

Returns the string representation of this Variable in the GAMS language.

generateRecords([density, func, seed])

Automatically generates records for the symbol based on a specified density and optional attribute-specific generation functions.

getAssignment()

Returns the latest GAMS assignment statement for this Variable.

getDeclaration()

Returns the GAMS declaration statement for this Variable.

getSparsity()

Calculates the sparsity of the symbol's records.

getVariableListing([n, filters])

Returns the variable listing (log output) from the last solve.

pivot([index, columns, value, fill_value])

Pivots the specified attribute of the symbol records into a two-dimensional pandas DataFrame.

product(*indices)

Equivalent to Product(indices, obj[obj.domain]).

sand(*indices)

Equivalent to Sand(indices, obj[obj.domain]).

setRecords(records[, uels_on_axes])

Sets the records (data) of the Variable.

smax(*indices)

Equivalent to Smax(indices, obj[obj.domain]).

smin(*indices)

Equivalent to Smin(indices, obj[obj.domain]).

sor(*indices)

Equivalent to Sor(indices, obj[obj.domain]).

sum(*indices)

Equivalent to Sum(indices, obj[obj.domain]).

toDense([column])

Convert column to a dense numpy.array format

toDict([columns, orient])

Converts the records of a non-scalar symbol to a Python dictionary.

toList([columns])

Converts the specified attributes of the symbol records to a Python list.

toSparseCoo([column])

Converts a specified attribute column of the symbol's records to a SciPy sparse COOrdinate format (coo_matrix).

toValue([column])

Returns the numerical value of a specified attribute for a scalar symbol.

countEps

countNA

countNegInf

countPosInf

countUndef

findEps

findNA

findNegInf

findPosInf

findSpecialValues

findUndef

getMaxAbsValue

getMaxValue

getMeanValue

getMinValue

whereMax

whereMaxAbs

whereMin

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=['i1', 'i2'])
>>> v = gp.Variable(m, "v", domain=[i], type="positive", description="Production quantity")
computeInfeasibilities() DataFrame | None[source]#

Computes infeasibilities of the variable.

Checks if the level value .l lies outside the bounds .lo and .up and returns a DataFrame containing the violations.

Returns:
pd.DataFrame | None

DataFrame showing the infeasible records.

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> x = gp.Variable(m, name="x")
>>> x.l[...] = -10
>>> x.lo[...] = 5
>>> x.computeInfeasibilities().values.tolist()
[[-10.0, 0.0, 5.0, inf, 1.0, 15.0]]
countEps(columns: str | list[str] | None = None) int#
countNA(columns: str | list[str] | None = None) int#
countNegInf(columns: str | list[str] | None = None) int#
countPosInf(columns: str | list[str] | None = None) int#
countUndef(columns: str | list[str] | None = None) int#
dropDefaults() None#

Drops records from the symbol that are equal to their default values.

This method removes records where all attributes (level, marginal, lower, upper, scale) match the default records for the symbol type.

dropEps() None#

Drops records from the symbol that contain EPS (Epsilon) values.

This method removes any record where at least one of its attributes (level, marginal, lower, upper, scale) is a SpecialValues.EPS value.

dropMissing() None#

Drops records from the symbol that contain missing (NaN) values.

This method removes any record where at least one of its attributes (level, marginal, lower, upper, scale) is missing (pandas NaN).

dropNA() None#

Drops records from the symbol that contain NA (Not Available) values.

This method removes any record where at least one of its attributes (level, marginal, lower, upper, scale) is a SpecialValues.NA value.

dropUndef() None#

Drops records from the symbol that contain UNDEF (Undefined) values.

This method removes any record where at least one of its attributes (level, marginal, lower, upper, scale) is a SpecialValues.UNDEF value.

equals(other: Variable | Equation, columns: str | list[str] | None = None, check_meta_data: bool = True, rtol: int | float | None = None, atol: int | float | None = None) bool#

Compares this symbol with another symbol to evaluate structural and numerical equality across specified attributes.

This method verifies dimensions, domain types, and data structure. It then performs an outer merge to match domains and checks the specified attribute columns for strict special value equivalence (EPS, NA, UNDEF) and numeric closeness (using relative and absolute tolerances).

Parameters:
otherVariable | Equation

The other Variable or Equation object to compare against.

columnsstr | list[str] | None, optional

The specific attribute column(s) to evaluate (e.g., [“level”, “marginal”]). If None, defaults to all symbol attributes (_attributes).

check_meta_databool, optional

If True, verifies that the symbol names and descriptions match exactly. Defaults to True.

rtolint | float | None, optional

Relative tolerance used for numeric evaluation via np.isclose. Defaults to 0.0.

atolint | float | None, optional

Absolute tolerance used for numeric evaluation via np.isclose. Defaults to 0.0.

Returns:
bool

True if the symbols are structurally identical and the evaluated attributes are equivalent within the specified tolerances; False otherwise.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["A", "B"])
>>> v1 = gp.Variable(m, name="v1", type="positive", domain=[i])
>>> v2 = gp.Variable(m, name="v2", type="positive", domain=[i])
>>> v1.equals(v2, check_meta_data=False)
True
findEps(column: str | None = None) pd.DataFrame | None#
findNA(column: str | None = None) pd.DataFrame | None#
findNegInf(column: str | None = None) pd.DataFrame | None#
findPosInf(column: str | None = None) pd.DataFrame | None#
findSpecialValues(values: float | list[float], column: str | None = None) pd.DataFrame | None#
findUndef(column: str | None = None) pd.DataFrame | None#
gamsRepr() str[source]#

Returns the string representation of this Variable in the GAMS language.

(e.g., ‘x(i)’).

Returns:
str

The GAMS string representation.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> x = gp.Variable(m, name="x", domain=i, type="positive")
>>> x.gamsRepr()
'x(i)'
generateRecords(density: int | float | list | None = None, func: dict[str, Callable] | None = None, seed: int | None = None) None#

Automatically generates records for the symbol based on a specified density and optional attribute-specific generation functions.

By default, the “level” attribute is populated with uniformly distributed floats between 0.0 and 1.0, while all other attributes (e.g., marginal, lower, upper) are initialized to the symbol’s default record limits.

Parameters:
densityint | float | list | None, optional

The target density for the generated records on the interval [0, 1]. * A single numeric value applies to the overall cartesian product. * A list applies specific densities to each domain independently. * Defaults to 1.0.

funcdict[str, Callable] | None, optional

A dictionary mapping attribute strings (e.g., “level”, “marginal”) to custom callables. If provided, each callable is invoked as func(seed=seed, size=(num_records,)). Attributes not specified in the dictionary fallback to the symbol’s defaults.

seedint | None, optional

A random seed for reproducibility during domain sampling and value generation.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["A", "B"])
>>> v = gp.Variable(m, name="v", type="positive", domain=[i])
>>> v.generateRecords(seed=42)
>>> e = gp.Equation(m, name="e", domain=i)
>>> e.generateRecords(seed=42)
getAssignment() str[source]#

Returns the latest GAMS assignment statement for this Variable.

Returns:
str

The GAMS assignment string.

Raises:
ValidationError

If the variable has not been assigned.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=['i1','i2'])
>>> v = gp.Variable(m, "v", domain=[i])
>>> v.l[i] = 0;
>>> v.getAssignment()
'v.l(i) = 0;'
getDeclaration() str[source]#

Returns the GAMS declaration statement for this Variable.

(e.g., ‘Positive Variable x(i);’).

Returns:
str

The GAMS declaration string.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=['i1','i2'])
>>> v = gp.Variable(m, "v", domain=[i])
>>> v.getDeclaration()
'free Variable v(i) / /;'
getMaxAbsValue(columns: str | list[str] | None = None) float#
getMaxValue(columns: str | list[str] | None = None) float#
getMeanValue(columns: str | list[str] | None = None) float#
getMinValue(columns: str | list[str] | None = None) float#
getSparsity() float#

Calculates the sparsity of the symbol’s records.

Sparsity is defined as 1 - (number_of_records / maximum_possible_records), where the maximum possible records is the product of the number of records in each of the symbol’s domain sets. A sparsity of 1.0 means the symbol has no records (completely empty), while 0.0 means the symbol is fully dense.

Returns:
float

The sparsity of the symbol (between 0.0 and 1.0). Returns float(“nan”) if the symbol is a scalar, has a relaxed domain (e.g., [“*”]), or if any of its domain sets have no records.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["A", "B"])
>>> j = gp.Set(m, name="j", records=["X", "Y", "Z"])
>>> p = gp.Parameter(m, name="p", domain=[i, j], records=[("A", "X", 10)])
>>> p.getSparsity()
0.8333333333333334
getVariableListing(n: int | None = None, filters: list[list[str]] | None = None) str[source]#

Returns the variable listing (log output) from the last solve.

This requires the model to have been solved with the variable_listing_limit option enabled.

Parameters:
nint, optional

Maximum number of variables to return.

filterslist[list[str]], optional

Filters to select specific elements for the listing. The list size must match the variable’s dimension.

Returns:
str

The text listing of the variable’s status and values.

Raises:
ValidationError

If the model was not solved with variable_listing_limit.

ValidationError

If the filter size does not match the variable dimension.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, records=["item1", "item2"])
>>> v = gp.Variable(m, domain=i)
>>> z = gp.Variable(m)
>>> e = gp.Equation(m, domain=i)
>>> e[i] = v[i] * z >= 5
>>> model = gp.Model(m, "test", equations=[e], problem="NLP", sense="MIN", objective=z)
>>> summary = model.solve(options=gp.Options(variable_listing_limit=10))
>>> print(v.getVariableListing())
v(item1)
                (.LO, .L, .UP, .M = -INF, 0, +INF, 0)
       (0)      e(item1)

v(item2)
                (.LO, .L, .UP, .M = -INF, 0, +INF, 0)
       (0)      e(item2)
pivot(index: str | list | None = None, columns: str | list | None = None, value: str | None = None, fill_value: int | float | str | None = None) pd.DataFrame#

Pivots the specified attribute of the symbol records into a two-dimensional pandas DataFrame. This isolates a specific attribute column (e.g., “level” or “marginal”) and pivots the data across the specified index and column domains.

Parameters:
indexstr | list | None, optional

Column(s) to use for the new frame’s index. If None, defaults to all domain labels except the last dimension.

columnsstr | list | None, optional

Column(s) to use for the new frame’s columns. If None, defaults to the last dimension of the domain labels.

valuestr | None, optional

The specific symbol attribute to pivot (e.g., “level”, “marginal”, “lower”, “upper”, “scale”). If None, defaults to “level”.

fill_valueint | float | str | None, optional

Value used to fill missing data created by the pivot operation. Defaults to 0.0.

Returns:
pd.DataFrame

The pivoted DataFrame representing the specified attribute.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["A", "B"])
>>> j = gp.Set(m, name="j", records=["X", "Y"])
>>> v = gp.Variable(m, name="v", domain=[i, j])
>>> # Assuming variable has been solved/populated
>>> df_level = v.pivot(value="level")
product(*indices: Set | Alias) Product#

Equivalent to Product(indices, obj[obj.domain]). For example:

v = Variable(m, domain=[i, j, k]) v.product() is equivalent to Product((i,j), v[i, j, k]) v.product(i) is equivalent to Product(i, v[i, j, k]) v.product(i, j) is equivalent to Product((i, j), v[i, j, k])

Returns:
Product

Generated Product operation.

Raises:
ValidationError

In case the symbol is scalar.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i")
>>> j = gp.Set(m, "j")
>>> x = gp.Parameter(m, "x", domain=[i, j])
>>> y = gp.Parameter(m, "y")
>>> x.product().gamsRepr()
'prod((i,j),x(i,j))'
>>> gp.Product((i, j), x[i, j]).gamsRepr()
'prod((i,j),x(i,j))'
sand(*indices: Set | Alias) Sand#

Equivalent to Sand(indices, obj[obj.domain]). For example:

v = Variable(m, domain=[i, j, k]) v.sand() is equivalent to Sand((i,j), v[i, j, k]) v.sand(i) is equivalent to Sand(i, v[i, j, k]) v.sand(i, j) is equivalent to Sand((i, j), v[i, j, k])

Returns:
Sand

Generated Sand operation.

Raises:
ValidationError

In case the symbol is scalar.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i")
>>> j = gp.Set(m, "j")
>>> x = gp.Parameter(m, "x", domain=[i, j])
>>> y = gp.Parameter(m, "y")
>>> x.sand().gamsRepr()
'sand((i,j),x(i,j))'
>>> gp.Sand((i, j), x[i, j]).gamsRepr()
'sand((i,j),x(i,j))'
setRecords(records: VarEquRecordsType | None, uels_on_axes: bool = False) None[source]#

Sets the records (data) of the Variable.

This is a convenience method to load data. It accepts various input formats. If uels_on_axes=True, it assumes domain information is in the pandas axes.

Parameters:
recordsSequence | np.ndarray | int | float | pd.DataFrame | pd.Series | dict

The data to load (e.g., list, numpy array, DataFrame).

uels_on_axesbool, optional

If True, assumes domain elements are in the axes of the DataFrame. Default is False.

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> x = gp.Variable(m, name="x", domain=i)
>>> x.setRecords(records=np.array([7, 18]))
>>> x.records.values.tolist()
[['seattle', 7.0, 0.0, -inf, inf, 1.0], ['san-diego', 18.0, 0.0, -inf, inf, 1.0]]
smax(*indices: Set | Alias) Smax#

Equivalent to Smax(indices, obj[obj.domain]). For example:

v = Variable(m, domain=[i, j, k]) v.smax() is equivalent to Smax((i,j), v[i, j, k]) v.smax(i) is equivalent to Smax(i, v[i, j, k]) v.smax(i, j) is equivalent to Smax((i, j), v[i, j, k])

Returns:
Smax

Generated Smax operation.

Raises:
ValidationError

In case the symbol is scalar.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i")
>>> j = gp.Set(m, "j")
>>> x = gp.Parameter(m, "x", domain=[i, j])
>>> y = gp.Parameter(m, "y")
>>> x.smax().gamsRepr()
'smax((i,j),x(i,j))'
>>> gp.Smax((i, j), x[i, j]).gamsRepr()
'smax((i,j),x(i,j))'
smin(*indices: Set | Alias) Smin#

Equivalent to Smin(indices, obj[obj.domain]). For example:

v = Variable(m, domain=[i, j, k]) v.smin() is equivalent to Smin((i,j), v[i, j, k]) v.smin(i) is equivalent to Smin(i, v[i, j, k]) v.smin(i, j) is equivalent to Smin((i, j), v[i, j, k])

Returns:
Smin

Generated Smin operation.

Raises:
ValidationError

In case the symbol is scalar.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i")
>>> j = gp.Set(m, "j")
>>> x = gp.Parameter(m, "x", domain=[i, j])
>>> y = gp.Parameter(m, "y")
>>> x.smin().gamsRepr()
'smin((i,j),x(i,j))'
>>> gp.Smin((i, j), x[i, j]).gamsRepr()
'smin((i,j),x(i,j))'
sor(*indices: Set | Alias) Sor#

Equivalent to Sor(indices, obj[obj.domain]). For example:

v = Variable(m, domain=[i, j, k]) v.sor() is equivalent to Sor((i,j), v[i, j, k]) v.sor(i) is equivalent to Sor(i, v[i, j, k]) v.sor(i, j) is equivalent to Sor((i, j), v[i, j, k])

Returns:
Sor

Generated Sor operation.

Raises:
ValidationError

In case the symbol is scalar.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i")
>>> j = gp.Set(m, "j")
>>> x = gp.Parameter(m, "x", domain=[i, j])
>>> y = gp.Parameter(m, "y")
>>> x.sor().gamsRepr()
'sor((i,j),x(i,j))'
>>> gp.Sor((i, j), x[i, j]).gamsRepr()
'sor((i,j),x(i,j))'
sum(*indices: Set | Alias) Sum#

Equivalent to Sum(indices, obj[obj.domain]). For example:

v = Variable(m, domain=[i, j, k]) v.sum() is equivalent to Sum((i,j), v[i, j, k]) v.sum(i) is equivalent to Sum(i, v[i, j, k]) v.sum(i, j) is equivalent to Sum((i, j), v[i, j, k])

Returns:
Sum

Generated Sum operation.

Raises:
ValidationError

In case the symbol is scalar.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i")
>>> j = gp.Set(m, "j")
>>> x = gp.Parameter(m, "x", domain=[i, j])
>>> y = gp.Parameter(m, "y")
>>> x.sum().gamsRepr()
'sum((i,j),x(i,j))'
>>> gp.Sum((i, j), x[i, j]).gamsRepr()
'sum((i,j),x(i,j))'
toDense(column: str = 'level') ndarray | None#

Convert column to a dense numpy.array format

Parameters:
columnstr, optional

The column to convert, by default “level”

Returns:
np.ndarray, optional

A column to a dense numpy.array format

toDict(columns: str | list[str] | None = None, orient: str | None = None) dict#

Converts the records of a non-scalar symbol to a Python dictionary.

Parameters:
columnsstr | list[str] | None, optional

The attribute column(s) to extract (e.g., “level”, “marginal”). If None, defaults to “level”.

orientstr | None, optional

The format of the dictionary. Options are: - “natural” (default): Maps domain elements to values. If multiple columns are requested,

the value becomes a dictionary mapping attributes to their values.

  • “columns”: Returns a dictionary of columns, mimicking a pandas DataFrame structure.

Returns:
dict

A dictionary containing the requested symbol attributes. Returns an empty dict if there are no records.

Raises:
TypeError

If the symbol is a scalar, or if an invalid column name is provided.

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["A", "B"])
>>> v = gp.Variable(m, name="v", domain=[i])
>>> v.setRecords(np.array([10.0, 20.0]))
>>> v.toDict(columns="level")
{'A': 10.0, 'B': 20.0}
toList(columns: str | None = None) list#

Converts the specified attributes of the symbol records to a Python list.

Parameters:
columnsstr | list[str] | None, optional

The attribute column(s) to include (e.g., “level”, “marginal”, “lower”, “upper”, “scale”). If None, defaults to “level”.

Returns:
list

A list containing the requested attribute values. For scalar symbols, it returns a list of tuples containing the attributes. For multi-dimensional symbols, it returns a list of tuples where domain indices are followed by the requested attributes. Returns an empty list if there are no records.

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["A", "B"])
>>> v = gp.Variable(m, name="v", domain=[i])
>>> v.setRecords(np.array([1.0, 2.0]))
>>> v.toList(columns="level")
[('A', 1.0), ('B', 2.0)]
toSparseCoo(column: str = 'level') coo_matrix | None#

Converts a specified attribute column of the symbol’s records to a SciPy sparse COOrdinate format (coo_matrix).

This method is only available for symbols with 2 or fewer dimensions. For scalar symbols (0D), it returns a 1x1 matrix. For 1D symbols, it returns a 1xN matrix. For 2D symbols, it returns an MxN matrix.

Parameters:
columnstr, optional

The attribute column to convert (e.g., “level”, “marginal”, “lower”, “upper”, “scale”). Defaults to “level”.

Returns:
coo_matrix | None

A SciPy sparse COO matrix containing the specified attribute values. Returns None if there are no records.

Raises:
TypeError

If the column argument is not a string, or if it is not a valid attribute for the symbol.

ValidationError

If the symbol has a dimension greater than 2.

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["A", "B"])
>>> j = gp.Set(m, name="j", records=["X", "Y"])
>>> v = gp.Variable(m, name="v", domain=[i, j])
>>> v.setRecords(np.array([[1.5, 0], [0, 2.5]]))
>>> sparse_mat = v.toSparseCoo(column="level")  # doctest +SKIP
toValue(column: str | None = None) float#

Returns the numerical value of a specified attribute for a scalar symbol.

Parameters:
columnstr | None, optional

The attribute to extract (e.g., “level”, “marginal”, “lower”, “upper”, “scale”). If None, defaults to “level”.

Returns:
float

The floating-point value of the requested attribute.

Raises:
TypeError

If the symbol is not a scalar (dimension > 0) or if an invalid column name is provided.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> v = gp.Variable(m, name="v")
>>> v.l[...] = 15.5
>>> v.toValue(column="level")
np.float64(15.5)
whereMax(column: str | None = None) list[str]#
whereMaxAbs(column: str | None = None) list[str]#
whereMin(column: str | None = None) list[str]#
property container: Container#

Container of the symbol

property description: str#

Description of the symbol

property dimension: int#

The dimension of symbol

property domain: NormalizedDomainType#

List of domains given either as string (* for universe set) or as reference to the Set/Alias object

property domain_labels: list[str]#

The column headings for the records DataFrame

property domain_names: list[str]#

String version of domain names

property domain_type#

State of the domain links

property fx: ImplicitParameter#

Fixed value of the variable.

Setting .fx implies setting both .lo and .up to the same value. Reading .fx returns the current fixed level (if fixed).

Returns:
ImplicitParameter

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> d = gp.Parameter(m, name="d", domain=i, records=np.array([7, 18]))
>>> x = gp.Variable(m, name="x", domain=i)
>>> x.fx[i] = d[i]
>>> x.records.values.tolist()
[['seattle', 7.0, 0.0, 7.0, 7.0, 1.0], ['san-diego', 18.0, 0.0, 18.0, 18.0, 1.0]]
property is_scalar: bool#

Returns True if the len(self.domain) = 0

Returns:
bool

True if the len(self.domain) = 0

property l: ImplicitParameter#

The Level of the variable (its current value).

This corresponds to the .l suffix in GAMS. After a solve, this holds the solution value.

Returns:
ImplicitParameter

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> d = gp.Parameter(m, name="d", domain=i, records=np.array([7, 18]))
>>> x = gp.Variable(m, name="x", domain=i)
>>> x.l[i] = d[i]
>>> x.records.values.tolist()
[['seattle', 7.0, 0.0, -inf, inf, 1.0], ['san-diego', 18.0, 0.0, -inf, inf, 1.0]]
property lo: ImplicitParameter#

The Lower Bound of the variable.

This corresponds to the .lo suffix in GAMS.

Returns:
ImplicitParameter

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> d = gp.Parameter(m, name="d", domain=i, records=np.array([7, 18]))
>>> x = gp.Variable(m, name="x", domain=i)
>>> x.lo[i] = d[i]
>>> x.records.values.tolist()
[['seattle', 0.0, 0.0, 7.0, inf, 1.0], ['san-diego', 0.0, 0.0, 18.0, inf, 1.0]]
property m: ImplicitParameter#

The Marginal (dual value) of the variable.

This corresponds to the .m suffix in GAMS. Represents the reduced cost.

Returns:
ImplicitParameter

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> d = gp.Parameter(m, name="d", domain=i, records=np.array([7, 18]))
>>> x = gp.Variable(m, name="x", domain=i)
>>> x.m[i] = d[i]
>>> x.records.values.tolist()
[['seattle', 0.0, 7.0, -inf, inf, 1.0], ['san-diego', 0.0, 18.0, -inf, inf, 1.0]]
property number_records: int#

Number of records

property prior: ImplicitParameter#

Branching Priority.

This corresponds to the .prior suffix in GAMS. Allows identifying a priority for branching on discrete variables. Valid only for discrete variable types (integer, binary).

Returns:
ImplicitParameter

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> d = gp.Parameter(m, name="d", domain=i, records=np.array([7, 18]))
>>> x = gp.Variable(m, name="x", domain=i, type="integer")
>>> x.prior[i] = d[i]
>>> x.records.values.tolist()
[['seattle', 0.0, 0.0, 0.0, inf, 7.0], ['san-diego', 0.0, 0.0, 0.0, inf, 18.0]]
property records: DataFrame | None#

Returns the records (data) of the Variable as a DataFrame.

The DataFrame contains columns for the domain sets, and columns for level, marginal, lower, upper, and scale.

Returns:
DataFrame | None

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> d = gp.Parameter(m, name="d", domain=i, records=np.array([7, 18]))
>>> x = gp.Variable(m, name="x", domain=i)
>>> x.fx[i] = d[i]
>>> x.records.values.tolist()
[['seattle', 7.0, 0.0, 7.0, 7.0, 1.0], ['san-diego', 18.0, 0.0, 18.0, 18.0, 1.0]]
property scale: ImplicitParameter#

The Scale factor of the variable.

This corresponds to the .scale suffix in GAMS, used for scaling the variable to improve numerical stability.

Returns:
ImplicitParameter

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> d = gp.Parameter(m, name="d", domain=i, records=np.array([7, 18]))
>>> x = gp.Variable(m, name="x", domain=i)
>>> x.scale[i] = d[i]
>>> x.records.values.tolist()
[['seattle', 0.0, 0.0, -inf, inf, 7.0], ['san-diego', 0.0, 0.0, -inf, inf, 18.0]]
property shape: tuple#

!! processed by numpydoc !!

property stage: ImplicitParameter#

Branching Stage.

This corresponds to the .stage suffix in GAMS. Used in stochastic programming or advanced branching strategies.

Returns:
ImplicitParameter

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> d = gp.Parameter(m, name="d", domain=i, records=np.array([7, 18]))
>>> x = gp.Variable(m, name="x", domain=i, type="integer")
>>> x.stage[i] = d[i]
>>> x.records.values.tolist()
[['seattle', 0.0, 0.0, 0.0, inf, 7.0], ['san-diego', 0.0, 0.0, 0.0, inf, 18.0]]
property summary#

!! processed by numpydoc !!

property synchronize: bool#

Synchronization state of the symbol. If True, the symbol data will be communicated with GAMS. Otherwise, GAMS state will not be updated.

Returns:
bool
property type: str#

!! processed by numpydoc !!

property up: ImplicitParameter#

The Upper Bound of the variable.

This corresponds to the .up suffix in GAMS.

Returns:
ImplicitParameter

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> d = gp.Parameter(m, name="d", domain=i, records=np.array([7, 18]))
>>> x = gp.Variable(m, name="x", domain=i)
>>> x.up[i] = d[i]
>>> x.records.values.tolist()
[['seattle', 0.0, 0.0, -inf, 7.0, 1.0], ['san-diego', 0.0, 0.0, -inf, 18.0, 1.0]]
class gamspy.VariableType(*values)[source]#

Bases: Enum

Enumeration of available variable types.

BINARY = 'binary'#

Discrete variable that can only take values of 0 or 1.

FREE = 'free'#

No bounds on variable. Both bounds may be changed from the default values by the user.

INTEGER = 'integer'#

Discrete variable that can only take integer values between the bounds.

NEGATIVE = 'negative'#

No positive values are allowed for variables. The user may change both bounds from the default value.

POSITIVE = 'positive'#

No negative values are allowed for variable. The user may change both bounds from the default value.

SEMICONT = 'semicont'#

Semi-continuous, must be zero or above a given minimum level.

SEMIINT = 'semiint'#

Semi-integer, must be zero or above a given minimum level and integer.

SOS1 = 'sos1'#

A set of variables, such that at most one variable within a group may have a non-zero value.

SOS2 = 'sos2'#

A set of variables, such that at most two variables within a group may have non-zero values and the two non-zero values are adjacent.