5.1. クラス¶
コンストラクタが公開されているクラスは,すべての引数をキーワード引数として呼び出さなければなりません. 複数の引数を持たせる場合,キーワード引数の順序は任意です.
インスタンス間に定義されている演算については 演算 を参照してください.
5.1.1. 集合¶
- class pysimple.Set(name: str | None = None, value: Iterable | None = None, dim: int | None = None)¶
ベースクラス:
collections.abc.Set
[tuple
[int
|float
|str
, ...]],pysimple.util.Named
集合を表すクラスです. Set はすべて順序を持っています.オブジェクトの生成後は要素を変更できません.
- パラメータ
- 例外
TypeError -- {} keyword argument 'dim' must be positive integer ({} given)
TypeError -- {} object is not iterable
ValueError -- dimension mismatch
ValueError -- empty data: {}
ValueError -- illegal type data: {}
サンプル
>>> Set(value=[1,2], name='I') Set(name='I', value=[1, 2]) >>> Set(value=range(3)) Set(value=[0, 1, 2]) >>> Set(value='XYZ') Set(value=['X', 'Y', 'Z']) >>> Set(value=[(1,3), (1,4), (2,3)]) Set(dim=2, value=[(1, 3), (1, 4), (2, 3)]) >>> Set() Set() >>> Set(dim=2) Set(dim=2)
- __call__(*slc: int) Set ¶
各次元を射影した集合を返します.
- パラメータ
*slc (non-negative integers) -- 射影する次元の列です(0 始まり).1 つ以上必要です.
- 戻り値の型
- 例外
TypeError -- slice of {} takes at least 1 argument (0 given)
TypeError -- slice of {} indices must be non-negative integers
IndexError -- slice index out of range
サンプル
>>> I = Set(value=[(1,3), (1,4), (2,3)], name='I') >>> I(0) Set(name='I(0)', value=[1, 2]) >>> I(1) Set(name='I(1)', value=[3, 4]) >>> I(2) IndexError: slice index out of range >>> I(1, 0, 1) Set(name='I(1,0,1)', dim=3, value=[(3, 1, 3), (4, 1, 4), (3, 2, 3)]) >>> I() TypeError: slice of 'I' takes at least 1 argument (0 given)
- __contains__(key: DType | Key) bool ¶
key が要素に含まれているかを返します.
注釈
Element のうち,集合に含まれる部分を表現したい場合は比較演算子を用いてください.
参考
pysimple.__lt__
,pysimple.__gt__
サンプル
>>> I = Set(value=[1,2], name='I') >>> 0 in I False >>> 1 in I True >>> i = Element(value=[1,2], name='i') >>> i in I TypeError: unsupported operand type(s) for 'Element' in 'Set', use 'i < I' instead of 'i in I' >>> J = Set(value=[(1,3), (1,4), (2,3)], name='J') >>> (2,3) in J True >>> (2,4) in J False
- __getitem__(key: int | ELEMENT | slice) DType | Key | Set | Parameter ¶
Set の key 番目の要素を返します. key には負数やスライスも指定できます.
- パラメータ
key (int or
ELEMENT
or slice) --- 戻り値
key が int の場合は Set の要素を,
ELEMENT
の場合は Parameter を,slice の場合は Set を返します.- 戻り値の型
- 例外
IndexError -- Set index out of range
TypeError -- Set indices must be integers, not {}
TypeError -- cannot apply {} to multidimensional Set
サンプル
>>> S = Set(value='XY', name='S') >>> S[-3] IndexError: Set index out of range >>> S[-2] 'X' >>> S[-1] 'Y' >>> S[0] 'X' >>> S[1] 'Y' >>> S[2] IndexError: Set index out of range >>> S['foo'] TypeError: Set indices must be integers, not str >>> i = Element(value=[-2, 1], name='i') >>> S[i] S[i][-2]='X' S[i][1]='Y' >>> I = Set(value=range(5), name='I') >>> I Set(name='I', value=[0, 1, 2, 3, 4]) >>> I[2:] Set(name='I[2:]', value=[2, 3, 4])
- __iter__() collections.abc.Iterator[Key] ¶
iter(self) を返します.
- 戻り値の型
Iterator[
Key
]
サンプル
>>> I = Set(value=[1,2]) >>> for i in I: ... print(i) ... (1,) (2,) >>> IJ = Set(value=[(1,3), (1,4), (2,3)]) >>> for ij in IJ: ... print(ij) ... (1, 3) (1, 4) (2, 3)
注釈
次元に関わらず,値は常にタプルとして返されることに注意してください.
- property dim¶
集合の次元です.
- index(key: DType | Key | ELEMENT) int | Parameter ¶
key が Set の何番目の要素であるかを返します.
- パラメータ
- 戻り値
key が
DType
またはKey
の場合は int を,ELEMENT
の場合は Parameter を返します.- 戻り値の型
- 例外
ValueError -- {} is not in {}
サンプル
>>> S = Set(value='XY', name='S') >>> S.index('X') 0 >>> S.index('Y') 1 >>> S.index('Z') ValueError: Z is not in Set >>> s = Element(set=S, name='s') >>> S.index(s) S.index(s)['X']=0 S.index(s)['Y']=1 >>> t = Element(value='YZ', name='t') >>> S.index(t) ValueError: Z is not in Set
- next(key: DType | Key | ELEMENT) DType | Key | Parameter ¶
Set における key の次の要素を返します.
- パラメータ
- 戻り値
key が
DType
またはKey
の場合は Set の要素を,ELEMENT
の場合は Parameter を返します.- 戻り値の型
- 例外
KeyError --
IndexError -- Set index out of range
TypeError -- cannot apply {} to multidimensional Set
サンプル
>>> XYZ = Set(value='XYZ', name='XYZ') >>> XYZ.next('X') 'Y' >>> XYZ.next('Y') 'Z' >>> XYZ.next('Z') IndexError: Set index out of range >>> XYZ.next('W') KeyError: 'W' >>> xy = Element(value='XY', name='xy') >>> XYZ.next(xy) XYZ.next(xy)['X']='Y' XYZ.next(xy)['Y']='Z' >>> yz = Element(value='YZ', name='yz') >>> XYZ.next(yz) IndexError: Set index out of range
- prev(key: DType | Key | ELEMENT) DType | Key | Parameter ¶
Set における key の前の要素を返します.
- パラメータ
- 戻り値
key が
DType
またはKey
の場合は Set の要素を,ELEMENT
の場合は Parameter を返します.- 戻り値の型
- 例外
KeyError --
IndexError -- Set index out of range
TypeError -- cannot apply {} to multidimensional Set
サンプル
>>> XYZ = Set(value='XYZ', name='XYZ') >>> XYZ.prev('Z') 'Y' >>> XYZ.prev('Y') 'X' >>> XYZ.prev('X') IndexError: Set index out of range >>> XYZ.prev('W') KeyError: 'W' >>> yz = Element(value='YZ', name='yz') >>> XYZ.prev(yz) XYZ.prev(yz)['Y']='X' XYZ.prev(yz)['Z']='Y' >>> xy = Element(value='YXY', name='xy') >>> XYZ.prev(xy) IndexError: Set index out of range
バージョン 1.1.0 で追加: __getitem__()
に slice が使用可能になりました.
5.1.2. 添字¶
- class pysimple.Element(name: str | None = None, set: Set | None = None, value: Iterable[DType | Key] | None = None, dim: int | None = None)¶
添字を表すクラスです.
集合と添字を対応付けます.集合の要素を直接与えることもできます. set キーワードと value キーワードのいずれか一方を指定する必要があります. 要素を確認する場合は set 属性を参照してください.
- パラメータ
- 例外
TypeError -- Element can only take either keyword argument 'set' or 'value' (no or both keyword arguments given)
サンプル
>>> I = Set(value=[1,2], name='I') >>> i = Element(set=I, name='i') >>> i.set Set(name='I', value=[1, 2]) >>> j = Element(value=[1,2], name='j') >>> j.set Set(name='j.set', value=[1, 2])
- __call__(*slc: int) ElementSlice ¶
各次元を射影した添字を返します.
- パラメータ
*slc (non-negative integers) -- 射影する次元の列です(0 始まり).1 つ以上必要です.
- 戻り値の型
- 例外
TypeError -- slice of {} takes at least 1 argument (0 given)
IndexError -- slice index out of range
サンプル
>>> i = Element(value=[(1,3), (1,4), (2,3)], name='i') >>> i(0).set Set(name='i.set(0)', value=[1, 2]) >>> i(1).set Set(name='i.set(1)', value=[3, 4]) >>> i(2).set IndexError: slice index out of range >>> i(1,0,1).set Set(name='i.set(1,0,1)', dim=3, value=[(3, 1, 3), (4, 1, 4), (3, 2, 3)]) >>> i() TypeError: slice of 'Element' takes at least 1 argument (0 given)
- property set: pysimple.element.Set¶
対応する集合を表す属性です.
- class pysimple.element.ElementSlice¶
Element のスライスに対して生成されるクラスです.
ElementSlice クラスは
__call__()
がないこと以外は,ほぼElement
と同じです. ElementSlice クラスのコンストラクタは公開されません.
- class pysimple.condition.Cond¶
Condition 関数などの条件付けによって生成されるクラスです. Cond オブジェクトは添字のように使用することができます.
サンプル
>>> ij = Element(value=[(1,3), (1,4), (2,3)], name='ij') >>> ij(1)!=4 (ij(1)!=4)[ij(1)] in [3] >>> Condition(ij, ij(1)!=4) (ij, (ij(1)!=4))[ij] in [(1, 3), (2, 3)] >>> (ij(0)!=2) & (ij(1)!=4) ((ij(0)!=2)&(ij(1)!=4))[ij(0),ij(1)] in [(1, 3)] >>> i = Element(value=[1,2,3,4], name='i') >>> i < [2,4,6,8] (i<[2, 4, 6, 8])[i] in [2, 4]
Cond クラスのコンストラクタは公開されません.
- class pysimple.index.Index¶
添字つきオブジェクトの添字情報を保持するクラスです.
- __iter__() collections.abc.Iterator[pysimple.index.IDXT] ¶
5.1.3. 定数¶
- class pysimple.Parameter(name: str = None, index: Set | ELEMENT | tuple[Set | ELEMENT, ...] | Index | None = None, value: DType | dict = 0)¶
定数を表すクラスです.
- パラメータ
- 例外
KeyError -- extra key {} in value of Parameter
サンプル
>>> i = Element(value=[1,2], name='i') >>> a = Parameter(index=i, name='a') >>> a a[1]=0 a[2]=0 >>> b = Parameter(index=i, value=1, name='b') >>> b b[1]=1 b[2]=1 >>> c = Parameter(index=i, value={2: 2}, name='c') >>> c c[1]=0 c[2]=2 >>> j = Element(value=[3,4], name='j') >>> d = Parameter(index=(i,j), name='d') >>> d d[1,3]=0 d[1,4]=0 d[2,3]=0 d[2,4]=0 >>> e = Parameter(value=1, name='e') >>> e e=1
- __bool__() bool ¶
真偽値 bool(self) を返します. index なしの場合,value の真偽値を返します. index ありの場合,TypeError が送出されます.
サンプル
>>> a = Parameter(value=3) >>> bool(a) True >>> b = Parameter() >>> bool(b) False >>> i = Element(value=[1,2]) >>> c = Parameter(index=i) >>> bool(c) TypeError: unsupported cast type(s) for bool: 'Parameter'
- __float__() float ¶
浮動小数への変換 float(self) を返します. index なしの場合,value の浮動小数値を返します. index ありの場合,TypeError が送出されます.
サンプル
>>> a = Parameter(value=3) >>> float(a) 3.0 >>> b = Parameter() >>> float(b) 0.0 >>> i = Element(value=[1,2]) >>> c = Parameter(index=i) >>> float(c) TypeError: unsupported cast type(s) for float: 'Parameter'
- __floor__() None ¶
Floor(obj: ObjPrm) -> Num | Parameter
- パラメータ
obj (
ObjPrm
) --- 戻り値
obj が
DType
の場合は math.floor (obj) の結果を, それ以外の場合は math.floor を各要素に適用した Parameter を返す.- 戻り値の型
Num
or Parameter
- __format__(spec: str) str ¶
整形した文字列表現 format(self, spec) を返します. index なしの場合,value を spec の書式に整形した文字列を返します. index ありの場合,TypeError が送出されます.
サンプル
>>> a = Parameter(value=3.14, name='a') >>> x = Variable(init=2.72, name='x') >>> f'{a} {a:.1f} {x.val} {x.val:.1f}' 'a=3.14 a=3.1 x.val=2.72 x.val=2.7' >>> format(a, '.1f'), format(x.val, '.1f') ('a=3.1', 'x.val=2.7') >>> i = Element(value=[1, 2], name='i') >>> b = Parameter(index=i, value=3.14, name='b') >>> f'{b[i]}' TypeError: unsupported cast type(s) for format: 'Parameter'
- __getitem__(key: ObjPrm | tuple[ObjPrm, ...] | Index) DType | Parameter ¶
key に対応した添字の Parameter を返します.
- パラメータ
key (
ObjPrm
or tuple of them or Index) --- 戻り値
- 戻り値の型
- 例外
サンプル
>>> i = Element(value=[1, 2], name='i') >>> j = Element(value=[3, 4], name='j') >>> a = Parameter(index=(i,j), name='a'); a[i,j] = i+j >>> a[i,j] a[1,3]=4 a[1,4]=5 a[2,3]=5 a[2,4]=6 >>> a[i,3] a[1,3]=4 a[2,3]=5 >>> a[2,3] 5 >>> ij = Element(value=[(1,3), (1,4), (2,3)], name='ij') >>> a[ij] a[1,3]=4 a[1,4]=5 a[2,3]=5 >>> a[1,5] KeyError: 'a[1,5]' >>> b = Parameter(index=j, value={3: 4, 4: 3}, name='b') >>> a[i, b[j]] a[i,b[j]][1,3]=5 a[i,b[j]][1,4]=4 a[i,b[j]][2,3]=6 a[i,b[j]][2,4]=5
- __int__() int ¶
整数への変換 int(self) を返します. index なしの場合,value の整数値を返します. index ありの場合,TypeError が送出されます.
サンプル
>>> a = Parameter(value=3) >>> int(a) 3 >>> b = Parameter() >>> int(b) 0 >>> i = Element(value=[1,2]) >>> c = Parameter(index=i) >>> int(c) TypeError: unsupported cast type(s) for int: 'Parameter'
- __iter__() collections.abc.Iterator[Key] ¶
iter(self) を返します.
- 戻り値の型
Iterator[
Key
]
サンプル
>>> i = Element(value=[1,2]) >>> a = Parameter(index=i) >>> for _i in a: ... print(_i) ... (1,) (2,) >>> ij = Element(value=[(1,3), (1,4), (2,3)]) >>> b = Parameter(index=ij) >>> for _ij in b: ... print(_ij) ... (1, 3) (1, 4) (2, 3)
注釈
次元に関わらず,値は常にタプルとして返されることに注意してください.
- __round__(ndigits: int | None = None) Parameter ¶
値の小数部を ndigits 桁に丸めた値を返します.ndigits が省略された場合,最も近い整数を返します.
サンプル
>>> i = Element(value=[1, 2, 3], name='i') >>> a = Parameter(index=i, value={1: 1, 2: 2.0000, 3: 3.1415}, name='a') >>> a a[1]=1 a[2]=2.0 a[3]=3.1415 >>> round(a[i]) round(a[i])[1]=1 round(a[i])[2]=2 round(a[i])[3]=3 >>> round(a[i], 0) round(a[i], 0)[1]=1 round(a[i], 0)[2]=2.0 round(a[i], 0)[3]=3.0 >>> round(a[i], 2) round(a[i], 2)[1]=1 round(a[i], 2)[2]=2.0 round(a[i], 2)[3]=3.14
- __setitem__(key: ObjPrm | tuple[ObjPrm, ...] | Index, value: ObjPrm) None ¶
key に対応した値を変更します.
サンプル
>>> i = Element(value=[1,2], name='i') >>> j = Element(value=[3,4], name='j') >>> a = Parameter(index=(i,j), name='a') >>> a[i,j] = 1 >>> a a[1,3]=1 a[1,4]=1 a[2,3]=1 a[2,4]=1 >>> a[i,3] = i*10 >>> a a[1,3]=10 a[1,4]=1 a[2,3]=20 a[2,4]=1 >>> a[2,3] = 100 >>> a a[1,3]=10 a[1,4]=1 a[2,3]=100 a[2,4]=1 >>> ij = Element(value=[(1,3), (1,4), (2,3)], name='ij') >>> a[ij] = 0 >>> a a[1,3]=0 a[1,4]=0 a[2,3]=0 a[2,4]=1 >>> a[1,5] = 1 KeyError: 'a[1,5]' >>> b = Parameter(index=j, value={3: 4, 4: 3}, name='b') >>> a[i, b[j]] = i+j >>> a a[1,3]=5 a[1,4]=4 a[2,3]=6 a[2,4]=5
- get(*key: ObjPrm) DType | Parameter ¶
key に対応した添字の Parameter を返します. __getitem__ と異なり key に対応するものがない場合には KeyError が 投げられず 0 となります.key の次元が異なる場合はその限りではありません. デフォルト値の指定はできず常に 0 となります.
サンプル
>>> i = Element(value=[1, 2], name='i') >>> j = Element(value=[3, 4], name='j') >>> a = Parameter(index=(i,j), name='a'); a[i,j] = i+j >>> a.get(i,j) a.get(i,j)[1,3]=4 a.get(i,j)[1,4]=5 a.get(i,j)[2,3]=5 a.get(i,j)[2,4]=6 >>> a.get(i,4) a.get(i,4)[1,4]=5 a.get(i,4)[2,4]=6 >>> a.get(i,5) a.get(i,5)[1,5]=0 a.get(i,5)[2,5]=0 >>> a.get(i+1,j) a.get((i+1)[i],j)[1,3]=5 a.get((i+1)[i],j)[1,4]=6 a.get((i+1)[i],j)[2,3]=0 a.get((i+1)[i],j)[2,4]=0
- property index: pysimple.index.Index¶
添字
- items() dict_items[Key, VT] ¶
キーと値ペアの列を返します.
- keys() dict_keys[Key, VT] ¶
キーの列を返します.
- values() dict_values[Key, VT] ¶
値の列を返します.
バージョン 1.3.0 で追加: __round__()
が使用可能になりました.
バージョン 1.5.0 で追加: get()
が添字をサポートするようになりました.
5.1.4. 変数,式¶
- class pysimple.Variable(name: str = None, index: Set | ELEMENT | tuple[Set | ELEMENT, ...] | Index | None = None, type: Literal[float, int, bin] | None = float, init: float | dict | None = 0, lb: float | dict | None = float('-inf'), ub: float | dict | None = float('inf'))¶
ベースクラス:
pysimple.util.Final
,collections.abc.Collection
[tuple
[int
|float
|str
, ...]],pysimple.util.Named
変数を表すクラスです.
- パラメータ
name (str) -- 省略した場合は自動で与えられます.オブジェクトの生成後に変更できます.
index (Set or
ELEMENT
or tuple of them or Index) -- Variable の添字. 省略した場合,添字なしの変数となります.type (float or int or bin) -- 組み込み関数の float, int, bin を指定します. それぞれ連続変数,整数変数,0-1 整数変数を意味します. bin が指定された場合,自動で lb=0, ub=1 が設定されます. オブジェクトの生成後に変更できます.
init (float or dict) -- Variable の初期値. float の場合,すべての要素に対して同じ値が適用されます. dict の場合,指定された要素の値が適用されます. オブジェクトの生成後に変更できます.
- 例外
TypeError -- 'type' keyword only takes built-in function 'float', 'int' or 'bin'
SimpleError -- infeasible bound of variable {} ( defined infeasible bound [{} <= * <= {}] )
サンプル
>>> i = Element(value=[1,2], name='i') >>> x = Variable(index=i, name='x') >>> x x: x[1] x[2] >>> x.init x[1].init=0 x[2].init=0 >>> x.val x[1].val=0 x[2].val=0 >>> y = Variable(index=i, init=1, name='y') >>> y.val y[1].val=1 y[2].val=1 >>> z = Variable(index=i, init={2: 2}, name='z') >>> z.val z[1].val=0 z[2].val=2 >>> j = Element(value=[3,4], name='j') >>> w = Variable(index=(i,j), name='w') >>> w.val w[1,3].val=0 w[1,4].val=0 w[2,3].val=0 w[2,4].val=0 >>> u = Variable(name='u') >>> u.val u.val=0
参考
pysimple.Variable.type
,pysimple.Variable.init
,pysimple.Variable.val
,pysimple.Variable.lb
,pysimple.Variable.ub
- __getitem__(key: ObjPrm | tuple[ObjPrm, ...] | Index) Variable ¶
key に対応した添字の Variable を返します.
サンプル
>>> i = Element(value=[1, 2], name='i') >>> j = Element(value=[3, 4], name='j') >>> x = Variable(index=(i,j), name='x'); x[i,j] = i+j >>> x[i,j].val x[1,3].val=4 x[1,4].val=5 x[2,3].val=5 x[2,4].val=6 >>> x[i,3].val x[1,3].val=4 x[2,3].val=5 >>> x[2,3].val 5 >>> ij = Element(value=[(1,3), (1,4), (2,3)], name='ij') >>> x[ij].val x[1,3].val=4 x[1,4].val=5 x[2,3].val=5 >>> x[1,5] KeyError: 'x[1,5]' >>> b = Parameter(index=j, value={3: 4, 4: 3}, name='b') >>> x[i, b[j]].val x[i,b[j]][1,3].val=5 x[i,b[j]][1,4].val=4 x[i,b[j]][2,3].val=6 x[i,b[j]][2,4].val=5
- __iter__() collections.abc.Iterator[Key] ¶
iter(self) を返します.
- 戻り値の型
Iterator[
Key
]
サンプル
>>> i = Element(value=[1,2]) >>> x = Variable(index=i) >>> for _i in x: ... print(_i) ... (1,) (2,) >>> ij = Element(value=[(1,3), (1,4), (2,3)]) >>> y = Variable(index=ij) >>> for _ij in y: ... print(_ij) ... (1, 3) (1, 4) (2, 3)
注釈
次元に関わらず,値は常にタプルとして返されることに注意してください.
- __setitem__(key: ObjPrm | tuple[ObjPrm, ...] | Index, value: ObjPrm) None ¶
key に対応した値を変更します.値は val で確認できます.
サンプル
>>> i = Element(value=[1,2], name='i') >>> j = Element(value=[3,4], name='j') >>> x = Variable(index=(i,j), name='x') >>> x[i,j] = 1 >>> x.val x[1,3].val=1 x[1,4].val=1 x[2,3].val=1 x[2,4].val=1 >>> x[i,3] = i*10 >>> x.val x[1,3].val=10 x[1,4].val=1 x[2,3].val=20 x[2,4].val=1 >>> x[2,3] = 100 >>> x.val x[1,3].val=10 x[1,4].val=1 x[2,3].val=100 x[2,4].val=1 >>> ij = Element(value=[(1,3), (1,4), (2,3)], name='ij') >>> x[ij] = 0 >>> x.val x[1,3].val=0 x[1,4].val=0 x[2,3].val=0 x[2,4].val=1 >>> x[1,5] = 1 KeyError: 'x[1,5]' >>> b = Parameter(index=j, value={3: 4, 4: 3}, name='b') >>> x[i, b[j]] = i+j >>> x.val x[1,3].val=5 x[1,4].val=4 x[2,3].val=6 x[2,4].val=5
- property dual: pysimple.table.Table | None¶
変数の双対変数値を表す属性です. 値は求解時に更新されます. オブジェクト生成時の値は None です.
- fix() None ¶
変数の値を現在値 val に固定します. 下限値 lb と上限値 ub を現在値 val に設定するのと同じ効果です. lb/ub と値が矛盾する場合は求解時に SimpleError が投げられます.
- get(*key: ObjPrm) Variable ¶
key に対応した添字の Variable を返します. __getitem__ と異なり key に対応するものがない場合には KeyError が 投げられず 0 となります.key の次元が異なる場合はその限りではありません. デフォルト値の指定はできず常に 0 となります.
サンプル
>>> i = Element(value=[1, 2], name='i') >>> j = Element(value=[3, 4], name='j') >>> x = Variable(index=(i,j), name='x'); x[i,j] = i+j >>> x.get(i,j) x.get(i,j): x.get(i,j)[1,3] x.get(i,j)[1,4] x.get(i,j)[2,3] x.get(i,j)[2,4] >>> x.get(i,4) x.get(i,4): x.get(i,4)[1,4] x.get(i,4)[2,4] >>> x.get(i,5) x.get(i,5): 0 0 >>> x.get(i+1,j) x.get((i+1)[i],j): x.get((i+1)[i],j)[1,3] x.get((i+1)[i],j)[1,4] 0 0
- property group: tuple[int, ...] | None¶
変数の添字グループ情報を表す属性です. グループは添字の次元の列で指定します. 解法が wls である場合,添字グループは wls における割当ラベルとして解釈され,解の探索に利用されます. 具体的には,アルゴリズム内で各変数が「指定された次元の列」と「指定されなかった次元の列」を割り当てる (関連づける)構造をもつと解釈されます. 例えば,下記サンプルコードの変数 x が「i を (j, k) に割り当てるなら 1,そうでないなら 0」を意味する 変数である場合,x.group = 0 の設定により探索性能の向上が見込めます. 本属性は解法 wls でのみ有効です.
サンプル
>>> i = Element(value=[1,2], name='i') >>> j = Element(value=[3,4], name='j') >>> k = Element(value=[5,6], name='k') >>> x = BinaryVariable(index=(i,j,k), name='x') >>> x.group = 0 >>> x.group (0,) >>> x.group = 0, 2 >>> x.group (0, 2)
- property index: pysimple.index.Index¶
添字
- property init: pysimple.table.Table¶
変数の初期値を表す属性です. 値は初期化,値の代入,求解時に更新されます. 求解時には .val 属性の値からコピーされます.
サンプル
>>> p = Problem(silent=True) >>> i = Element(value=[1,2]) >>> x = Variable(index=i, init=2, lb=1, name='x') >>> x.init x[1].init=2 x[2].init=2 >>> x[2] = 3 >>> x.init x[1].init=2 x[2].init=3 >>> p += Sum(x[i]) >>> p.solve() <NuoptStatus.OPTIMAL: 1> >>> x.init x[1].init=2 x[2].init=3 >>> p.solve() <NuoptStatus.OPTIMAL: 1> >>> x.init x[1].init=1.0000000002083331 x[2].init=1.0000000002083331
- property lb: pysimple.table.Table¶
変数の下限値を表す属性です. 値は初期化時にのみ更新されます. 初期化時に type=bin を指定すると lb=0 が設定されます.
サンプル
>>> i = Element(value=[1,2], name='i') >>> x = Variable(index=i, name='x') >>> x.lb x[1].lb=-inf x[2].lb=-inf >>> y = Variable(index=i, lb=0, name='y') >>> y.lb y[1].lb=0 y[2].lb=0 >>> z = BinaryVariable(index=i, name='z') >>> z.lb z[1].lb=0 z[2].lb=0
- property type: Literal[float | int | bin]¶
変数の種類を表す属性です. 値は代入により変更できます. 組み込み関数の float, int, bin を指定します. それぞれ連続変数,整数変数,0-1 整数変数を意味します.
サンプル
>>> x = Variable() >>> x.type <class 'float'> >>> x.type = int >>> x.type <class 'int'> >>> x.type = bin >>> x.type <built-in function bin> >>> x.type = bool TypeError: 'type' keyword only takes built-in function 'float', 'int' or 'bin' >>> y1 = Variable(type=int) >>> y1.type <class 'int'> >>> y2 = IntegerVariable() >>> y2.type <class 'int'>
- property ub: pysimple.table.Table¶
変数の上限値を表す属性です. 値は初期化時にのみ更新されます. 初期化時に type=bin を指定すると ub=1 が設定されます.
サンプル
>>> i = Element(value=[1,2], name='i') >>> x = Variable(index=i, name='x') >>> x.ub x[1].ub=inf x[2].ub=inf >>> y = Variable(index=i, ub=1, name='y') >>> y.ub y[1].ub=1 y[2].ub=1 >>> z = BinaryVariable(index=i, name='z') >>> z.ub z[1].ub=1 z[2].ub=1
- property val: pysimple.table.Table¶
変数の現在値を表す属性です. 値は初期化,値の代入,求解時に更新されます.
サンプル
>>> p = Problem(silent=True) >>> i = Element(value=[1,2]) >>> x = Variable(index=i, init=2, lb=1, name='x') >>> x.val x[1].val=2 x[2].val=2 >>> x[2].val 2 >>> x[2] = 3 >>> x.val x[1].val=2 x[2].val=3 >>> p += Sum(x[i]) >>> p.solve() <NuoptStatus.OPTIMAL: 1> >>> x.val x[1].val=1.0000000002083331 x[2].val=1.0000000002083331
バージョン 1.5.0 で追加: get()
が追加されました.
- class pysimple.IntegerVariable(name: str = None, index: Set | ELEMENT | tuple[Set | ELEMENT, ...] | Index | None = None, type: Literal[float, int, bin] | None = float, init: float | dict | None = 0, lb: float | dict | None = float('-inf'), ub: float | dict | None = float('inf'))¶
ベースクラス:
pysimple.expression.Variable
整数変数を表すクラスです.Variable(type=int, ..) と等価です.type キーワードはありません.
- パラメータ
name (str) -- 省略した場合は自動で与えられます.オブジェクトの生成後に変更できます.
index (Set or
ELEMENT
or tuple of them or Index) -- Variable の添字. 省略した場合,添字なしの変数となります.type (float or int or bin) -- 組み込み関数の float, int, bin を指定します. それぞれ連続変数,整数変数,0-1 整数変数を意味します. bin が指定された場合,自動で lb=0, ub=1 が設定されます. オブジェクトの生成後に変更できます.
init (float or dict) -- Variable の初期値. float の場合,すべての要素に対して同じ値が適用されます. dict の場合,指定された要素の値が適用されます. オブジェクトの生成後に変更できます.
- 例外
TypeError -- 'type' keyword only takes built-in function 'float', 'int' or 'bin'
SimpleError -- infeasible bound of variable {} ( defined infeasible bound [{} <= * <= {}] )
サンプル
>>> i = Element(value=[1,2], name='i') >>> x = Variable(index=i, name='x') >>> x x: x[1] x[2] >>> x.init x[1].init=0 x[2].init=0 >>> x.val x[1].val=0 x[2].val=0 >>> y = Variable(index=i, init=1, name='y') >>> y.val y[1].val=1 y[2].val=1 >>> z = Variable(index=i, init={2: 2}, name='z') >>> z.val z[1].val=0 z[2].val=2 >>> j = Element(value=[3,4], name='j') >>> w = Variable(index=(i,j), name='w') >>> w.val w[1,3].val=0 w[1,4].val=0 w[2,3].val=0 w[2,4].val=0 >>> u = Variable(name='u') >>> u.val u.val=0
- class pysimple.BinaryVariable(name: str = None, index: Set | ELEMENT | tuple[Set | ELEMENT, ...] | Index | None = None, type: Literal[float, int, bin] | None = float, init: float | dict | None = 0, lb: float | dict | None = float('-inf'), ub: float | dict | None = float('inf'))¶
ベースクラス:
pysimple.expression.Variable
0-1 整数変数を表すクラスです.Variable(type=bin, ..) と等価です.type キーワードはありません.
- パラメータ
name (str) -- 省略した場合は自動で与えられます.オブジェクトの生成後に変更できます.
index (Set or
ELEMENT
or tuple of them or Index) -- Variable の添字. 省略した場合,添字なしの変数となります.type (float or int or bin) -- 組み込み関数の float, int, bin を指定します. それぞれ連続変数,整数変数,0-1 整数変数を意味します. bin が指定された場合,自動で lb=0, ub=1 が設定されます. オブジェクトの生成後に変更できます.
init (float or dict) -- Variable の初期値. float の場合,すべての要素に対して同じ値が適用されます. dict の場合,指定された要素の値が適用されます. オブジェクトの生成後に変更できます.
- 例外
TypeError -- 'type' keyword only takes built-in function 'float', 'int' or 'bin'
SimpleError -- infeasible bound of variable {} ( defined infeasible bound [{} <= * <= {}] )
サンプル
>>> i = Element(value=[1,2], name='i') >>> x = Variable(index=i, name='x') >>> x x: x[1] x[2] >>> x.init x[1].init=0 x[2].init=0 >>> x.val x[1].val=0 x[2].val=0 >>> y = Variable(index=i, init=1, name='y') >>> y.val y[1].val=1 y[2].val=1 >>> z = Variable(index=i, init={2: 2}, name='z') >>> z.val z[1].val=0 z[2].val=2 >>> j = Element(value=[3,4], name='j') >>> w = Variable(index=(i,j), name='w') >>> w.val w[1,3].val=0 w[1,4].val=0 w[2,3].val=0 w[2,4].val=0 >>> u = Variable(name='u') >>> u.val u.val=0
- class pysimple.expression.QVariable¶
ベースクラス:
pysimple.expression.Variable
二次の変数を表すクラスです.
QVariable クラスのコンストラクタは公開されません.
- class pysimple.expression.Expression¶
ベースクラス:
collections.abc.Collection
[tuple
[int
|float
|str
, ...]],pysimple.util.Named
式を表すクラスです.
- __getitem__(key: ObjPrm | tuple[ObjPrm, ...] | Index) Expression ¶
key に対応した添字の Expression を返します.
サンプル
>>> i = Element(value=[1, 2], name='i') >>> j = Element(value=[3, 4], name='j') >>> x = Variable(index=(i,j), name='x'); x[i,j] = i+j >>> e = x[i,j] + 1 >>> e[i,j].val (x[i,j]+1)[1,3].val=5 (x[i,j]+1)[1,4].val=6 (x[i,j]+1)[2,3].val=6 (x[i,j]+1)[2,4].val=7 >>> e[i,3].val (x[i,j]+1)[1,3].val=5 (x[i,j]+1)[2,3].val=6 >>> e[2,3].val 6 >>> ij = Element(value=[(1,3), (1,4), (2,3)], name='ij') >>> e[ij].val (x[i,j]+1)[1,3].val=5 (x[i,j]+1)[1,4].val=6 (x[i,j]+1)[2,3].val=6 >>> e[1,5].val KeyError: 'x[1,5]' >>> b = Parameter(index=j, value={3: 4, 4: 3}, name='b') >>> e[i, b[j]].val (x[i,j]+1)[i,b[j]][1,3].val=6 (x[i,j]+1)[i,b[j]][1,4].val=5 (x[i,j]+1)[i,b[j]][2,3].val=7 (x[i,j]+1)[i,b[j]][2,4].val=6
- __iter__() collections.abc.Iterator[Key] ¶
iter(self) を返します.
- 戻り値の型
Iterator[
Key
]
サンプル
>>> i = Element(value=[1,2]) >>> x = Variable(index=i) >>> x1 = x[i] + 1 >>> for _i in x1: ... print(_i) ... (1,) (2,) >>> ij = Element(value=[(1,3), (1,4), (2,3)]) >>> y = Variable(index=ij) >>> y1 = y[ij] + 1 >>> for _ij in y1: ... print(_ij) ... (1, 3) (1, 4) (2, 3)
注釈
次元に関わらず,値は常にタプルとして返されることに注意してください.
- get(*key: ObjPrm) Expression ¶
key に対応した添字の Expression を返します. __getitem__ と異なり key に対応するものがない場合には KeyError が 投げられず 0 となります.key の次元が異なる場合はその限りではありません. デフォルト値の指定はできず常に 0 となります.
サンプル
>>> i = Element(value=[1, 2], name='i') >>> j = Element(value=[3, 4], name='j') >>> x = Variable(index=(i,j), name='x'); x[i,j] = i+j >>> e = x[i,j] + 1 >>> e.get(i,j) (x[i,j]+1).get(i,j): x[1,3]+1 x[1,4]+1 x[2,3]+1 x[2,4]+1 >>> e.get(i,4) (x[i,j]+1).get(i,4): x[1,4]+1 x[2,4]+1 >>> e.get(i,5) (x[i,j]+1).get(i,5): 1 1 >>> e.get(i+1,j) (x[i,j]+1).get((i+1)[i],j): x[2,3]+1 x[2,4]+1 1 1
- property index: pysimple.index.Index¶
添字
- property init: pysimple.table.Table¶
式の初期値を表す属性です. 値は構成される変数・定数の値の更新に連動します.
サンプル
>>> p = Problem(silent=True) >>> i = Element(value=[1,2], name='i') >>> x = Variable(index=i, init=2, lb=1, name='x') >>> x1 = x[i] + 1 >>> x1.init (x[i]+1)[1].init=3 (x[i]+1)[2].init=3 >>> x[2] = 3 >>> x1.init (x[i]+1)[1].init=3 (x[i]+1)[2].init=4 >>> p += Sum(x1[i]) >>> p.solve() <NuoptStatus.OPTIMAL: 1> >>> x1.init (x[i]+1)[1].init=3 (x[i]+1)[2].init=4 >>> p.solve() <NuoptStatus.OPTIMAL: 1> >>> x1.init (x[i]+1)[1].init=2.000000000208333 (x[i]+1)[2].init=2.000000000208333
- property val: pysimple.table.Table¶
式の現在値を表す属性です. 値は構成される変数の値の更新に連動します.
サンプル
>>> p = Problem(silent=True) >>> i = Element(value=[1,2], name='i') >>> x = Variable(index=i, init=2, lb=1, name='x') >>> x1 = x[i] + 1 >>> x1.val (x[i]+1)[1].val=3 (x[i]+1)[2].val=3 >>> x[2] = 3 >>> x1.val (x[i]+1)[1].val=3 (x[i]+1)[2].val=4 >>> p += Sum(x1[i]) >>> p.solve() <NuoptStatus.OPTIMAL: 1> >>> x1.val (x[i]+1)[1].val=2.000000000208333 (x[i]+1)[2].val=2.000000000208333
バージョン 1.3.1 で追加: __getitem__()
に Parameter が使用可能になりました.
バージョン 1.5.0 で追加: get()
が追加されました.
5.1.5. 制約式¶
- class pysimple.constraint.Constraint¶
ベースクラス:
collections.abc.Collection
[tuple
[int
|float
|str
, ...]],pysimple.util.Named
制約式を表すクラスです.
Constraint クラスのコンストラクタは公開されません.
- __getitem__(key: ObjPrm | tuple[ObjPrm, ...] | Index) Constraint ¶
key に対応した添字の Constraint を返します.
サンプル
>>> i = Element(value=[1, 2], name='i') >>> j = Element(value=[3, 4], name='j') >>> x = Variable(index=(i,j), name='x'); x[i,j] = i+j >>> cons = x[i,j] >= 1 >>> cons[i,j] (x[i,j]>=1): x[1,3]>=1 x[1,4]>=1 x[2,3]>=1 x[2,4]>=1 >>> cons[i,3] (x[i,j]>=1): x[1,3]>=1 x[2,3]>=1 >>> cons[2,3] (x[i,j]>=1): x[2,3]>=1 >>> ij = Element(value=[(1,3), (1,4), (2,3)], name='ij') >>> cons[ij] (x[i,j]>=1): x[1,3]>=1 x[1,4]>=1 x[2,3]>=1 >>> cons[1,5] KeyError: 'x[1,5]'
- __iter__() collections.abc.Iterator[Key] ¶
iter(self) を返します.
- 戻り値の型
Iterator[
Key
]
サンプル
>>> i = Element(value=[1,2]) >>> x = Variable(index=i) >>> cons1 = x[i] <= 1 >>> for _i in cons1: ... print(_i) ... (1,) (2,) >>> ij = Element(value=[(1,3), (1,4), (2,3)]) >>> y = Variable(index=ij) >>> cons2 = y[ij] <= 1 >>> for _ij in cons2: ... print(_ij) ... (1, 3) (1, 4) (2, 3)
注釈
次元に関わらず,値は常にタプルとして返されることに注意してください.
- property dual: pysimple.table.Table | None¶
制約式の双対変数値を表す属性です. 値は求解時に更新されます. オブジェクト生成時の値は None です.
- get(*key: ObjPrm) Constraint ¶
key に対応した添字の Constraint を返します. __getitem__ と異なり key に対応するものがない場合には KeyError が 投げられず 0 となります.key の次元が異なる場合はその限りではありません. デフォルト値の指定はできず常に 0 となります.
サンプル
>>> i = Element(value=[1, 2], name='i') >>> j = Element(value=[3, 4], name='j') >>> x = Variable(index=(i,j), name='x'); x[i,j] = i+j >>> cons = x[i,j] >= 1 >>> cons.get(i,j) (x[i,j]>=1): x[1,3]>=1 x[1,4]>=1 x[2,3]>=1 x[2,4]>=1 >>> cons.get(i,4) (x[i,j]>=1): x[1,4]>=1 x[2,4]>=1 >>> cons.get(i,5) (x[i,j]>=1): 0>=1 0>=1 >>> cons.get(i+1,j) (x[i,j]>=1): x[2,3]>=1 x[2,4]>=1 0>=1 0>=1
- property index: pysimple.index.Index¶
添字
- isHard() bool ¶
weight
がハード制約の場合に True となります.SelectionConstraint
では常に True です.
- property violation: pysimple.constraint.ConstraintWeight¶
制約式の違反値を表す属性です. 両辺の現在値に対して計算されます. 不等式制約と等式制約の場合で異なり,以下が成立します.
(式1 <= 式2).violation = 式1.val - 式2.val
(式1 >= 式2).violation = 式2.val - 式1.val
(式1 == 式2).violation = abs(式1.val - 式2.val)
値は構成される変数・定数の値の更新に連動します.
サンプル
>>> i = Element(value=[1,2], name='i') >>> x = Variable(index=i, init=2, name='x') >>> (x[i] <= 5).violation (x[i]<=5)[1].violation=-3 (x[i]<=5)[2].violation=-3 >>> y = Variable(index=i, init=9, name='y') >>> (y[i] <= 5).violation (y[i]<=5)[1].violation=4 (y[i]<=5)[2].violation=4 >>> z = Variable(index=i, init=2, name='z') >>> (z[i] == 5).violation (z[i]==5)[1].violation=3 (z[i]==5)[2].violation=3 >>> w = Variable(index=i, init=9, name='w') >>> (w[i] == 5).violation (w[i]==5)[1].violation=4 (w[i]==5)[2].violation=4
- property weight: pysimple.constraint.ConstraintWeight¶
制約関数で指定した制約種別です.
バージョン 1.5.0 で追加: get()
が追加されました.
- class pysimple.constraint.SelectionConstraint¶
ベースクラス:
pysimple.constraint.Constraint
Selection
関数によって作成された制約を表すクラスです.
- class pysimple.constraint.ConstraintWeight¶
制約式の種別を表すクラスです.
5.1.6. 問題,求解オプション,解情報¶
- class pysimple.Problem(name: str = None, type: Literal[min, max] = min, silent: bool = False, subprocess: bool = False, solfile: bool | str | None = None, iis: bool = True)¶
問題を表すクラスです.
- パラメータ
name (str) -- 省略した場合はクラス名になります.オブジェクトの生成後に変更できます.
type (min or max) -- 組み込み関数の min, max を指定します. それぞれ目的関数の最小化,最大化を意味します.
silent (bool) -- 求解時の求解情報を標準出力に出力するか制御します. False: 出力する, True: 出力しない
subprocess (bool) -- 求解を別プロセスとして行うかを制御します. False: 同一プロセスで行う, True: 別プロセスで行う
solfile (None or bool or str) --
解ファイルの出力を制御します.
None or False: 出力しない.
True: 出力する.ファイル名は Problem.name + '.sol' となります.
str: 出力する.ファイル名は solfile + '.sol' となります.
iis (bool) -- 解が infeasible の場合に IIS 情報を生成するかどうか制御します. False: IIS 情報を生成しない, True: IIS 情報を生成する
注釈
引数 solfile でファイル名を指定する場合は絶対パス名, 相対パス名のいずれでも指定することができます. また,以下の場合に solfile の出力に失敗しますが,Variable.val 等で計算結果の取得は可能です.
ファイル名として使用できない文字(: * ? " < > |)が含まれている場合
同名のファイルがすでに存在し,上書きの許可がない場合
ファイルシステムに空き容量がない場合
- __delitem__(key: str | int) None ¶
del problem.constraints[key] と等価です.
サンプル
>>> p = Problem() >>> x = Variable(name='x') >>> y = Variable(name='y') >>> p += x >= 1 >>> p += y >= 2, '制約式2' >>> p Problem(name='Problem', type=min, silent=False, subprocess=False, solfile=None, iis=True): [constraints] (x>=1): x>=1 制約式2: y>=2 . [objective] None . >>> del p['(x>=1)'] >>> del p['制約式2'] >>> p Problem(name='Problem', type=min, silent=False, subprocess=False, solfile=None, iis=True): [constraints] . [objective] None
- __getitem__(key: str | int) Constraint ¶
problem.constraints[key] と等価です.
サンプル
>>> p = Problem() >>> x = Variable(name='x') >>> y = Variable(name='y') >>> p += x >= 1 >>> p += y >= 2, '制約式2' >>> p Problem(name='Problem', type=min, silent=False, subprocess=False, solfile=None, iis=True): [constraints] (x>=1): x>=1 制約式2: y>=2 . [objective] None . >>> p['(x>=1)'] (x>=1): x>=1 >>> p['制約式2'] 制約式2: y>=2 >>> p[1] 制約式2: y>=2 >>> p[-1] 制約式2: y>=2
- __iadd__(args: Variable | Expression) Self ¶
- __iadd__(args: tuple[Variable | Expression, str]) Self
- __iadd__(args: tuple[Variable | Expression, ConstraintWeight]) Self
- __iadd__(args: tuple[Variable | Expression, str, ConstraintWeight]) Self
- __iadd__(args: tuple[Variable | Expression, ConstraintWeight, str]) Self
- __iadd__(args: Constraint) Self
- __iadd__(args: tuple[Constraint, str]) Self
問題に目的関数・制約式を設定します. 「問題 += 変数・式[, 目的関数名]」で目的関数を設定し,「問題 += 制約式[, 制約式名]」で制約式を追加します. 目的関数には添字が残っていてはいけません. 目的関数を複数設定することは通常できませんが,一旦求解することで再設定できるようになります. 同名の制約式を追加することはできません.
- 例外
SimpleError -- objective can only be assigned once
SimpleError -- override constraint {}
注釈
目的関数名・制約式名を与えた場合は副作用があります. すなわち,式・制約式の name 属性が変更されます.
サンプル
>>> p = Problem(silent=True) >>> i = Element(value=[1,2], name='i') >>> x = Variable(index=i, name='x') >>> p += Sum(x[i]), '総コスト' >>> p += x[1] >= 1 >>> p += x[2] >= 2, '制約式2' >>> p Problem(name='Problem', type=min, silent=True, subprocess=False, solfile=None, iis=True): [constraints] (x[1]>=1): x[1]>=1 制約式2: x[2]>=2 . [objective] 総コスト: x[1]+x[2] . >>> p += Sum(x[i]) pysimple.error.SimpleError: objective can only be assigned once >>> p += x[1] >= 1 pysimple.error.SimpleError: override constraint '(x[1]>=1)' >>> p.solve() <NuoptStatus.OPTIMAL: 1> >>> p += Sum(x[i])
- property constraints: pysimple.problem.IndexedDict[pysimple.constraint.Constraint]¶
問題の制約式を表す属性です.「問題 += 制約式[, 制約式名]」で追加されます. 制約式名をキー,制約式を値とする辞書です. 参照,削除には追加した順の番号も使用できます.負数の場合,逆順から参照されます.
サンプル
>>> x = Variable(name='x') >>> y = Variable(name='y') >>> p = Problem() >>> p += x >= 1, 'cons1' >>> p.constraints cons1: x>=1 >>> p += y >= 2, 'cons2' >>> p.constraints cons1: x>=1 cons2: y>=2 >>> p.constraints['cons2'] cons2: y>=2 >>> p.constraints[1] cons2: y>=2 >>> p.constraints[-1] cons2: y>=2 >>> del p.constraints[-1] >>> p.constraints cons1: x>=1
- hasSolution() bool ¶
直前の Problem.solve() で解情報が設定されているかどうかを返します. 解情報は本問題で使用している変数の val 属性から参照することができます.
- 戻り値
求解後に解情報が設定されている場合に真,そうでない場合に偽を返します.
- 戻り値の型
注釈
problem.status の値が NuoptStatus.OPTIMAL,NuoptStatus.FEASIBLE の場合は problem.hasSolution() は必ず真を返し,設定されている解情報は実行可能な解の 保証があります. 一方,problem.status がその他の値で problem.hasSolution() が真の場合は, 実行不可能な解が設定されています.
- isFeasible() bool ¶
直前の Problem.solve() で実行可能解が求まったかどうかを返します.
- 戻り値
実行可能解が求まった場合に真を返します. 実行可能解が求まっていない場合は偽を返します.
- 戻り値の型
注釈
problem.status が NuoptStatus.OPTIMAL または NuoptStatus.FEASIBLE の場合に真を返します. 本メソッドの戻り値が真の場合,本問題で使用している変数の val 属性から 参照できる解情報は実行可能です.
- isInfeasible() bool ¶
直前の Problem.solve() で実行可能解が存在しないと判断されたかどうかを返します.
- 戻り値
求解後の実行可能解が存在しないと判断された場合に真, そうでない場合に偽を返します.
- 戻り値の型
注釈
problem.status が NuoptStatus.INFEASIBLE の場合に真を返します. 本メソッドの戻り値が真(実行可能解が存在しない場合)で,かつ, problem.hasSolution() も真の場合は,本問題で使用している変数の val 属性には実行不可能な解情報が設定されています.
- mpsout(mpsfile: bool | str | None = True, anonymous: bool = False, initial: bool = False) None ¶
問題情報を mps 形式でファイル出力します.
- パラメータ
注釈
引数で指定された名前に拡張子 .mps が付与されたファイル名で mps 形式のファイルが 出力されます. ファイル名は絶対パス名,相対パス名のいずれでも指定することができます. 出力される mps ファイルの形式は自由長形式です(固定長形式ではありません). 以下の場合に mps ファイルの出力に失敗します.
ファイル名として使用できない文字(: * ? " < > |)が含まれている場合
同名のファイルがすでに存在し,上書きの許可がない場合
ファイルシステムに空き容量がない場合
- property objective: pysimple.expression.Variable | pysimple.expression.Expression¶
問題の目的関数を表す属性です. 「問題 += 変数・式[, 目的関数名]」で設定されます. オブジェクト生成時の値は空の式です. 通常,目的関数を複数設定することはできませんが,一旦求解することで再設定できるようになります. del 文で目的関数を削除できます.
サンプル
>>> p = Problem(silent=True) >>> i = Element(value=[1,2], name='i') >>> x = Variable(index=i, lb=1, init=2, name='x') >>> x.val x[1].val=2 x[2].val=2 >>> p.objective <empty>: 0 >>> p += Sum(x[i]) >>> p.objective.val 4 >>> p += x[2] pysimple.error.SimpleError: objective can only be assigned once >>> p.solve() <NuoptStatus.OPTIMAL: 1> >>> x.val x[1].val=1.0000000002083331 x[2].val=1.0000000002083331 >>> p.objective.val 2.0000000004166663 >>> p += x[2] >>> del p.objective >>> p += x[1]
- property options: pysimple.options.ProblemOptions¶
求解オプション定数を制御する属性です. 種類と値は help(problem.options) か dir(problem.options) で, 定数値は help(Options) か help(Options.Branch) で確認してください.
- property result: pysimple.problem.Result¶
求解後の求解情報を表す属性です. 詳細は help(problem.result) で確認してください.
- setCallback(mip_terminate: Callable[[dict[str, int | float]], bool] | None = None) None ¶
分枝限定法の停止を制御するコールバック関数を設定します. コールバック関数は次のような関数になります.
def mip_terminate(solver: dict[str, int | float]) -> bool:
戻り値は bool 型オブジェクトが想定され,True を返すと分枝限定法を停止し,False を返すと継続して実行されます. 引数には,本関数が呼び出された時点の最適化計算の情報が辞書型に格納されており,次の情報を取得することができます.
キー
内容
ElapsedTime
経過時間
RelativeGap
相対ギャップ
AbsoluteGap
絶対ギャップ
Objective
目的関数値
SolutionCount
実行可能解の数
TotalMemory
メモリ消費量(MiB)
MemoryAvailable
利用可能メモリ量 (MiB)
PartialProblemCount
部分問題の数(ノード数)
- パラメータ
mip_terminate (コールバック関数 or None) -- 分枝限定法の終了コールバック関数を指定します. None を指定した場合はコールバック関数がクリアされます.
- 例外
TypeError -- mip_terminate が関数でも None でもない場合に raise されます.
注釈
- コールバック関数により停止した場合のステータス番号は次のようになります.
実行可能解が得られている場合 : NUOPT 31
実行可能解が得られていない場合 : NUOPT 32
実行可能解が得られていない場合,AbsoluteGap / RelativeGap は +inf の値になっています.
実行可能解が得られていない場合,Objective は最大化問題の場合 -inf,最小化問題の場合 +inf の値になっています.
最適化計算情報の内,"MemoryAvailable" は Windows 版のみ有効です.
コールバック関数内で例外が発生した場合は,その例外の stacktrace を標準エラー出力に表示し,分枝限定法を停止します.
サンプル
>>> def func(solver: dict[str, int | float]) -> bool: ... if solver["SolutionCount"] >= 1: ... # 実行可能解の個数が 1 以上になったら分枝限定法を停止する ... return True ... return False >>> p = Problem() >>> p.setCallback(mip_terminate=func)
- solve(type: Literal[min, max] = min, silent: bool = False, subprocess: bool = False, solfile: bool | str | None = None, iis: bool = True) NuoptStatus ¶
求解を行います. 引数の詳細は Problem の初期化時 help(Problem.__init__) で確認してください. 引数は初期化時に設定した値に優先されます. 省略した場合,初期化時の値が使用されます.
- 例外
RuntimeError -- kernel of Nuorium Optimizer is terminated abnormally
NuoptError -- internal error in Nuorium Optimizer
SimpleError -- neither valid objective nor constraint in this model
- 戻り値
求解後のステータスです.
戻り値
ステータス
NuoptStatus.OPTIMAL
最適解が求まりました
NuoptStatus.FEASIBLE
実行可能解が求まりました
NuoptStatus.INFEASIBLE
実行不可能であることが判明しました
NuoptStatus.UNBOUNDED
非有界であることが判明しました
NuoptStatus.DUAL_INFEASIBLE
双対実行不可能(実行不可能あるいは非有界)であることが判明しました
NuoptStatus.ERROR
最適化計算実行時にエラーとなりました
NuoptStatus.UNKNOWN
上記以外のステータスとなりました
- 戻り値の型
注釈
NuoptStatus.OPTIMAL の以外の場合は,Problem.result.errorCode から 詳細なエラー番号を取得することができます. また,Problem.result.errorMessage に最適化のカーネルからの エラーメッセージが設定されている場合があります.
- property status: pysimple.problem.NuoptStatus¶
直前の Problem.solve() の結果を表す属性です.
NuoptStatus.INITIAL : 求解をしたことがないことを表しています.
NuoptStatus.OPTIMAL : 最適解が得られたことを表しています.
NuoptStatus.FEASIBLE : 実行可能解が得られたことを表しています.
NuoptStatus.INFEASIBLE : 実行可能解が存在しなかったと判定されたことを表しています.
NuoptStatus.UNBOUNDED : 非有界であることを表しています.
NuoptStatus.DUAL_INFEASIBLE : 双対実行不可能(実行不可能あるいは非有界)であることを表しています.
NuoptStatus.UNKNOWN : 上記以外のステータスであることを表しています.
- property variables: pysimple.problem.IndexedDict[pysimple.expression.Variable]¶
問題に登録した制約式,目的関数に含まれる変数の一覧を表す属性です. 変数名をキー,変数を値とする辞書です. 参照には追加した順の番号も使用できます.負数の場合,逆順から参照されます. 辞書は制約式,目的関数の登録状況,name 属性の変更等に対して動的に追従します.
- 例外
SimpleError -- Variable name {} is duplicated
サンプル
>>> x = Variable(name='x') >>> y = Variable(name='y') >>> p = Problem() >>> p += x >= 1, 'cons1' >>> p.variables x: x >>> p += y >= 1, 'cons2' >>> p.variables x: x y: y >>> p.variables['y'] y: y >>> p.variables[1] y: y >>> p.variables[-1] y: y >>> del p['cons2'] >>> p.variables x: x
バージョン 1.1.0 で追加: mpsout()
が追加されました.
バージョン 1.3.0 で追加: variables()
が追加されました.
バージョン 1.3.0 で追加: __getitem__()
, __delitem__()
に番号でアクセスできるようになりました.
バージョン 1.4.0 で追加: setCallback()
が追加されました.
バージョン 1.6.0 で追加: mpsout()
に引数 anonymous と initial が追加されました.
- class pysimple.options.ProblemOptions¶
求解オプション定数を表すクラスです.
- property branchCut: pysimple.options.Cut | None¶
導入される切除平面の数の目安.(分枝限定法専用) 値: Cut.OFF, Cut.ON, Cut.AGGRESSIVE
- property branchDisconnected: pysimple.options.Disconnected | None¶
非連結成分検出.(分枝限定法専用) 値: Disconnected.AUTO, Disconnected.OFF, Disconnected.ON
- property branchDiving: pysimple.options.Diving | None¶
ヒューリスティクスサーチ Diving の頻度.(分枝限定法専用) 値: Diving.AUTO, Diving.OFF, Diving.ON, Diving.AGGRESSIVE, Diving.SUPERAGGRESSIVE
- property branchFeasPump: pysimple.options.FeasPump | None¶
ヒューリスティクスサーチ Feasibility Pump の頻度.(分枝限定法専用) 値: FeasPump.AUTO, FeasPump.OFF, FeasPump.ON
- property branchNodeSelect: pysimple.options.NodeSelect | None¶
ノード選択.(分枝限定法専用) 値: NodeSelect.AUTO, NodeSelect.BESTDEPTH, NodeSelect.BESTESTIMATE
- property branchParallelMethod: pysimple.options.ParallelMethod | None¶
並列分枝限定法の手法.(分枝限定法専用) 値: ParallelMethod.RACING, ParallelMethod.DETERMINISTIC_RACING, ParallelMethod.SUBTREE
- property branchPresolve: pysimple.options.Presolve | None¶
分枝限定法における前処理.(分枝限定法専用) 値: Presolve.AUTO, Presolve.OFF, Presolve.ON
- property branchRens: pysimple.options.Rens | None¶
ヒューリスティクスサーチ rens の導入.(分枝限定法専用) 値: Rens.AUTO, Rens.OFF, Rens.ON
- property branchRepairSolution: pysimple.options.RepairSolution | None¶
ユーザ指定の初期解を元に解の修復をおこなう.(分枝限定法専用) 値: RepairSolution.OFF, RepairSolution.ON, RepairSolution.AGGRESSIVE
- property branchRins: pysimple.options.Rins | None¶
ヒューリスティクスサーチ rins の導入.(分枝限定法専用) 値: Rins.AUTO, Rins.OFF, Rins.ON
- property branchUseWcsp: pysimple.options.UseWcsp | None¶
ヒューリスティクスサーチ wcsp タブーサーチの導入.(分枝限定法専用) 値: UseWcsp.AUTO, UseWcsp.OFF, UseWcsp.ON
- property branchUseWls: pysimple.options.UseWls | None¶
ヒューリスティクスサーチ wls の導入.(分枝限定法専用) 値: UseWls.AUTO, UseWls.OFF, UseWls.ON
- property branchVariableSelectScore: pysimple.options.VariableSelectScore | None¶
分枝変数のスコアの評価方法.(分枝限定法専用) 値: VariableSelectScore.AUTO, VariableSelectScore.SUM, VariableSelectScore.PRODUCT
- property hsimplexMethod: pysimple.options.Options.HsimplexMethod | None¶
アルゴリズム hsimplex の具体的な手法.(hsimplex 専用) 値: HsimplexMethod.AUTO, HsimplexMethod.PRIMAL, HsimplexMethod.DUAL
- property maxMemory: int | None¶
メモリ利用量上限(MiB).負の値の場合は,分枝限定法は残り利用可能メモリ(MiB)による制限,wls は無制限と解釈します.(分枝限定法,wls) 値: int (-1 以上)
- property method: pysimple.options.Options.Method | None¶
求解アルゴリズムの種類. 値: Method.AUTO, Method.LIPM, Method.HIGHER, Method.TIPM, Method.BFGS, Method.SIMPLEX, Method.ASQP, Method.LSQP, Method.TSQP, Method.HSIMPLEX, Method.WCSP, Method.WLS
- property objectiveTarget: float | None¶
分枝限定法および wls では目的関数の目標値.目標値よりも良い解を発見した場合は計算を終了します.wcsp ではこの値を目的関数の下(上)限とするソフト制約と解釈します.(分枝限定法,wcsp,wls) 値: float
- property scaling: pysimple.options.Options.Scaling | None¶
スケーリングの種類. 値: Scaling.AUTO, Scaling.OFF, Scaling.ON, Scaling.MINMAX, Scaling.CR
- property wcspPhaseOneMaxIteration: int | None¶
制約充足フェーズにおける制約充足フェーズにおける反復回数上限.(wcsp 専用) 値: int (-1 以上)
- class pysimple.Options¶
ソルバのパラメータを設定するためのクラスです. デフォルト値は Nuorium Optimizer SIMPLEマニュアルの「5. 求解オプション設定 」を参照してください.
- class Branch¶
分枝限定法の求解オプション定数を表すクラスです.
- class Cut(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
導入される切除平面の数の目安.(分枝限定法専用)
- AGGRESSIVE = 2¶
- OFF = 0¶
- ON = 1¶
- class Disconnected(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
非連結成分検出.(分枝限定法専用)
- AUTO = -1¶
- OFF = 0¶
- ON = 1¶
- class Diving(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
ヒューリスティクスサーチ Diving の頻度.(分枝限定法専用)
- AGGRESSIVE = 2¶
- AUTO = -1¶
- OFF = 0¶
- ON = 1¶
- SUPERAGGRESSIVE = 3¶
- class FeasPump(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
ヒューリスティクスサーチ Feasibility Pump の頻度.(分枝限定法専用)
- AUTO = -1¶
- OFF = 0¶
- ON = 1¶
- class NodeSelect(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
ノード選択.(分枝限定法専用)
- AUTO = -1¶
- BESTDEPTH = 1¶
- BESTESTIMATE = 2¶
- class ParallelMethod(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
並列分枝限定法の手法.(分枝限定法専用)
- DETERMINISTIC_RACING = 1¶
- RACING = 0¶
- SUBTREE = 2¶
- class Presolve(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
分枝限定法における前処理.(分枝限定法専用)
- AUTO = -1¶
- OFF = 0¶
- ON = 1¶
- class Rens(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
ヒューリスティクスサーチ rens の導入.(分枝限定法専用)
- AUTO = -1¶
- OFF = 0¶
- ON = 1¶
- class RepairSolution(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
ユーザ指定の初期解を元に解の修復をおこなう.(分枝限定法専用)
- AGGRESSIVE = 2¶
- OFF = 0¶
- ON = 1¶
- class Rins(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
ヒューリスティクスサーチ rins の導入.(分枝限定法専用)
- AUTO = -1¶
- OFF = 0¶
- ON = 1¶
- class UseWcsp(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
ヒューリスティクスサーチ wcsp タブーサーチの導入.(分枝限定法専用)
- AUTO = -1¶
- OFF = 0¶
- ON = 1¶
- class HsimplexMethod(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
アルゴリズム hsimplex の具体的な手法を表すクラスです.
- AUTO = -1¶
- DUAL = 1¶
- PRIMAL = 0¶
- class Method(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)¶
求解アルゴリズムの求解オプション定数を表すクラスです.
- ASQP = 'asqp'¶
- AUTO = 'auto'¶
- BFGS = 'bfgs'¶
- HIGHER = 'higher'¶
- HSIMPLEX = 'hsimplex'¶
- LIPM = 'lipm'¶
- LSQP = 'lsqp'¶
- SIMPLEX = 'simplex'¶
- TIPM = 'tipm'¶
- TSQP = 'tsqp'¶
- WCSP = 'wcsp'¶
- WLS = 'wls'¶
バージョン 1.4.0 で追加: 求解オプション定数のクラス構造が変更されました.
- class pysimple.NuoptStatus¶
ベースクラス:
enum.IntEnum
ソルバの計算後の状態値を定義しているクラスです.
- DUAL_INFEASIBLE = 5¶
- ERROR = 7¶
- FEASIBLE = 2¶
- INFEASIBLE = 3¶
- INITIAL = 0¶
- OPTIMAL = 1¶
- UNBOUNDED = 4¶
- UNKNOWN = 6¶
- class pysimple.problem.Result¶
求解後の求解情報を表すクラスです.
- property errorCode: int¶
Nuorium Optimizer のエラーコード.最適解が得られた場合は 0 が設定されています. エラーコードは Nuorium Optimizer SIMPLE マニュアルの「 A.1.1 Nuorium Optimizerのエラー/警告メッセージ 」を参照してください.
- property iis: pysimple.problem.IIS¶
問題が実行不可能な場合の IIS 情報.IIS 情報がない場合は空の IIS オブジェクトが設定されています.
- class pysimple.problem.IIS¶
-
IIS 情報を保持するクラスです. 制約式は 0 始まりのインデックスで管理されており,そのインデックスを使い各制約式情報にアクセスできます.
サンプル
>>> x = Variable(name='x', lb=0) >>> y = Variable(name='y', lb=0, ub=1) >>> z = Variable(name='z', lb=0) >>> p = Problem() >>> p += x + y + z >>> p += y + z >= 0, 'cons1' >>> p += x + y >= 5, 'cons2' >>> p += x + z <= 3, 'cons3' >>> p.solve(silent=True) <NuoptStatus.INFEASIBLE: 3> >>> p.result.iis 0: cons2: violation=-1 x+y>=5 1: cons3 -x-z>=-3 >>> p.result.iis[0] 0: cons2: violation=1 x+y>=5 x: value=3: dual=0: [0, inf] y: value=1: dual=-1: [0, 1] >>> del p[p.result.iis[0].consname] # index=0 の制約式を delete >>> p Problem(name='Problem', type=min, silent=False, subprocess=False, solfile=None, iis=True): [constraints] cons1: y+z>=0 cons3: -x-z>=-3 . [objective] ((x+y)+z): x+y+z >>> p.solve(silent=True) <NuoptStatus.OPTIMAL: 1> >>> print(p.result.iis) no IIS
参考
pysimple.problem.IIS.OneIIS
- class OneIIS¶
IIS 情報のうち 1 つの制約式の情報を保持するクラスです.
- property OneIIS.variables: list[pysimple.expression.Variable]¶
制約式に含まれる変数列.
5.1.7. シリアライズ¶
- class pysimple.serialize.Serialize¶
PySIMPLE オブジェクトをシリアライズするためのクラスです. pickle.dump/dumps でシリアライズ可能なオブジェクトに加え,PySIMPLE オブジェクトをシリアライズできます.
- static dump(obj: Any, file: BinaryIO) None ¶
オブジェクトをバイナリにシリアライズしてファイル出力します.
サンプル
>>> x = Variable(name='x') >>> with open('dump.pkl', 'wb') as f: ... Serialize.dump(x, f) ... >>> with open('dump.pkl', 'rb') as g: ... x_ = Serialize.load(g) ...
- static dumps(obj: Any) Pickler ¶
オブジェクトをバイナリにシリアライズして返します.
サンプル
>>> x = Variable(name='x') >>> pkl = Serialize.dumps(x) >>> pkl Pickler(version_info(major=1, minor=3, micro=0)) >>> x_ = Serialize.loads(pkl)
- static load(file: BinaryIO) Any ¶
シリアライズされたオブジェクトをバイナリファイルから復元します.
サンプル
>>> x = Variable(name='x') >>> with open('dump.pkl', 'wb') as f: ... Serialize.dump(x, f) ... >>> with open('dump.pkl', 'rb') as g: ... x_ = Serialize.load(g) ...