クラス

目次

5.1. クラス#

コンストラクタが公開されているクラスは,すべての引数をキーワード引数として呼び出さなければなりません. 複数の引数を持たせる場合,キーワード引数の順序は任意です.

インスタンス間に定義されている演算については 演算 を参照してください.

5.1.1. 集合#

class pysimple.Set(name: str | None = None, value: Iterable | None = None, dim: int | None = None)#

ベースクラス: Set[tuple[int | float | str, ...]], Named

集合を表すクラスです. Set はすべて順序を持っています.オブジェクトの生成後は要素を変更できません.

パラメータ:
  • name (str) -- 省略した場合は自動で与えられます.オブジェクトの生成後に変更できます.

  • value (Iterable[DType | Key]) -- イテラブルなオブジェクトを指定します. 多次元の場合は tuple の列を与えます. 省略した場合は空集合が作成されます.

  • dim (positive integer) -- 省略できます. 多次元の空集合を作成する場合は明示的に指定する必要があります.

例外:

サンプル

>>> 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 つ以上必要です.

戻り値の型:

Set

例外:
  • 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 が要素に含まれているかを返します.

パラメータ:

key (DType | Key)

戻り値の型:

bool

注釈

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 を返します.

戻り値の型:

DType or Key or Parameter or 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)

注釈

次元に関わらず,値は常にタプルとして返されることに注意してください.

__len__() int#

要素数を返します.

戻り値の型:

int

property dim#

集合の次元です.

index(key: DType | Key | ELEMENT) int | Parameter#

key が Set の何番目の要素であるかを返します.

パラメータ:

key (DType or Key or ELEMENT)

戻り値:

key が DType または Key の場合は int を,ELEMENT の場合は Parameter を返します.

戻り値の型:

int or 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
property name: str#

name 属性です.値は文字列の代入により変更できます.

next(key: DType | Key | ELEMENT) DType | Key | Parameter#

Set における key の次の要素を返します.

パラメータ:

key (DType or Key or ELEMENT)

戻り値:

key が DType または Key の場合は Set の要素を,ELEMENT の場合は Parameter を返します.

戻り値の型:

DType or Key or Parameter

例外:

サンプル

>>> 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 or Key or ELEMENT)

戻り値:

key が DType または Key の場合は Set の要素を,ELEMENT の場合は Parameter を返します.

戻り値の型:

DType or Key or Parameter

例外:

サンプル

>>> 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

Added in version 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 属性を参照してください.

パラメータ:
  • name (str) -- 省略した場合は自動で与えられます.オブジェクトの生成後に変更できます.

  • set (Set) -- 対応する集合です.value キーワードと併用できません.

  • value (Iterable) -- Set の value キーワードと同じです.set キーワードと併用できません.

  • dim (positive integer) -- 省略できます. 多次元の空の添字を作成する場合は明示的に指定する必要があります.

例外:

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 つ以上必要です.

戻り値の型:

ElementSlice

例外:
  • 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 name: str#

name 属性です.値は文字列の代入により変更できます.

property set: 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__() Iterator[IDXT]#
property dim: int#

添字つきオブジェクトの次元です.

5.1.3. 定数#

class pysimple.Parameter(name: str = None, index: Set | ELEMENT | tuple[Set | ELEMENT, ...] | Index | None = None, value: DType | dict = 0)#

定数を表すクラスです.

パラメータ:
  • name (str) -- 省略した場合は自動で与えられます.オブジェクトの生成後に変更できます.

  • index (Set or ELEMENT or tuple of them or Index) -- Parameter の添字. 省略した場合,添字なしの定数となります.

  • value (DType or dict) -- Parameter の値. DType の場合,すべての要素に対して同じ値が適用されます. dict の場合,指定された要素の値が適用されます. オブジェクトの生成後に変更できます.

例外:

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
__abs__() None#

Fabs(obj: ObjPrm) -> Num | Parameter

パラメータ:

obj (ObjPrm)

戻り値:

obj が DType の場合は math.fabs (obj) の結果を, それ以外の場合は math.fabs を各要素に適用した Parameter を返す.

戻り値の型:

Num or Parameter

__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'
__ceil__() None#

Ceil(obj: ObjPrm) -> Num | Parameter

パラメータ:

obj (ObjPrm)

戻り値:

obj が DType の場合は math.ceil (obj) の結果を, それ以外の場合は math.ceil を各要素に適用した Parameter を返す.

戻り値の型:

Num or Parameter

__contains__(key: DType or Key) bool#

key がキーに含まれているかを返します.

戻り値の型:

bool

__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)

戻り値:

key がすべて DType の場合,DType を返します. それ以外の場合,Parameter を返します.

戻り値の型:

DType or Parameter

例外:
  • KeyError -- key がキーに存在しない場合

  • KeyError -- '{}' takes {} dimension index ({} given)

サンプル

>>> 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)

注釈

次元に関わらず,値は常にタプルとして返されることに注意してください.

__len__() int#

キーの要素数を返します.

戻り値の型:

int

__round__(ndigits: int | None = None) Parameter#

値の小数部を ndigits 桁に丸めた値を返します.ndigits が省略された場合,最も近い整数を返します.

パラメータ:

ndigits (int) -- 小数部を丸める桁数です.0 や負数の場合,整数部となります.

戻り値の型:

Parameter

サンプル

>>> 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 に対応した値を変更します.

パラメータ:
例外:

KeyError -- 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 となります.

パラメータ:

*key (ObjPrm)

戻り値:

key がすべて DType の場合,DType を返します. それ以外の場合,Parameter を返します.

戻り値の型:

DType or Parameter

例外:

KeyError -- '{}' takes {} dimension index ({} given)

サンプル

>>> 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: Index#

添字

items() dict_items[Key, VT]#

キーと値ペアの列を返します.

keys() dict_keys[Key, VT]#

キーの列を返します.

property name: str#

name 属性です.値は文字列の代入により変更できます.

values() dict_values[Key, VT]#

値の列を返します.

Added in version 1.3.0: __round__() が使用可能になりました.

Added in version 1.5.0: get() が添字をサポートするようになりました.

class pysimple.table.Table#

.val などの属性を表すクラスです.

Table クラスは __getitem__(), get(), __setitem__() がないこと以外は,ほぼ Parameter と同じです.

Table クラスのコンストラクタは公開されません.

initvallbubdualinitval, dualviolation が Table クラスに該当します.

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'))#

ベースクラス: Final, Collection[tuple[int | float | str, ...]], 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 の場合,指定された要素の値が適用されます. オブジェクトの生成後に変更できます.

  • lb (float or dict) -- Variable の下限値.

  • ub (float or dict) -- Variable の上限値.

例外:
  • 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
__contains__(key: DType or Key) bool#

key がキーに含まれているかを返します.

戻り値の型:

bool

__getitem__(key: ObjPrm | tuple[ObjPrm, ...] | Index) Variable#

key に対応した添字の Variable を返します.

パラメータ:

key (ObjPrm or tuple of them or Index)

戻り値の型:

Variable

例外:

KeyError -- key がキーに存在しない場合

サンプル

>>> 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)

注釈

次元に関わらず,値は常にタプルとして返されることに注意してください.

__len__() int#

キーの要素数を返します.

戻り値の型:

int

__setitem__(key: ObjPrm | tuple[ObjPrm, ...] | Index, value: ObjPrm) None#

key に対応した値を変更します.値は val で確認できます.

パラメータ:
例外:

KeyError -- key がキーに存在しない場合

サンプル

>>> 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: Table | None#

変数の双対変数値を表す属性です. 値は求解時に更新されます. オブジェクト生成時の値は None です.

fix() None#

変数の値を現在値 val に固定します. 下限値 lb と上限値 ub を現在値 val に設定するのと同じ効果です. lb/ub と値が矛盾する場合は求解時に SimpleError が投げられます.

get(*key: ObjPrm) Variable#

key に対応した添字の Variable を返します. __getitem__ と異なり key に対応するものがない場合には KeyError が 投げられず 0 となります.key の次元が異なる場合はその限りではありません. デフォルト値の指定はできず常に 0 となります.

パラメータ:

*key (ObjPrm)

戻り値の型:

Variable

例外:

KeyError -- '{}' takes {} dimension index ({} given)

サンプル

>>> 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 における割当ラベルとして解釈され,解の探索に利用されます. 具体的には,アルゴリズム内で各変数が「指定された添字」と「それ以外の添字」を割り当てる(関連づける) 構造をもつと解釈されます. 例えば,下記サンプルコードの 0-1 変数 x が「i を (j, k) に割り当てるなら 1,そうでないなら 0」 を意味する変数である場合,x.group = 0 の設定により探索性能の向上が見込めます. i が作業員,j が仕事,k が時間帯だとすると,x.group = 0 は「各作業員 i に対して,仕事 j と時間帯 k の組合せを割り当てる」ことを意味します.

本属性は解法 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     # 「0 番目の添字」と「1, 2 番目の添字」の割当てを明示
>>> x.group
(0,)
>>> x.group = 0, 2  # 「0, 2 番目の添字」と「1 番目の添字」の割当てを明示
>>> x.group
(0, 2)
property index: Index#

添字

property init: 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: 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 name: str#

name 属性です.値は文字列の代入により変更できます.

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: 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
unfix() None#

Variable.fix で固定した変数の値を解除します.

property val: 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

Added in version 1.5.0: fix() , unfix() が追加されました.

Added in version 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'))#

ベースクラス: 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 の場合,指定された要素の値が適用されます. オブジェクトの生成後に変更できます.

  • lb (float or dict) -- Variable の下限値.

  • ub (float or dict) -- Variable の上限値.

例外:
  • 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'))#

ベースクラス: 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 の場合,指定された要素の値が適用されます. オブジェクトの生成後に変更できます.

  • lb (float or dict) -- Variable の下限値.

  • ub (float or dict) -- Variable の上限値.

例外:
  • 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#

ベースクラス: Variable

二次の変数を表すクラスです.

QVariable クラスのコンストラクタは公開されません.

class pysimple.expression.Expression#

ベースクラス: Collection[tuple[int | float | str, ...]], Named

式を表すクラスです.

__contains__(key: DType or Key) bool#

key がキーに含まれているかを返します.

戻り値の型:

bool

__getitem__(key: ObjPrm | tuple[ObjPrm, ...] | Index) Expression#

key に対応した添字の Expression を返します.

パラメータ:

key (ObjPrm or tuple of them or Index)

戻り値の型:

Expression

例外:

KeyError -- key がキーに存在しない場合

サンプル

>>> 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)

注釈

次元に関わらず,値は常にタプルとして返されることに注意してください.

__len__() int#

キーの要素数を返します.

戻り値の型:

int

get(*key: ObjPrm) Expression#

key に対応した添字の Expression を返します. __getitem__ と異なり key に対応するものがない場合には KeyError が 投げられず 0 となります.key の次元が異なる場合はその限りではありません. デフォルト値の指定はできず常に 0 となります.

パラメータ:

*key (ObjPrm)

戻り値の型:

Expression

例外:

KeyError -- '{}' takes {} dimension index ({} given)

サンプル

>>> 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: Index#

添字

property init: 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 name: str#

name 属性です.値は文字列の代入により変更できます.

property val: 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

Added in version 1.3.1: __getitem__() に Parameter が使用可能になりました.

Added in version 1.5.0: get() が追加されました.

5.1.5. 制約式#

class pysimple.constraint.Constraint#

ベースクラス: Collection[tuple[int | float | str, ...]], Named

制約式を表すクラスです.

Constraint クラスのコンストラクタは公開されません.

__contains__(key: DType or Key) bool#

key がキーに含まれているかを返します.

戻り値の型:

bool

__getitem__(key: ObjPrm | tuple[ObjPrm, ...] | Index) Constraint#

key に対応した添字の Constraint を返します.

パラメータ:

key (ObjPrm or tuple of them or Index)

戻り値の型:

Constraint

例外:

KeyError -- key がキーに存在しない場合

サンプル

>>> 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)

注釈

次元に関わらず,値は常にタプルとして返されることに注意してください.

__len__() int#

キーの要素数を返します.

戻り値の型:

int

property dual: Table | None#

制約式の双対変数値を表す属性です. 値は求解時に更新されます. オブジェクト生成時の値は None です.

get(*key: ObjPrm) Constraint#

key に対応した添字の Constraint を返します. __getitem__ と異なり key に対応するものがない場合には KeyError が 投げられず 0 となります.key の次元が異なる場合はその限りではありません. デフォルト値の指定はできず常に 0 となります.

パラメータ:

*key (ObjPrm)

戻り値の型:

Constraint

例外:

KeyError -- '{}' takes {} dimension index ({} given)

サンプル

>>> 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: Index#

添字

isHard() bool#

weight がハード制約の場合に True となります. SelectionConstraint では常に True です.

isSemiHard() bool#

weight がセミハード制約の場合に True となります.

isSoft() bool#

weight がソフト制約の場合に True となります.

property name: str#

name 属性です.値は文字列の代入により変更できます.

property violation: 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: ConstraintWeight#

制約関数で指定した制約種別です.

Added in version 1.5.0: get() が追加されました.

class pysimple.constraint.SelectionConstraint#

ベースクラス: Constraint

Selection 関数によって作成された制約を表すクラスです.

class pysimple.constraint.ConstraintWeight#

制約式の種別を表すクラスです.

5.1.6. 問題,求解オプション,解情報#

class pysimple.Problem(name: str | None = None, type: Literal[min, max] = min, silent: bool = False, subprocess: bool = False, solfile: bool | str | os.PathLike[str] | None = None, iis: Problem.IIS = Problem.IIS.AUTO)#

問題を表すクラスです.

パラメータ:
  • name (str or None) -- 省略した場合はクラス名になります.オブジェクトの生成後に変更できます.

  • type (min or max) -- 組み込み関数の min, max を指定します. それぞれ目的関数の最小化,最大化を意味します.

  • silent (bool) -- 求解時の求解情報を標準出力に出力するか制御します. False: 出力する, True: 出力しない

  • subprocess (bool) -- 求解を別プロセスとして行うかを制御します. False: 同一プロセスで行う, True: 別プロセスで行う

  • solfile (None or bool or str or os.PathLike[str]) --

    解ファイルの出力を制御します.

    • None or False: 出力しない.

    • True: 出力する.ファイル名は Problem.name + '.sol'

    • str or os.PathLike[str]: 出力する.ファイル名は solfile + '.sol'

  • iis (Problem.IIS) --

    実行不可能時に実行不可能性を検出する iisDetect を起動するかどうか制御します.

    • IIS.AUTO: 計算負荷が低いと想定される場合に起動(デフォルト)

    • IIS.OFF: 起動しない

    • IIS.ON: 常に起動する

注釈

引数 solfile でファイル名を指定する場合は絶対パス名, 相対パス名のいずれでも指定することができます. また,以下の場合に solfile の出力に失敗しますが,Variable.val 等で計算結果の取得は可能です.

  • ファイル名として使用できない文字(: * ? " < > |)が含まれている場合

  • 同名のファイルがすでに存在し,上書きの許可がない場合

  • ファイルシステムに空き容量がない場合

class IIS#

ベースクラス: IntEnum

実行不可能性要因検出機能の探索を行うかを表すクラスです.

IIS.AUTO = -1#
IIS.OFF = 0#
IIS.ON = 1#
__delitem__(key: str | int) None#

del problem.constraints[key] と等価です.

パラメータ:

key (str or int) -- 削除する制約式名,または追加した制約式の番号.負数の場合,逆順から参照されます.

サンプル

>>> 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=IIS.AUTO):
[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=IIS.AUTO):
[constraints]
.
[objective]
None
__getitem__(key: str | int) Constraint#

problem.constraints[key] と等価です.

パラメータ:

key (str or int) -- 参照する制約式名,または追加した制約式の番号.負数の場合,逆順から参照されます.

サンプル

>>> 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=IIS.AUTO):
[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: Constraint) Self#
__iadd__(args: tuple[Constraint, str]) Self
__iadd__(args: tuple[Constraint, ConstraintWeight]) Self
__iadd__(args: tuple[Constraint, str, ConstraintWeight]) Self
__iadd__(args: tuple[Constraint, ConstraintWeight, str]) Self
__iadd__(args: Variable | Expression) Self
__iadd__(args: tuple[Variable | Expression, str]) Self

問題に目的関数・制約式を設定します. 「問題 += 変数・式[, 目的関数名]」で目的関数を設定し,「問題 += 制約式[, 制約式名]」で制約式を追加します. 目的関数には添字が残っていてはいけません. 目的関数を複数設定することは通常できませんが,一旦求解することで再設定できるようになります. 同名の制約式を追加することはできません.

例外:

注釈

目的関数名・制約式名を与えた場合は副作用があります. すなわち,式・制約式の 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=IIS.AUTO):
[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: IndexedDict[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 属性から参照することができます.

戻り値:

求解後に解情報が設定されている場合に真,そうでない場合に偽を返します.

戻り値の型:

bool

注釈

problem.status の値が NuoptStatus.OPTIMAL,NuoptStatus.FEASIBLE の場合は problem.hasSolution() は必ず真を返し,設定されている解情報は実行可能な解の 保証があります. 一方,problem.status がその他の値で problem.hasSolution() が真の場合は, 実行不可能な解が設定されています.

isFeasible() bool#

直前の Problem.solve() で実行可能解が求まったかどうかを返します.

戻り値:

実行可能解が求まった場合に真を返します. 実行可能解が求まっていない場合は偽を返します.

戻り値の型:

bool

注釈

problem.status が NuoptStatus.OPTIMAL または NuoptStatus.FEASIBLE の場合に真を返します. 本メソッドの戻り値が真の場合,本問題で使用している変数の val 属性から 参照できる解情報は実行可能です.

isInfeasible() bool#

直前の Problem.solve() で実行可能解が存在しないと判断されたかどうかを返します.

戻り値:

求解後の実行可能解が存在しないと判断された場合に真, そうでない場合に偽を返します.

戻り値の型:

bool

注釈

problem.status が NuoptStatus.INFEASIBLE の場合に真を返します. 本メソッドの戻り値が真(実行可能解が存在しない場合)で,かつ, problem.hasSolution() も真の場合は,本問題で使用している変数の val 属性には実行不可能な解情報が設定されています.

mpsout(mpsfile: bool | str | os.PathLike[str] | None = True, anonymous: bool = False, initial: bool = False) None#

問題情報を mps 形式でファイル出力します.

パラメータ:
  • mpsfile (None or bool or str or os.PathLike[str]) --

    • None or False: 出力しない.

    • True: 出力する.ファイル名は Problem.name + '.mps' となります.

    • str or os.PathLike[str]: 出力する.ファイル名は mpsfile + '.mps' となります.

  • anonymous (bool) --

    • True: モデル情報を mps ファイルに埋め込まない.

    • False: モデル情報を mps ファイルに埋め込む.

  • initial (bool) --

    • True: 初期値を出力します.

    • False: 初期値を出力しません.

注釈

引数で指定された名前に拡張子 .mps が付与されたファイル名で mps 形式のファイルが 出力されます. ファイル名は絶対パス名,相対パス名のいずれでも指定することができます. 出力される mps ファイルの形式は自由長形式です(固定長形式ではありません). 以下の場合に mps ファイルの出力に失敗します.

  • ファイル名として使用できない文字(: * ? " < > |)が含まれている場合

  • 同名のファイルがすでに存在し,上書きの許可がない場合

  • ファイルシステムに空き容量がない場合

property name: str#

name 属性です.値は文字列の代入により変更できます.

property objective: Variable | 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: ProblemOptions#

求解オプション定数を制御する属性です. 種類と値は help(problem.options) か dir(problem.options) で, 定数値は help(Options) か help(Options.Branch) で確認してください.

property result: 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 | os.PathLike[str] | None = None, iis: Problem.IIS = Problem.IIS.AUTO) 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

注釈

NuoptStatus.OPTIMAL の以外の場合は,Problem.result.errorCode から 詳細なエラー番号を取得することができます. また,Problem.result.errorMessage に最適化のカーネルからの エラーメッセージが設定されている場合があります.

property status: NuoptStatus#

直前の Problem.solve() の結果を表す属性です.

  • NuoptStatus.INITIAL : 求解をしたことがないことを表しています.

  • NuoptStatus.OPTIMAL : 最適解が得られたことを表しています.

  • NuoptStatus.FEASIBLE : 実行可能解が得られたことを表しています.

  • NuoptStatus.INFEASIBLE : 実行可能解が存在しなかったと判定されたことを表しています.

  • NuoptStatus.UNBOUNDED : 非有界であることを表しています.

  • NuoptStatus.DUAL_INFEASIBLE : 双対実行不可能(実行不可能あるいは非有界)であることを表しています.

  • NuoptStatus.UNKNOWN : 上記以外のステータスであることを表しています.

property variables: IndexedDict[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

Added in version 1.1.0: mpsout() が追加されました.

Added in version 1.3.0: variables() が追加されました.

Added in version 1.3.0: __getitem__(), __delitem__() に番号でアクセスできるようになりました.

Added in version 1.4.0: setCallback() が追加されました.

Added in version 1.6.0: mpsout() に引数 anonymous と initial が追加されました.

Added in version 1.6.1: Problem(), solve() の solfile 引数,および mpsout() の mpsfile 引数が path-like-object を受け付けるようになりました.

class pysimple.options.ProblemOptions#

求解オプション定数を表すクラスです.

__dir__() list[str]#

求解オプション定数一覧を表示します.

property branchCut: Cut | None#

導入される切除平面の数の目安.(分枝限定法専用) 値: Cut.OFF, Cut.ON, Cut.AGGRESSIVE

property branchCutoff: float | None#

足切り点.(分枝限定法専用) 値: float

property branchDisconnected: Disconnected | None#

非連結成分検出.(分枝限定法専用) 値: Disconnected.AUTO, Disconnected.OFF, Disconnected.ON

property branchDiving: Diving | None#

ヒューリスティクスサーチ Diving の頻度.(分枝限定法専用) 値: Diving.AUTO, Diving.OFF, Diving.ON, Diving.AGGRESSIVE, Diving.SUPERAGGRESSIVE

property branchFeasPump: FeasPump | None#

ヒューリスティクスサーチ Feasibility Pump の頻度.(分枝限定法専用) 値: FeasPump.AUTO, FeasPump.OFF, FeasPump.ON

property branchGapTolerance: float | None#

上下界値のギャップの閾値.絶対値で設定.(分枝限定法専用) 値: float (-1 以上)

property branchMaxNode: int | None#

探索問題数上限.(分枝限定法専用) 値: int (-1 以上)

property branchMaxSolutionCount: int | None#

整数解取得個数上限.(分枝限定法専用) 値: int (-1 以上)

property branchNodeSelect: NodeSelect | None#

ノード選択.(分枝限定法専用) 値: NodeSelect.AUTO, NodeSelect.BESTDEPTH, NodeSelect.BESTESTIMATE

property branchParallelMethod: ParallelMethod | None#

並列分枝限定法の手法.(分枝限定法専用) 値: ParallelMethod.RACING, ParallelMethod.DETERMINISTIC_RACING, ParallelMethod.SUBTREE

property branchPresolve: Presolve | None#

分枝限定法における前処理.(分枝限定法専用) 値: Presolve.AUTO, Presolve.OFF, Presolve.ON

property branchRelativeGapTolerance: float | None#

上下界値のギャップの閾値.相対値で設定.(分枝限定法専用) 値: float (-1 以上)

property branchRens: Rens | None#

ヒューリスティクスサーチ rens の導入.(分枝限定法専用) 値: Rens.AUTO, Rens.OFF, Rens.ON

property branchRepairIteration: int | None#

解の修復時の反復回収上限.(分枝限定法専用) 値: int (0 以上)

property branchRepairSolution: RepairSolution | None#

ユーザ指定の初期解を元に解の修復をおこなう.(分枝限定法専用) 値: RepairSolution.OFF, RepairSolution.ON, RepairSolution.AGGRESSIVE

property branchRins: Rins | None#

ヒューリスティクスサーチ rins の導入.(分枝限定法専用) 値: Rins.AUTO, Rins.OFF, Rins.ON

property branchUseWcsp: UseWcsp | None#

ヒューリスティクスサーチ wcsp タブーサーチの導入.(分枝限定法専用) 値: UseWcsp.AUTO, UseWcsp.OFF, UseWcsp.ON

property branchUseWls: UseWls | None#

ヒューリスティクスサーチ wls の導入.(分枝限定法専用) 値: UseWls.AUTO, UseWls.OFF, UseWls.ON

property higherCrossover: bool | None#

単体法へのクロスオーバー.(高次内点法専用) 値: False, True

property hsimplexMethod: HsimplexMethod | None#

アルゴリズム hsimplex の具体的な手法.(hsimplex 専用) 値: HsimplexMethod.AUTO, HsimplexMethod.PRIMAL, HsimplexMethod.DUAL

property kktEps: float | None#

KKT 条件の残差停止条件. 値: float (0 より大きい かつ 0.0001 以下)

property maxIteration: int | None#

最大反復回数.(内点法,wcsp,wls) 値: int

property maxMemory: int | None#

メモリ利用量上限(MiB).負の値の場合は,分枝限定法は残り利用可能メモリ(MiB)による制限,wls は無制限と解釈します.(分枝限定法,wls,synthesis) 値: int

property maxTime: float | None#

計算時間上限(秒).(分枝限定法,wcsp,wls,synthesis) 値: float (-1 以上)

property method: 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, Method.SYNTHESIS

property objectiveTarget: float | None#

分枝限定法および wls では目的関数の目標値.目標値よりも良い解を発見した場合は計算を終了します.wcsp ではこの値を目的関数の下(上)限とするソフト制約と解釈します.(分枝限定法,wcsp,wls) 値: float

property randomSeed: int | None#

乱数のシード.(wcsp 専用) 値: int (1 以上)

property scaling: Scaling | None#

スケーリングの種類. 値: Scaling.AUTO, Scaling.OFF, Scaling.ON, Scaling.MINMAX, Scaling.CR

property simplexDualTolerance: float | None#

双対変数の実行可能性判定閾値.(単体法専用) 値: float (0 以上 かつ 0.0001 以下)

property simplexPrimalTolerance: float | None#

主変数の実行可能性判定閾値.(単体法専用) 値: float (0 以上 かつ 0.0001 以下)

property synthesisGapTolerance: float | None#

上下界値のギャップの閾値.絶対値で設定.(synthesis 専用) 値: float (-1 以上)

property synthesisRelativeGapTolerance: float | None#

上下界値のギャップの閾値.相対値で設定.(synthesis 専用) 値: float (-1 以上)

property threads: int | None#

スレッド数.-1 の場合は自動的に設定します.0 は 1 と解釈します.(分枝限定法,wcsp,wls,synthesis) 値: int (-1 以上)

property tryCount: int | None#

試行回数.(wcsp,wls) 値: int (1 以上)

property wcspInitialValueActivation: bool | None#

初期値からの探索.(wcsp 専用) 値: False, True

property wcspPhaseOneMaxIteration: int | None#

制約充足フェーズにおける制約充足フェーズにおける反復回数上限.(wcsp 専用) 値: int (-1 以上)

property wcspPhaseOneMaxTime: int | None#

制約充足フェーズにおける計算時間上限.(wcsp 専用) 値: int (-1 以上)

property wcspPhaseTwoMaxIntervalIteration: int | None#

解更新フェーズにおける解更新間隔反復回数上限.(wcsp 専用) 値: int (-1 以上)

property wcspPhaseTwoMaxIntervalTime: int | None#

解更新フェーズにおける計算時間上限.(wcsp 専用) 値: int (-1 以上)

class pysimple.Options#

ソルバのパラメータを設定するためのクラスです. デフォルト値は Nuorium Optimizer SIMPLEマニュアルの「5. 求解オプション設定 」を参照してください.

class Branch#

分枝限定法の求解オプション定数を表すクラスです.

class Cut(value)#

導入される切除平面の数の目安.(分枝限定法専用)

AGGRESSIVE = 2#
OFF = 0#
ON = 1#
class Disconnected(value)#

非連結成分検出.(分枝限定法専用)

AUTO = -1#
OFF = 0#
ON = 1#
class Diving(value)#

ヒューリスティクスサーチ Diving の頻度.(分枝限定法専用)

AGGRESSIVE = 2#
AUTO = -1#
OFF = 0#
ON = 1#
SUPERAGGRESSIVE = 3#
class FeasPump(value)#

ヒューリスティクスサーチ Feasibility Pump の頻度.(分枝限定法専用)

AUTO = -1#
OFF = 0#
ON = 1#
class NodeSelect(value)#

ノード選択.(分枝限定法専用)

AUTO = -1#
BESTDEPTH = 1#
BESTESTIMATE = 2#
class ParallelMethod(value)#

並列分枝限定法の手法.(分枝限定法専用)

DETERMINISTIC_RACING = 1#
RACING = 0#
SUBTREE = 2#
class Presolve(value)#

分枝限定法における前処理.(分枝限定法専用)

AUTO = -1#
OFF = 0#
ON = 1#
class Rens(value)#

ヒューリスティクスサーチ rens の導入.(分枝限定法専用)

AUTO = -1#
OFF = 0#
ON = 1#
class RepairSolution(value)#

ユーザ指定の初期解を元に解の修復をおこなう.(分枝限定法専用)

AGGRESSIVE = 2#
OFF = 0#
ON = 1#
class Rins(value)#

ヒューリスティクスサーチ rins の導入.(分枝限定法専用)

AUTO = -1#
OFF = 0#
ON = 1#
class UseWcsp(value)#

ヒューリスティクスサーチ wcsp タブーサーチの導入.(分枝限定法専用)

AUTO = -1#
OFF = 0#
ON = 1#
class UseWls(value)#

ヒューリスティクスサーチ wls の導入.(分枝限定法専用)

AUTO = -1#
OFF = 0#
ON = 1#
class HsimplexMethod(value)#

アルゴリズム hsimplex の具体的な手法を表すクラスです.

AUTO = -1#
DUAL = 1#
PRIMAL = 0#
class Method(value)#

求解アルゴリズムの求解オプション定数を表すクラスです.

ASQP = 'asqp'#
AUTO = 'auto'#
BFGS = 'bfgs'#
HIGHER = 'higher'#
HSIMPLEX = 'hsimplex'#
LIPM = 'lipm'#
LSQP = 'lsqp'#
SIMPLEX = 'simplex'#
SYNTHESIS = 'synthesis'#
TIPM = 'tipm'#
TSQP = 'tsqp'#
WCSP = 'wcsp'#
WLS = 'wls'#
class Scaling(value)#

スケーリングの求解オプション定数を表すクラスです.

AUTO = -1#
CR = 3#
MINMAX = 2#
OFF = 0#
ON = 1#

Added in version 1.4.0: 求解オプション定数のクラス構造が変更されました.

class pysimple.NuoptStatus#

ベースクラス: IntEnum

ソルバの計算後の状態値を定義しているクラスです.

DUAL_INFEASIBLE = 5#
ERROR = 7#
FEASIBLE = 2#
INFEASIBLE = 3#
INITIAL = 0#
OPTIMAL = 1#
UNBOUNDED = 4#
UNKNOWN = 6#
class pysimple.problem.Result#

求解後の求解情報を表すクラスです.

property consInfeasibility: float#

制約式の実行不可能性.

property elapseTime: float#

計算時間.Nuorium Optimizer のカーネルが最適化計算を行っている時間です.単位は秒です.

property errorCode: int#

Nuorium Optimizer のエラーコード.最適解が得られた場合は 0 が設定されています. エラーコードは Nuorium Optimizer SIMPLE マニュアルの「 A.1.1 Nuorium Optimizerのエラー/警告メッセージ 」を参照してください.

property errorMessage: str#

エラーメッセージ.Nuorium Optimizer がエラーとなった場合に,それに対応するエラーメッセージが設定されています.

property factCount: int#

行列分解の回数.アルゴリズムとして内点法を選択した時のみ意味を持ちます.

property fevals: int#

制約式の評価回数.アルゴリズムとして内点法を選択した時のみ意味を持ちます.

property hardPenalty: float#

ハード制約のペナルティ(重み×違反量)の合計値.

property iis: IIS#

問題が実行不可能な場合の IIS 情報.IIS 情報がない場合は空の IIS オブジェクトが設定されています.

property infeasibility: float#

実行不可能性.スケーリングを行っている場合はスケールを戻して計算した値になります.

property iters: int#

反復回数.アルゴリズムとして内点法を選択した時のみ意味を持ちます.

property method: str#

求解に用いられた解法.

property nfunc: int#

制約式と目的関数の数.目的関数は必ず 1 であるため,「制約式の数+1」が設定されています.

property nvars: int#

変数の数.

property optValue: float#

目的関数の値.最適解の場合は最適値となります.

property peakPhysicalMemoryUsed: int#

最適化計算で利用された最大物理メモリ量です.単位は MiB です.

property peakVirtualMemoryUsed: int#

最適化計算で利用された最大仮想メモリ量です.単位は MiB です.

property residual: float#

KKT 条件の充足度合い.連続変数の最適化時のみ意味を持ちます.

property semiHardPenalty: float#

セミハード制約のペナルティ(重み×違反量)の合計値.

property softPenalty: float#

ソフト制約のペナルティ(重み×違反量)の合計値.

property tolerance: float#

反復停止条件として実際にどの値が使われたか.アルゴリズムとして内点法を選択した時のみ意味を持ちます.

property varInfeasibility: float#

変数の実行不可能性.

class pysimple.problem.IIS#

ベースクラス: dict[int, IIS.OneIIS]

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.consname: str#

制約式名.

property OneIIS.dual: int | float#

制約式の dual 値.

property OneIIS.formatted: str#

制約式の展開された式表示.

property OneIIS.key: int | float | str | tuple[int | float | str, ...]#

制約式の添字.

property OneIIS.no: int#

制約式番号(0 始まり).

property OneIIS.variables: list[Variable]#

制約式に含まれる変数列.

property OneIIS.violation: int | float#

制約式の違反量.

5.1.7. シリアライズ#

class pysimple.serialize.Serialize#

PySIMPLE オブジェクトをシリアライズするためのクラスです. pickle.dump/dumps でシリアライズ可能なオブジェクトに加え,PySIMPLE オブジェクトをシリアライズできます.

static dump(obj: Any, file: BinaryIO) None#

オブジェクトをバイナリにシリアライズしてファイル出力します.

パラメータ:
  • obj (Any) -- シリアライズするオブジェクト.

  • file (BinaryIO) -- 書き込むファイルオブジェクト

サンプル

>>> 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#

オブジェクトをバイナリにシリアライズして返します.

パラメータ:

obj (Any) -- シリアライズするオブジェクト.

戻り値:

pickle.Pickler をラップしたバイナリを保持するオブジェクトです.

戻り値の型:

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#

シリアライズされたオブジェクトをバイナリファイルから復元します.

パラメータ:

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)
...
static loads(data: Pickler) Any#

シリアライズされたオブジェクトを pysimple.Pickler オブジェクトから復元します.

パラメータ:

data (Pickler) -- シリアライズした Pickler オブジェクト.

戻り値:

シリアライズを復元したオブジェクト.

戻り値の型:

Any

サンプル

>>> x = Variable(name='x')
>>> pkl = Serialize.dumps(x)
>>> pkl
Pickler(version_info(major=1, minor=3, micro=0))
>>> x_ = Serialize.loads(pkl)