If#
- class gamspy.If(condition: ConditionType, container: Container | None = None)[source]#
Bases:
objectA context manager to conditionally execute a group of statements.
The If class maps to the GAMS if statement. It allows you to branch conditionally around a group of execution statements. It can be used within loops as well as on the outermost level. On the outermost level, the statements of the block are executed when the block is closed.
- Parameters:
- conditionConditionType
The logical condition that must be satisfied to execute the nested statements.
- containerContainer, optional
The container to add the statements to. Required only if the container cannot be deduced from the condition.
Examples
1. Skipping iterations conditionally:
>>> import gamspy as gp >>> m = gp.Container() >>> i = gp.Set(m, records=[f"i{idx}" for idx in range(1, 11)]) >>> cnt = gp.Parameter(m, records=0) >>> with gp.Loop(i) as loop: ... with gp.If(gp.math.mod(gp.Ord(i), 2) == 0): ... loop.Continue ... cnt[...] += 1
2. Breaking a loop based on a condition:
>>> with gp.Loop(i) as loop: ... with gp.If(i.sameAs("i6")): ... loop.Break ... cnt[...] += 1
3. Branching on the outermost level:
>>> x = gp.Parameter(m, records=15) >>> with gp.If(x > 10): ... x[...] = 10 >>> with gp.Else(): ... x[...] = 0 >>> x.toValue() np.float64(10.0)
4. Providing the container explicitly:
>>> with gp.If(gp.Number(1) == 1, container=m): ... cnt[...] = 1