.. -*- coding: utf-8 -*- PySIMPLE オブジェクトのシリアライズ =================================== Python には,Python オブジェクトをシリアライズ(直列化)できる pickle という機能が 標準で用意されています. PySIMPLE では,pickle と同様に PySIMPLE オブジェクトをシリアライズできる Serialize クラスがあります. 以下では,添字付き変数をシリアライズし,ファイルに dump,復元をしています.:: i = Element(value=[1, 2, 3]) x = Variable(index=i) x[i] = i*10 with open('dump.pkl', 'wb') as f: Serialize.dump(x, f) with open('dump.pkl', 'rb') as g: x_ = Serialize.load(g) print(x_.val) 以下では,Problem オブジェクトをファイルに dump,復元をした後,求解しています. この使用法は求解直前から再開できるため,求解前までに時間を要したり,手間がかかる場合に有効です.:: i = Element(value=[1, 2]) x = Variable(index=i, lb=0, ub=5) problem = Problem() problem += 6*x[1] + x[2] >= 12 problem += 4*x[1] + 6*x[2] >= 24 problem += 180*x[1] + 160*x[2] # Problem をファイルに dump with open('dump.pkl', 'wb') as f: Serialize.dump(problem, f) # 読み込み with open('dump.pkl', 'rb') as g: problem_ = Serialize.load(g) x_ = problem_.variables['x'] problem_.solve(silent=True) print(x_.val) 以下では,求解後に Problem に登録した全ての変数をファイルに dump,復元後,元の変数に値を設定しています. この使用法は求解時の値を簡単に復元できるため,実行可能な初期値を設定する,実行不可能時に以前の値に戻す, といったケースが考えられます.:: i = Element(value=[1, 2]) x = Variable(index=i, lb=0, ub=5) problem = Problem() problem += 6*x[1] + x[2] >= 12 problem += 4*x[1] + 6*x[2] >= 24 problem += 180*x[1] + 160*x[2] problem.solve(silent=True) print(x.val) # Problem に登録した全ての変数をファイルに dump with open('dump.pkl', 'wb') as f: Serialize.dump(list(problem.variables.values()), f) # 変数の値を変える操作 x[i] = 0 print(x.val) # 0 # 読み込み with open('dump.pkl', 'rb') as g: variables = Serialize.load(g) # 元の変数に復元した値を設定 for var1, var2 in zip(problem.variables.values(), variables): # 今回の場合 x[i] = variables[0][i].val と等価 var1[var1.index] = var2[var1.index].val print(x.val) また,Serialize クラスは Python の pickle モジュールのラッパーであるため,Python オブジェクトも シリアライズできます. メソッド一覧は `Serialize` をご確認ください.