Set#

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

Bases: Operable, DomainSymbol, SetMixin

Represents a Set symbol in GAMS.

See https://gamspy.readthedocs.io/en/latest/user/basics/set.html for more details.

Parameters:
containerContainer

The Container object that this set belongs to.

namestr, optional

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

domainSequence[Set | Alias | str] | Set | Alias | str, optional

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

is_singletonbool, optional

If True, restricts the set to contain at most one element. Default is False.

recordspd.DataFrame | np.ndarray | list, optional

Initial elements to populate the set.

domain_forwardingbool | list[bool], optional

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

descriptionstr, optional

A human-readable description of the set.

uels_on_axesbool, optional

If True, implies that the Unique Element Labels (UELs) for the domain are contained in the axes (index/columns) of the provided records object (e.g., pandas DataFrame). Default is False.

is_miro_inputbool, optional

If True, flags this set as an input symbol for GAMS MIRO. Default is False.

is_miro_outputbool, optional

If True, flags this set 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

first

Returns 1 if the element is the first in the set, otherwise 0.

is_singleton
last

Returns 1 if the element is the last in the set, otherwise 0.

len

Returns the length of the set element name (count of characters).

number_records

Number of records

off

Returns the element position in the current set minus 1.

ord

Same as .pos but for ordered sets only.

pos

Returns the element position in the current set, starting with 1.

records

Records of the Set

rev

Returns the reverse element position in the current set.

summary
synchronize

Synchronization state of the symbol.

tlen

Returns the length of the set element explanatory text (count of characters).

tval

Returns the numerical value if the set element text is a number.

uel

Returns the element position in the global Unique Element List (UEL).

val

Returns the numerical value if the set element name is a number.

Methods

equals(other, *[, check_element_text, ...])

Compares this Set with another Set or Alias for equality.

gamsRepr()

Representation of this Set in GAMS language.

generateRecords([density, seed])

Automatically generates records for the Set based on a specified density.

getAssignment()

Latest assignment to the Set in GAMS

getDeclaration()

Declaration of the Set in GAMS

getSparsity()

Calculates the sparsity of the symbol's records.

lag(n[, type])

Shifts the values of a Set or Alias by n positions to the left (lag).

lead(n[, type])

Shifts the values of a Set or Alias by n positions to the right (lead).

pivot([index, columns, fill_value])

Convenience function to pivot records into a new shape (only symbols with >1D can be pivoted).

sameAs(other)

Evaluates to True if the current set element is identical to the given symbol or string.

setRecords(records[, uels_on_axes])

Sets the records (elements) of the Set.

toList(*[, include_element_text])

Converts the records of the Set to a Python list.

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"])
equals(other: Set | Alias, *, check_element_text: bool = True, check_meta_data: bool = True) bool[source]#

Compares this Set with another Set or Alias for equality.

Parameters:
otherSet | Alias

The other Set or Alias object to compare against.

check_element_textbool, optional

If True, includes the element explanatory text in the equality check. Defaults to True.

check_meta_databool, optional

If True, includes symbol metadata in the equality check. Defaults to True.

Returns:
bool

True if the sets are considered equal based on the given parameters, False otherwise.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> j = gp.Set(m, name="j", records=["seattle", "san-diego"])
>>> i.equals(j, check_meta_data=False)
True
gamsRepr() str[source]#

Representation of this Set in GAMS language.

Returns:
str

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", domain=["*"], records=['i1','i2'])
>>> i.gamsRepr()
'i'
generateRecords(density: int | float | list | None = None, seed: int | None = None) None[source]#

Automatically generates records for the Set based on a specified density.

Parameters:
densityint | float | list | None, optional

The target density for the generated records. Can be a single numeric value or a list. Provinig a list allows users to specify a density per symbol dimension.

seedint | None, optional

A random seed to ensure reproducibility of the generated records.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=range(10))
>>> a = gp.Parameter(m, name="a", domain=i)
>>> # Generate records with 50% density
>>> a.generateRecords(density=0.5, seed=42)
getAssignment() str[source]#

Latest assignment to the Set in GAMS

Returns:
str
Raises:
ValueError

When type is not circular or linear

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=['i1','i2'])
>>> i['i1'] = False
>>> i.getAssignment()
'i("i1") = no;'
getDeclaration() str[source]#

Declaration of the Set in GAMS

Returns:
str

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=['i1','i2'])
>>> i.getDeclaration()
'Set i(*);'
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
lag(n: OperableType, type: Literal['linear', 'circular'] = 'linear') ImplicitSet#

Shifts the values of a Set or Alias by n positions to the left (lag).

Parameters:
nOperableType

The number of positions to shift. Can be an integer or a GAMS symbol.

type‘linear’ or ‘circular’, optional

The type of lag to perform: - ‘linear’ (default): Elements shifted out of bounds are dropped. - ‘circular’: Elements shifted out of bounds wrap around to the end.

Returns:
ImplicitSet

The shifted set expression.

Raises:
ValueError

If type is not ‘linear’ or ‘circular’.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> t = gp.Set(m, name="t", description="time sequence", records=[f"y-{x}" for x in range(1987, 1992)])
>>> a = gp.Parameter(m, name="a", domain=[t])
>>> b = gp.Parameter(m, name="b", domain=[t])
>>> a[t] = 1986 + gp.Ord(t)
>>> b[t] = a[t.lag(1, "linear")]
>>> b.records.values.tolist()
[['y-1988', 1987.0], ['y-1989', 1988.0], ['y-1990', 1989.0], ['y-1991', 1990.0]]
lead(n: OperableType, type: Literal['linear', 'circular'] = 'linear') ImplicitSet#

Shifts the values of a Set or Alias by n positions to the right (lead).

Parameters:
nOperableType

The number of positions to shift. Can be an integer or a GAMS symbol.

type‘linear’ or ‘circular’, optional

The type of lead to perform: - ‘linear’ (default): Elements shifted out of bounds are dropped. - ‘circular’: Elements shifted out of bounds wrap around to the beginning.

Returns:
ImplicitSet

The shifted set expression.

Raises:
ValueError

If type is not ‘linear’ or ‘circular’.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> t = gp.Set(m, name="t", description="time sequence", records=[f"y-{x}" for x in range(1987, 1992)])
>>> a = gp.Parameter(m, name="a", domain=[t])
>>> c = gp.Parameter(m, name="c", domain=[t])
>>> a[t] = 1986 + gp.Ord(t)
>>> c[t.lead(2, "linear")] = a[t]
>>> c.records.values.tolist()
[['y-1989', 1987.0], ['y-1990', 1988.0], ['y-1991', 1989.0]]
pivot(index: str | list | None = None, columns: str | list | None = None, fill_value: int | float | str | None = None) DataFrame[source]#

Convenience function to pivot records into a new shape (only symbols with >1D can be pivoted). If index is None then it is set to dimensions [0..dimension-1]. If columns is None then it is set to the last dimension. Missing values in the pivot will take the value provided by fill_value.

Parameters:
indexstr | list | None, optional

Column(s) to use to make new frame’s index.

columnsstr | list | None, optional

Column(s) to use to make new frame’s columns.

fill_valueint | float | str | None, optional

Value to use for missing values.

Returns:
pd.DataFrame

The pivoted DataFrame representing the set records.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> j = gp.Set(m, name="j", records=["new-york", "chicago"])
>>> # Pivot requires a symbol with dimension > 1
>>> ij = gp.Set(m, name="ij", domain=[i, j], records=[("seattle", "new-york")])
>>> df = ij.pivot()
sameAs(other: Set | Alias | str) MathOp#

Evaluates to True if the current set element is identical to the given symbol or string.

This corresponds to the sameAs operator in GAMS.

Parameters:
otherSet | Alias | str

The other set, alias, or string label to compare against.

Returns:
MathOp

A boolean expression that evaluates to True (1) if they match, False (0) otherwise.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> j = gp.Set(m, name="j", records=["new-york", "seattle"])
>>> attr = gp.Parameter(m, "attr", domain=[i, j])
>>> attr[i,j] = i.sameAs(j)
>>> attr.records.values.tolist()
[['seattle', 'seattle', 1.0]]
setRecords(records: SetRecordsType | None, uels_on_axes: bool = False) None[source]#

Sets the records (elements) of the Set.

This is a convenience method to load data into the set. It handles various input formats like lists and pandas DataFrames.

Parameters:
recordspd.DataFrame | pd.Series | Sequence

The data to load. Common formats:

  • List of strings: [‘i1’, ‘i2’]

  • List of tuples (for multi-dimensional sets): [(‘a’, ‘1’), (‘b’, ‘2’)]

  • pandas DataFrame.

uels_on_axesbool, optional

If True, assumes that the domain information is located in the axes (index/columns) of the records object rather than the data values. Use this when passing a DataFrame where the indices represent the set elements.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i")
>>> i.setRecords(["seattle", "san-diego"])
>>> i.records.values.tolist()
[['seattle', ''], ['san-diego', '']]
toList(*, include_element_text: bool = False) list[source]#

Converts the records of the Set to a Python list.

Parameters:
include_element_textbool, optional

If True, includes the element explanatory text in the output. Defaults to False.

Returns:
list

A list of the set elements. If the set has dimension > 1, the elements are returned as tuples.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego"])
>>> i.toList()
['seattle', 'san-diego']
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 first: ImplicitParameter#

Returns 1 if the element is the first in the set, otherwise 0.

This attribute corresponds to the .first attribute in GAMS.

Returns:
ImplicitParameter

An implicit parameter with value 1 for the first element.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego", "new-york"], description="canning plants")
>>> i.first.records.values.tolist()
[['seattle', 'is_first', 1.0]]
property is_singleton: bool#

!! processed by numpydoc !!

property last: ImplicitParameter#

Returns 1 if the element is the last in the set, otherwise 0.

This attribute corresponds to the .last attribute in GAMS.

Returns:
ImplicitParameter

An implicit parameter with value 1 for the last element.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego", "new-york"], description="canning plants")
>>> i.last.records.values.tolist()
[['new-york', 'is_last', 1.0]]
property len: ImplicitParameter#

Returns the length of the set element name (count of characters).

This attribute corresponds to the .len attribute in GAMS.

Returns:
ImplicitParameter

The character count of the element name.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego", "new-york"], description="canning plants")
>>> i.len.records.values.tolist()
[['seattle', 'length', 7.0], ['san-diego', 'length', 9.0], ['new-york', 'length', 8.0]]
property number_records: int#

Number of records

property off: ImplicitParameter#

Returns the element position in the current set minus 1.

Mathematically: .off = .pos - 1. This attribute corresponds to the .off attribute in GAMS.

Returns:
ImplicitParameter

The offset position of the element.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego", "new-york"], description="canning plants")
>>> i.off.records.values.tolist()
[['san-diego', 'off', 1.0], ['new-york', 'off', 2.0]]
property ord: ImplicitParameter#

Same as .pos but for ordered sets only.

Returns:
ImplicitParameter

The ordinal position of the element.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego", "new-york"], description="canning plants")
>>> i.ord.records.values.tolist()
[['seattle', 'order', 1.0], ['san-diego', 'order', 2.0], ['new-york', 'order', 3.0]]
property pos: ImplicitParameter#

Returns the element position in the current set, starting with 1.

This attribute corresponds to the .pos attribute in GAMS.

Returns:
ImplicitParameter

The position of the element.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego", "new-york"], description="canning plants")
>>> i.pos.records.values.tolist()
[['seattle', 'position', 1.0], ['san-diego', 'position', 2.0], ['new-york', 'position', 3.0]]
property records: DataFrame | None#

Records of the Set

Returns:
DataFrame | None

Examples

>>> import gamspy as gp
>>> import numpy as np
>>> m = gp.Container()
>>> i = gp.Set(m, name="i")
>>> i.setRecords(["seattle", "san-diego"])
>>> i.records.values.tolist()
[['seattle', ''], ['san-diego', '']]
property rev: ImplicitParameter#

Returns the reverse element position in the current set.

The value for the last element is 0, the penultimate is 1, and so on. This attribute corresponds to the .rev attribute in GAMS.

Returns:
ImplicitParameter

The reverse position value.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego", "new-york"], description="canning plants")
>>> i.rev.records.values.tolist()
[['seattle', 'reverse', 2.0], ['san-diego', 'reverse', 1.0]]
property summary: dict#

!! 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 tlen: ImplicitParameter#

Returns the length of the set element explanatory text (count of characters).

This attribute corresponds to the .tlen attribute in GAMS.

Returns:
ImplicitParameter

The character count of the element text.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=[("seattle", "Wisconsin"), ("san-diego", ""), ("new-york", " ")], description="canning plants")
>>> i.tlen.records.values.tolist()
[['seattle', 'text_length', 9.0], ['new-york', 'text_length', 1.0]]
property tval: ImplicitParameter#

Returns the numerical value if the set element text is a number.

If the element text is not a number, this attribute is undefined. This attribute corresponds to the .tval attribute in GAMS.

Returns:
ImplicitParameter

The numerical value of the element text.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=[("seattle", "12"), ("san-diego", ""), ("new-york", "-13.4")], description="canning plants")
>>> i.tval.records.values.tolist()
[['seattle', 'text_value', 12.0], ['new-york', 'text_value', -13.4]]
property uel: ImplicitParameter#

Returns the element position in the global Unique Element List (UEL).

This attribute corresponds to the .uel attribute in GAMS.

Returns:
ImplicitParameter

The position index in the UEL table.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["seattle", "san-diego", "new-york"], description="canning plants")
>>> i.uel.records.values.tolist()
[['seattle', 'uel_position', 1.0], ['san-diego', 'uel_position', 2.0], ['new-york', 'uel_position', 3.0]]
property val: ImplicitParameter#

Returns the numerical value if the set element name is a number.

If the element is not a number, this attribute is undefined and may result in an error or ignored record. This attribute corresponds to the .val attribute in GAMS.

Returns:
ImplicitParameter

The numerical value of the element name.

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, name="i", records=["12", "20", "-13.4"], description="canning plants")
>>> i.val.records.values.tolist()
[['12', 'value', 12.0], ['20', 'value', 20.0], ['-13.4', 'value', -13.4]]