Set#

class gamspy.Set(container, name, domain=None, is_singleton=False, records=None, domain_forwarding=False, description='', uels_on_axes=False, is_miro_input=False, is_miro_output=False)[source]#

Bases: Set, Operable, Symbol, SetMixin

Represents a Set symbol in GAMS. https://www.gams.com/latest/docs/UG_SetDefinition.html

Parameters:
containerContainer
namestr
domainlist, optional
is_singletonbool, optional
recordsint | float | DataFrame, optional
domain_forwardingbool, optional
descriptionstr, optional
uels_on_axesbool
is_miro_inputbool
is_miro_outputbool
Parameters:
  • container (Container) –

  • name (str) –

  • domain (list[Set | str] | None) –

  • is_singleton (bool) –

  • records (Any | None) –

  • domain_forwarding (bool) –

  • description (str) –

  • uels_on_axes (bool) –

  • is_miro_input (bool) –

  • is_miro_output (bool) –

Examples

>>> import gamspy as gp
>>> m = gp.Container()
>>> i = gp.Set(m, "i", records=['i1','i2'])
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_forwarding

A boolean indicating whether domain forwarding is enabled

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 for the first set element, otherwise 0.

is_singleton

Whether a symbol is a singleton set

last

Returns 1 for the last set element, otherwise 0.

len

Length of the set element name (a count of the number of characters).

modified

Flag that identifies if the symbol has been modified

name

Name of symbol

number_records

Number of records

off

Element position in the current set minus 1.

ord

Same as .pos but for ordered sets only.

pos

Element position in the current set, starting with 1.

records

Records of the Set

rev

Reverse element position in the current set, so the value for the last element is 0, the value for the penultimate is 1, etc.

summary

Returns a dict of only the metadata

tlen

Length of the set element text (a count of the number of characters).

tval

If a set element text is a number, this attribute gives the value of the number.

uel

Element position in the unique element list.

val

If a set element is a number, this attribute gives the value of the number.

Parameters:
  • container (Container) –

  • name (str) –

  • domain (list[Set | str] | None) –

  • is_singleton (bool) –

  • records (Any | None) –

  • domain_forwarding (bool) –

  • description (str) –

  • uels_on_axes (bool) –

  • is_miro_input (bool) –

  • is_miro_output (bool) –

Methods

addUELs(uels[, dimensions])

Adds UELs to the symbol dimensions.

capitalizeUELs([dimensions])

Will capitalize all UELs in the Container or a subset of specified symbols, can be chained with other *UELs string operations

casefoldUELs([dimensions])

Will casefold all UELs in the Container or a subset of specified symbols, can be chained with other *UELs string operations

countDomainViolations()

Returns the count of how many records contain at least one domain violation

countDuplicateRecords()

Returns the count of how many (case insensitive) duplicate records exist

dropDomainViolations()

drop records from the symbol that contain a domain violation

dropDuplicateRecords([keep])

Drop records with (case insensitive) duplicate domains from the symbol

equals(other[, check_uels, ...])

Used to compare the symbol to another symbol

findDomainViolations()

Get a view of the records DataFrame that contain any domain violations

findDuplicateRecords([keep])

Get a view of the records DataFrame that contain any (case insensitive) duplicate domains – keep argument can take values of "first" (finds all duplicates while keeping the first instance as unique), "last" (finds all duplicates while keeping the last instance as unique), or False (finds all duplicates)

gamsRepr()

Representation of this Set in GAMS language.

generateRecords([density, seed])

Convenience method to set standard pandas.DataFrame formatted records given domain set information.

getDomainViolations()

Returns a list of DomainViolation objects if any (None otherwise)

getSparsity()

Get the sparsity of the symbol w.r.t the cardinality

getStatement()

Statement of the Set definition

getUELs([dimensions, codes, ignore_unused, ...])

Gets UELs from symbol dimensions.

hasDomainViolations()

Returns True if there are domain violations in the records, returns False if not.

hasDuplicateRecords()

Returns True if there are (case insensitive) duplicate records in the symbol, returns False if not

isValid([verbose, force])

Checks if the symbol is in a valid format

lag(n[, type])

Lag operation shifts the values of a Set or Alias by one to the left

lead(n[, type])

Lead shifts the values of a Set or Alias by one to the right

ljustUELs(length[, fill_character, dimensions])

Will left justify all UELs in the symbol or a subset of specified dimensions, can be chained with other *UELs string operations

lowerUELs([dimensions])

Will lowercase all UELs in the parent symbol or a subset of specified dimensions in the parent symbol, can be chain with other *UELs string operations

lstripUELs([dimensions])

Will left strip whitespace from all UELs in the parent set or a subset of specified dimensions in the parent set, can be chain with other *UELs string operations

pivot([index, columns, fill_value])

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

removeUELs([uels, dimensions])

Removes UELs that appear in the symbol dimensions, If uels is None then remove all unused UELs (categories).

renameUELs(uels[, dimensions, allow_merge])

Renames UELs (case-sensitive) that appear in the symbol dimensions.

reorderUELs([uels, dimensions])

Reorders the UELs in the symbol dimensions.

rjustUELs(length[, fill_character, dimensions])

Will right justify all UELs in the symbol or a subset of specified dimensions, can be chained with other *UELs string operations

rstripUELs([dimensions])

Will right strip whitespace from all UELs in the parent set or a subset of specified dimensions in the parent set, can be chain with other *UELs string operations

sameAs(other)

Evaluates to true if this set is identical to the given set or alias, false otherwise.

setRecords(records[, uels_on_axes])

main convenience method to set standard pandas.DataFrame formatted records.

setUELs(uels[, dimensions, rename])

Set the UELs for symbol dimensions.

stripUELs([dimensions])

Will strip whitespace from all UELs in the parent set or a subset of specified dimensions in the parent set, can be chain with other *UELs string operations

titleUELs([dimensions])

Will title (capitalize all individual words) in all UELs in the Container or a subset of specified symbols, can be chained with other *UELs string operations

toList([include_element_text])

Convenience method to return symbol records as a python list

upperUELs([dimensions])

Will uppercase all UELs in the parent symbol or a subset of specified dimensions in the parent symbol, can be chain with other *UELs string operations

property description#

Description of the symbol

property modified#

Flag that identifies if the symbol has been modified

property records#

Records of the Set

Returns:
DataFrame
setRecords(records, uels_on_axes=False)[source]#

main convenience method to set standard pandas.DataFrame formatted records. If uels_on_axes=True setRecords will assume that all domain information is contained in the axes of the pandas object – data will be flattened (if necessary).

Parameters:
recordsAny
uels_on_axesbool, optional
Parameters:
  • records (Any) –

  • uels_on_axes (bool) –

Return type:

None

gamsRepr()[source]#

Representation of this Set in GAMS language.

Returns:
str
Return type:

str

addUELs(uels, dimensions=None)#

Adds UELs to the symbol dimensions. If dimensions is None then add UELs to all dimensions. ** All trailing whitespace is trimmed **

Parameters:
uelsstr | List[str]

List of UELs

dimensionsint | list, optional

Symbol dimensions, by default None

Parameters:
  • uels (str | List[str]) –

  • dimensions (int | list | None) –

Return type:

None

capitalizeUELs(dimensions=None)#

Will capitalize all UELs in the Container or a subset of specified symbols, can be chained with other *UELs string operations

Parameters:
dimensionsint | List[int], optional

Symbols’ dimensions, by default None

Parameters:

dimensions (int | List[int] | None) –

casefoldUELs(dimensions=None)#

Will casefold all UELs in the Container or a subset of specified symbols, can be chained with other *UELs string operations

Parameters:
dimensionsint | List[int], optional

Symbols’ dimensions, by default None

Parameters:

dimensions (int | List[int] | None) –

property container#

Container of the symbol

countDomainViolations()#

Returns the count of how many records contain at least one domain violation

Returns:
int

Count of how many records contain at least one domain violation

Return type:

int

countDuplicateRecords()#

Returns the count of how many (case insensitive) duplicate records exist

Returns:
int

Count of how many (case insensitive) duplicate records exist

Return type:

int

property dimension#

The dimension of symbol

property domain#

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

property domain_forwarding#

A boolean indicating whether domain forwarding is enabled

property domain_labels#

The column headings for the records DataFrame

property domain_names#

String version of domain names

property domain_type#

State of the domain links

dropDomainViolations()#

drop records from the symbol that contain a domain violation

dropDuplicateRecords(keep='first')#

Drop records with (case insensitive) duplicate domains from the symbol

Parameters:
keepstr | bool, optional

keep argument can take values of “first” (keeps the first instance of a duplicate record), “last” (keeps the last instance of a record), or False (drops all duplicates including the first and last), by default “first”

Parameters:

keep (str | bool) –

Return type:

None

equals(other, check_uels=True, check_element_text=True, check_meta_data=True, verbose=False)#

Used to compare the symbol to another symbol

Parameters:
otherSet | Alias

Other Symbol to compare with

check_uelsbool, optional

If True, check both used and unused UELs and confirm same order, otherwise only check used UELs in data and do not check UEL order, by default True

check_element_textbool, optional

If True, check that all set elements have the same descriptive element text, otherwise skip, by default True

check_meta_databool, optional

If True, check that symbol name and description are the same, otherwise skip, by default True

verbosebool, optional

If True, will return an exception from the asserter describing the nature of the difference, by default False

Returns:
bool

True if symbols are equal, False otherwise

Parameters:
  • other (Set | Alias) –

  • check_uels (bool) –

  • check_element_text (bool) –

  • check_meta_data (bool) –

  • verbose (bool) –

Return type:

bool

findDomainViolations()#

Get a view of the records DataFrame that contain any domain violations

Returns:
Optional[pd.DataFrame]

Records DataFrame that contain any domain violations

Return type:

DataFrame | None

findDuplicateRecords(keep='first')#

Get a view of the records DataFrame that contain any (case insensitive) duplicate domains – keep argument can take values of “first” (finds all duplicates while keeping the first instance as unique), “last” (finds all duplicates while keeping the last instance as unique), or False (finds all duplicates)

Parameters:
keepstr | bool, optional

Argument ‘keep’ must be either ‘first’ (returns duplicates except for the first occurrence), ‘last’ (returns duplicates except for the last occurrence), or False (returns all duplicates), by default “first”

Returns:
pd.DataFrame
Parameters:

keep (str | bool) –

Return type:

DataFrame

property first#

Returns 1 for the first set element, otherwise 0.

Returns:
ImplicitSet
generateRecords(density=None, seed=None)#

Convenience method to set standard pandas.DataFrame formatted records given domain set information. Will generate records with the Cartesian product of all domain sets

Parameters:
densityint | float | list, optional

Takes any value on the interval [0,1]. If density is <1 then randomly selected records will be removed. density will accept a list of length dimension – allows users to specify a density per symbol dimension, by default None

seedint, optional

Random number state can be set with seed argument, by default None

Parameters:
  • density (int | float | list | None) –

  • seed (int | None) –

Return type:

None

getDomainViolations()#

Returns a list of DomainViolation objects if any (None otherwise)

Returns:
Optional[DomainViolation]

List of DomainViolation objects if any (None otherwise)

Return type:

List[DomainViolation] | None

getSparsity()#

Get the sparsity of the symbol w.r.t the cardinality

Returns:
float

Sparsity of the symbol w.r.t the cardinality

Return type:

float

getStatement()[source]#

Statement of the Set definition

Returns:
str
Return type:

str

getUELs(dimensions=None, codes=None, ignore_unused=False, unique_only=False)#

Gets UELs from symbol dimensions. If dimensions is None then get UELs from all dimensions (maintains order). The argument codes accepts a list of str UELs and will return the corresponding int; must specify a single dimension if passing codes.

Parameters:
dimensionsint | list, optional

Symbols’ dimensions, by default None

codesint | list, optional

Symbols’ codes, by default None

ignore_unusedbool, optional

Flag to ignore unused UELs, by default False

unique_onlybool, optional

Flag to check only unique UELs, by default False

Returns:
List[str]

Only UELs in the data if ignore_unused=True, otherwise return all UELs.

Parameters:
  • dimensions (int | list | None) –

  • codes (int | list | None) –

  • ignore_unused (bool) –

  • unique_only (bool) –

Return type:

List[str]

hasDomainViolations()#

Returns True if there are domain violations in the records, returns False if not.

Returns:
bool

True if there are domain violations in the records, returns False if not.

Return type:

bool

hasDuplicateRecords()#

Returns True if there are (case insensitive) duplicate records in the symbol, returns False if not

Returns:
bool

True if there are (case insensitive) duplicate records in the symbol, returns False if not

Return type:

bool

isValid(verbose=False, force=False)#

Checks if the symbol is in a valid format

Parameters:
verbosebool, optional

Throw exceptions if verbose=True, by default False

forcebool, optional

Recheck a symbol if force=True, by default False

Returns:
bool

True if a symbol is in valid format, False otherwise (throws exceptions if verbose=True)

Parameters:
  • verbose (bool) –

  • force (bool) –

Return type:

bool

property is_singleton: bool#

Whether a symbol is a singleton set

Returns:
bool

True if the symbol is a singleton set; False otherwise

lag(n, type='linear')#

Lag operation shifts the values of a Set or Alias by one to the left

Parameters:
nint | Symbol | Expression
type‘linear’ or ‘circular’, optional
Returns:
ImplicitSet
Raises:
ValueError

When type is not circular or linear

Parameters:
  • self (Alias | Set) –

  • n (int | Symbol | Expression) –

  • type (Literal['linear', 'circular']) –

Return type:

ImplicitSet

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])
>>> c = gp.Parameter(m, name="c", domain=[t])
>>> a[t] = 1986 + gp.Ord(t)
>>> b[t] = -1
>>> 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]]
>>> c[t] = a[t.lag(1, "circular")]
>>> c.records.values.tolist()
[['y-1987', 1991.0], ['y-1988', 1987.0], ['y-1989', 1988.0], ['y-1990', 1989.0], ['y-1991', 1990.0]]
property last#

Returns 1 for the last set element, otherwise 0.

Returns:
ImplicitSet
lead(n, type='linear')#

Lead shifts the values of a Set or Alias by one to the right

Parameters:
nint | Symbol | Expression
type‘linear’ or ‘circular’, optional
Returns:
ImplicitSet
Raises:
ValueError

When type is not circular or linear

Parameters:
  • self (Set | Alias) –

  • n (int | Symbol | Expression) –

  • type (Literal['linear', 'circular']) –

Return type:

ImplicitSet

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])
>>> d = gp.Parameter(m, name="d", domain=[t])
>>> a[t] = 1986 + gp.Ord(t)
>>> c[t] = -1
>>> c[t.lead(2, "linear")] = a[t]
>>> c.records.values.tolist()
[['y-1987', -1.0], ['y-1988', -1.0], ['y-1989', 1987.0], ['y-1990', 1988.0], ['y-1991', 1989.0]]
>>> d[t.lead(2, "circular")] = a[t]
>>> d.records.values.tolist()
[['y-1987', 1990.0], ['y-1988', 1991.0], ['y-1989', 1987.0], ['y-1990', 1988.0], ['y-1991', 1989.0]]
property len#

Length of the set element name (a count of the number of characters).

Returns:
ImplicitSet
ljustUELs(length, fill_character=None, dimensions=None)#

Will left justify all UELs in the symbol or a subset of specified dimensions, can be chained with other *UELs string operations

Parameters:
lengthint
fill_characterstr, optional

Characters to fill in the empty, by default None

dimensionsint | List[int], optional

Symbols’ dimensions, by default None

Parameters:
  • length (int) –

  • fill_character (str | None) –

  • dimensions (int | List[int] | None) –

lowerUELs(dimensions=None)#

Will lowercase all UELs in the parent symbol or a subset of specified dimensions in the parent symbol, can be chain with other *UELs string operations

Parameters:
dimensionsint | List[int], optional

Symbols’ dimensions, by default None

Parameters:

dimensions (int | List[int] | None) –

lstripUELs(dimensions=None)#

Will left strip whitespace from all UELs in the parent set or a subset of specified dimensions in the parent set, can be chain with other *UELs string operations

Parameters:
dimensionsint | List[int], optional

Symbols’ dimensions, by default None

Parameters:

dimensions (int | List[int] | None) –

property name#

Name of symbol

property number_records#

Number of records

property off#

Element position in the current set minus 1. So .off = .pos - 1

Returns:
ImplicitSet
property ord#

Same as .pos but for ordered sets only.

Returns:
ImplicitSet
pivot(index=None, columns=None, fill_value=None)#

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

Parameters:
indexstr | list, optional

If index is None then it is set to dimensions [0..dimension-1], by default None

columnsstr | list, optional

If columns is None then it is set to the last dimension, by default None

fill_valueint | float | str, optional

Missing values in the pivot will take the value provided by fill_value, by default None

Returns:
DataFrame

Pivoted records dataframe

Parameters:
  • index (str | list | None) –

  • columns (str | list | None) –

  • fill_value (int | float | str | None) –

Return type:

DataFrame

property pos#

Element position in the current set, starting with 1.

Returns:
ImplicitSet
removeUELs(uels=None, dimensions=None)#

Removes UELs that appear in the symbol dimensions, If uels is None then remove all unused UELs (categories). If dimensions is None then operate on all dimensions.

Parameters:
uelsdict | list | str

List of UELs (case-sensitive) that appear in the symbol dimensions

dimensionsint | list, optional

Symbols’ dimensions, by default None

Parameters:
  • uels (dict | list | str | None) –

  • dimensions (int | list | None) –

Return type:

None

renameUELs(uels, dimensions=None, allow_merge=False)#

Renames UELs (case-sensitive) that appear in the symbol dimensions. If dimensions is None then operate on all dimensions of the symbol. ** All trailing whitespace is trimmed **

Parameters:
uelsdict | list | str

List of UELs (case-sensitive) that appear in the symbol dimensions

dimensionsint | list, optional

Symbols’ dimensions, by default None

allow_mergebool, optional

If True, the categorical object will be re-created to offer additional data flexibility. By default False

Parameters:
  • uels (dict | list | str) –

  • dimensions (int | list | None) –

  • allow_merge (bool) –

Return type:

None

reorderUELs(uels=None, dimensions=None)#

Reorders the UELs in the symbol dimensions. If uels is None, reorder UELs to data order and append any unused categories. If dimensions is None then reorder UELs in all dimensions of the symbol.

Parameters:
uelsstr | List[str], optional

List of UELs, by default None

dimensionsint | list, optional

Symbol dimensions, by default None

Parameters:
  • uels (str | List[str] | None) –

  • dimensions (int | list | None) –

Return type:

None

property rev#

Reverse element position in the current set, so the value for the last element is 0, the value for the penultimate is 1, etc.

Returns:
ImplicitSet
rjustUELs(length, fill_character=None, dimensions=None)#

Will right justify all UELs in the symbol or a subset of specified dimensions, can be chained with other *UELs string operations

Parameters:
lengthint
fill_characterstr, optional

Characters to fill in the empty, by default None

dimensionsint | List[int], optional

Symbols’ dimensions, by default None

Parameters:
  • length (int) –

  • fill_character (str | None) –

  • dimensions (int | List[int] | None) –

rstripUELs(dimensions=None)#

Will right strip whitespace from all UELs in the parent set or a subset of specified dimensions in the parent set, can be chain with other *UELs string operations

Parameters:
dimensionsint | List[int], optional

Symbols’ dimensions, by default None

Parameters:

dimensions (int | List[int] | None) –

sameAs(other)#

Evaluates to true if this set is identical to the given set or alias, false otherwise.

Parameters:
otherSet | Alias
Returns:
Expression
Parameters:
Return type:

Expression

setUELs(uels, dimensions=None, rename=False)#

Set the UELs for symbol dimensions. If dimensions is None then set UELs for all dimensions. ** All trailing whitespace is trimmed **

Parameters:
uelsstr | List[str]

List of UELs (case-sensitive) that appear in the symbol dimensions

dimensionsint | list, optional

Symbols’ dimensions, by default None

renamebool, optional

If True, the old UEL names will be renamed with the new UEL names. By default False

Parameters:
  • uels (str | List[str]) –

  • dimensions (int | list | None) –

  • rename (bool) –

Return type:

None

stripUELs(dimensions=None)#

Will strip whitespace from all UELs in the parent set or a subset of specified dimensions in the parent set, can be chain with other *UELs string operations

Parameters:
dimensionsint | List[int], optional

Symbols’ dimensions, by default None

Parameters:

dimensions (int | List[int] | None) –

property summary: dict#

Returns a dict of only the metadata

Returns:
dict

Outputs a dict of only the metadata

titleUELs(dimensions=None)#

Will title (capitalize all individual words) in all UELs in the Container or a subset of specified symbols, can be chained with other *UELs string operations

Parameters:
dimensionsint | List[int], optional

Symbols’ dimensions, by default None

Parameters:

dimensions (int | List[int] | None) –

property tlen#

Length of the set element text (a count of the number of characters).

Returns:
ImplicitSet
toList(include_element_text=False)[source]#

Convenience method to return symbol records as a python list

Parameters:
include_element_textbool, optional

If True, include the element text as tuples (record, element text). If False, return a list of records only.

Returns:
list | None

A list containing the records of the symbol, None if no record was assigned

Return type:

List[str | tuple] | None

Examples

>>> m = gt.Container()
>>> i = gt.Set(m, "i", records=["new-york", "chicago", "topeka"])
>>> print(i.toList())
['new-york', 'chicago', 'topeka']
property tval#

If a set element text is a number, this attribute gives the value of the number. For extended range arithmetic symbols, the symbols are reproduced. If a set element text is a string that is not a number, then this attribute is not defined and trying to use it results in an error.

Returns:
ImplicitSet
property uel#

Element position in the unique element list.

Returns:
ImplicitSet
upperUELs(dimensions=None)#

Will uppercase all UELs in the parent symbol or a subset of specified dimensions in the parent symbol, can be chain with other *UELs string operations

Parameters:
dimensionsint | List[int], optional

Symbols’ dimensions, by default None

Parameters:

dimensions (int | List[int] | None) –

property val#

If a set element is a number, this attribute gives the value of the number. For extended range arithmetic symbols, the symbols are reproduced. If a set element is a string that is not a number, then this attribute is not defined and trying to use it results in an error.

Returns:
ImplicitSet