def test_changing_variable_names_is_reflected_in_the_solver(self): model = Model(problem=glpk_read_cplex(TESTMODELPATH)) for i, variable in enumerate(model.variables): variable.name = "var" + str(i) self.assertEqual(variable.name, "var" + str(i)) self.assertEqual(glp_get_col_name(model.problem, variable._index), "var" + str(i))
def _MakeMDFProblemDual(self): """Create a CVXOPT problem for finding the Maximal Thermodynamic Driving Force (MDF). Does not set the objective function... leaves that to the caller. Returns: the linear problem object, and the four types of variables as arrays """ A, b, c, w, g, z, u = self._GetDualVariablesAndConstants() x = w + g + z + u lp = Model(name="MDF_DUAL") cnstr_names = ["y_%02d" % j for j in range(self.Nr)] + \ ["l_%02d" % j for j in range(self.Nc)] + \ ["MDF"] constraints = [] for i in range(A.shape[1]): row = [A[j, i] * x[j] for j in range(A.shape[0])] constraints.append( Constraint(sum(row), lb=c[i, 0], ub=c[i, 0], name=cnstr_names[i])) lp.add(constraints) row = [b[i, 0] * x[i] for i in range(A.shape[0])] lp.objective = Objective(sum(row), direction='min') return lp, w, g, z, u
def test_get_primal(self): self.assertEqual(self.var.primal, None) model = Model(problem=glpk_read_cplex(TESTMODELPATH)) model.optimize() for i, j in zip([var.primal for var in model.variables], [ 0.8739215069684306, -16.023526143167608, 16.023526143167604, -14.71613956874283, 14.71613956874283, 4.959984944574658, 4.959984944574657, 4.959984944574658, 3.1162689467973905e-29, 2.926716099010601e-29, 0.0, 0.0, -6.112235045340358e-30, -5.6659435396316186e-30, 0.0, -4.922925402711085e-29, 0.0, 9.282532599166613, 0.0, 6.00724957535033, 6.007249575350331, 6.00724957535033, -5.064375661482091, 1.7581774441067828, 0.0, 7.477381962160285, 0.0, 0.22346172933182767, 45.514009774517454, 8.39, 0.0, 6.007249575350331, 0.0, -4.541857463865631, 0.0, 5.064375661482091, 0.0, 0.0, 2.504309470368734, 0.0, 0.0, -22.809833310204958, 22.809833310204958, 7.477381962160285, 7.477381962160285, 1.1814980932459636, 1.496983757261567, -0.0, 0.0, 4.860861146496815, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.064375661482091, 0.0, 5.064375661482091, 0.0, 0.0, 1.496983757261567, 10.000000000000002, -10.0, 0.0, 0.0, 0.0, 0.0, 0.0, -29.175827135565804, 43.598985311997524, 29.175827135565804, 0.0, 0.0, 0.0, -1.2332237321082153e-29, 3.2148950476847613, 38.53460965051542, 5.064375661482091, 0.0, -1.2812714099825612e-29, -1.1331887079263237e-29, 17.530865429786694, 0.0, 0.0, 0.0, 4.765319193197458, -4.765319193197457, 21.79949265599876, -21.79949265599876, -3.2148950476847613, 0.0, -2.281503094067127, 2.6784818505075303, 0.0 ]): self.assertAlmostEqual(i, j)
def _MakeMDFProblem(self): """Create a CVXOPT problem for finding the Maximal Thermodynamic Driving Force (MDF). Does not set the objective function... leaves that to the caller. Returns: the linear problem object, and the three types of variables as arrays """ A, b, c, y, l = self._GetPrimalVariablesAndConstants() B = Variable('mdf') x = y + l + [B] lp = Model(name="MDF_PRIMAL") cnstr_names = ["driving_force_%02d" % j for j in range(self.Nr_active)] + \ ["covariance_var_ub_%02d" % j for j in range(self.Nr)] + \ ["covariance_var_lb_%02d" % j for j in range(self.Nr)] + \ ["log_conc_ub_%02d" % j for j in range(self.Nc)] + \ ["log_conc_lb_%02d" % j for j in range(self.Nc)] constraints = [] for j in range(A.shape[0]): row = [A[j, i] * x[i] for i in range(A.shape[1])] constraints.append( Constraint(sum(row), ub=b[j, 0], name=cnstr_names[j])) lp.add(constraints) row = [c[i, 0] * x[i] for i in range(c.shape[0])] lp.objective = Objective(sum(row), direction='max') return lp, y, l, B
def setUp(self): self.var1 = var1 = Variable("var1", lb=0, ub=1, type="continuous") self.var2 = var2 = Variable("var2", lb=0, ub=1, type="continuous") self.const1 = const1 = Constraint(0.5 * var1, lb=0, ub=1, name="c1") self.const2 = const2 = Constraint(0.1 * var2 + 0.4 * var1, name="c2") self.model = model = Model() model.add([var1, var2]) model.add([const1, const2]) model.objective = Objective(var1 + var2) model.update() self.json_string = json.dumps(model.to_json())
def load_problem(mps_file): prob_tmp_file = tempfile.mktemp(suffix='.mps') with open(prob_tmp_file, 'wb') as tmp_handle: f = gzip.open(mps_file, 'rb') tmp_handle.write(f.read()) f.close() problem = glp_create_prob() glp_read_mps(problem, GLP_MPS_FILE, None, prob_tmp_file) model = Model(problem=problem) model.configuration.presolve = True model.configuration.verbosity = 3 model.configuration.timeout = 60 * 9 return problem, model
def _GetTotalEnergyProblem(self, min_driving_force=0.0, direction='min'): A, b, _c, y, l = self._GetPrimalVariablesAndConstants() x = y + l + [min_driving_force] lp = Model(name='MDF') constraints = [] for j in range(A.shape[0]): row = [A[j, i] * x[i] for i in range(A.shape[1])] constraints.append( Constraint(sum(row), ub=b[j, 0], name='row_%d' % j)) total_g0 = float(self.fluxes @ self.dG0_r_prime) total_reaction = self.S @ self.fluxes.T row = [total_reaction[i, 0] * x[i] for i in range(self.Nc)] total_g = total_g0 + sum(row) lp.add(constraints) lp.objective = Objective(total_g, direction=direction) return lp
def test_glpk_create_empty_model(self): model = Model(name="empty_problem") self.assertEqual(glp_get_prob_name(model.problem), "empty_problem")
def setUp(self): self.model = Model(problem=glpk_read_cplex(TESTMODELPATH)) self.obj = self.model.objective
def test_netlib(netlib_tar_path=os.path.join(os.path.dirname(__file__), 'data/netlib_lp_problems.tar.gz')): """ Test netlib with glpk interface """ if six.PY3: nose.SkipTest('Skipping because py3') else: with open(os.path.join(os.path.dirname(__file__), 'data/the_final_netlib_results.pcl'), 'rb') as fhandle: THE_FINAL_NETLIB_RESULTS = pickle.load(fhandle) # noinspection PyShadowingNames def read_netlib_sif_glpk(fhandle): tmp_file = tempfile.mktemp(suffix='.mps') with open(tmp_file, 'w') as tmp_handle: content = ''.join([str(s) for s in fhandle if str(s.strip())]) tmp_handle.write(content) fhandle.close() problem = glp_create_prob() glp_read_mps(problem, GLP_MPS_DECK, None, tmp_file) # glp_read_mps(problem, GLP_MPS_FILE, None, tmp_file) return problem def check_dimensions(glpk_problem, model): """ Tests that the glpk problem and the interface model have the same number of rows (constraints) and columns (variables). """ assert glp_get_num_cols(glpk_problem) == len(model.variables) def check_objval(glpk_problem, model_objval): """ Check that ... """ smcp = glp_smcp() smcp.presolve = True glp_simplex(glpk_problem, None) status = glp_get_status(glpk_problem) if status == GLP_OPT: glpk_problem_objval = glp_get_obj_val(glpk_problem) else: glpk_problem_objval = None nose.tools.assert_almost_equal(glpk_problem_objval, model_objval, places=4) def check_objval_against_the_final_netlib_results(netlib_id, model_objval): relative_error = abs(1 - (model_objval / float(THE_FINAL_NETLIB_RESULTS[netlib_id]['Objvalue']))) print(relative_error) nose.tools.assert_true(relative_error < 0.01) # nose.tools.assert_almost_equal(model_objval, float(THE_FINAL_NETLIB_RESULTS[netlib_id]['Objvalue']), places=4) tar = tarfile.open(netlib_tar_path) model_paths_in_tar = glob.fnmatch.filter(tar.getnames(), '*.SIF') for model_path_in_tar in model_paths_in_tar: netlib_id = os.path.basename(model_path_in_tar).replace('.SIF', '') # TODO: get the following problems to work # E226 seems to be a MPS related problem, see http://lists.gnu.org/archive/html/bug-glpk/2003-01/msg00003.html if netlib_id in ('AGG', 'E226', 'SCSD6', 'DFL001'): # def test_skip(netlib_id): # raise SkipTest('Skipping netlib problem %s ...' % netlib_id) # test_skip(netlib_id) # class TestWeirdNetlibProblems(unittest.TestCase): # @unittest.skip('Skipping netlib problem') # def test_fail(): # pass continue # TODO: For now, test only models that are covered by the final netlib results else: if netlib_id not in THE_FINAL_NETLIB_RESULTS.keys(): continue fhandle = tar.extractfile(model_path_in_tar) glpk_problem = read_netlib_sif_glpk(fhandle) model = Model(problem=glpk_problem) model.configuration.presolve = True # model.configuration.verbosity = 3 func = partial(check_dimensions, glpk_problem, model) func.description = "test_netlib_check_dimensions_%s (%s)" % (netlib_id, os.path.basename(str(__file__))) yield func model.optimize() if model.status == 'optimal': model_objval = model.objective.value else: raise Exception('No optimal solution found for netlib model %s' % netlib_id) func = partial(check_objval, glpk_problem, model_objval) func.description = "test_netlib_check_objective_value_%s (%s)" % ( netlib_id, os.path.basename(str(__file__))) yield func func = partial(check_objval_against_the_final_netlib_results, netlib_id, model_objval) func.description = "test_netlib_check_objective_value__against_the_final_netlib_results_%s (%s)" % ( netlib_id, os.path.basename(str(__file__))) yield func