def test_change_of_objective_is_reflected_in_low_level_solver(self): x = Variable('x', lb=-83.3, ub=1324422.) y = Variable('y', lb=-181133.3, ub=12000.) objective = Objective(0.3 * x + 0.4 * y, name='test', direction='max') self.model.objective = objective self.assertEqual((self.model.objective.expression - (0.4 * y + 0.3 * x)).expand() - 0, 0) self.assertEqual(self.model.objective.direction, "max") self.assertEqual(glp_get_obj_coef(self.model.problem, x._index), 0.3) self.assertEqual(glp_get_obj_coef(self.model.problem, y._index), 0.4) for i in range(1, glp_get_num_cols(self.model.problem) + 1): if i != x._index and i != y._index: self.assertEqual(glp_get_obj_coef(self.model.problem, i), 0) z = Variable('z', lb=4, ub=4, type='integer') self.model.objective += 77. * z self.assertEqual((self.model.objective.expression - (0.4 * y + 0.3 * x + 77.0 * z)).expand() - 0, 0) self.assertEqual(self.model.objective.direction, "max") self.assertEqual(glp_get_obj_coef(self.model.problem, x._index), 0.3) self.assertEqual(glp_get_obj_coef(self.model.problem, y._index), 0.4) self.assertEqual(glp_get_obj_coef(self.model.problem, z._index), 77.) for i in range(1, glp_get_num_cols(self.model.problem) + 1): if i != x._index and i != y._index and i != z._index: self.assertEqual(glp_get_obj_coef(self.model.problem, i), 0)
def test_change_of_objective_is_reflected_in_low_level_solver(self): x = self.interface.Variable('x', lb=-83.3, ub=1324422.) y = self.interface.Variable('y', lb=-181133.3, ub=12000.) objective = self.interface.Objective(0.3 * x + 0.4 * y, name='test', direction='max') self.model.objective = objective self.assertEqual( (self.model.objective.expression - (0.4 * y + 0.3 * x)).expand() - 0, 0 ) self.assertEqual(self.model.objective.direction, "max") self.assertEqual(glp_get_obj_coef(self.model.problem, x._index), 0.3) self.assertEqual(glp_get_obj_coef(self.model.problem, y._index), 0.4) for i in range(1, glp_get_num_cols(self.model.problem) + 1): if i != x._index and i != y._index: self.assertEqual(glp_get_obj_coef(self.model.problem, i), 0) z = self.interface.Variable('z', lb=4, ub=4, type='integer') self.model.objective += 77. * z self.assertEqual( (self.model.objective.expression - (0.4 * y + 0.3 * x + 77.0 * z)).expand() - 0, 0 ) self.assertEqual(self.model.objective.direction, "max") self.assertEqual(glp_get_obj_coef(self.model.problem, x._index), 0.3) self.assertEqual(glp_get_obj_coef(self.model.problem, y._index), 0.4) self.assertEqual(glp_get_obj_coef(self.model.problem, z._index), 77.) for i in range(1, glp_get_num_cols(self.model.problem) + 1): if i != x._index and i != y._index and i != z._index: self.assertEqual(glp_get_obj_coef(self.model.problem, i), 0)
def test_init_from_existing_problem(self): inner_prob = self.model.problem self.assertEqual(len(self.model.variables), glp_get_num_cols(inner_prob)) self.assertEqual(len(self.model.constraints), glp_get_num_rows(inner_prob)) self.assertEqual(self.model.variables.keys(), [glp_get_col_name(inner_prob, i) for i in range(1, glp_get_num_cols(inner_prob) + 1)]) self.assertEqual(self.model.constraints.keys(), [glp_get_row_name(inner_prob, j) for j in range(1, glp_get_num_rows(inner_prob) + 1)])
def test_change_variable_bounds(self): inner_prob = self.model.problem inner_problem_bounds = [(glp_get_col_lb(inner_prob, i), glp_get_col_ub(inner_prob, i)) for i in range(1, glp_get_num_cols(inner_prob) + 1)] bounds = [(var.lb, var.ub) for var in self.model.variables.values()] self.assertEqual(bounds, inner_problem_bounds) for var in self.model.variables.values(): var.lb = random.uniform(-1000, 1000) var.ub = random.uniform(var.lb, 1000) inner_problem_bounds_new = [(glp_get_col_lb(inner_prob, i), glp_get_col_ub(inner_prob, i)) for i in range(1, glp_get_num_cols(inner_prob) + 1)] bounds_new = [(var.lb, var.ub) for var in self.model.variables.values()] self.assertNotEqual(bounds, bounds_new) self.assertNotEqual(inner_problem_bounds, inner_problem_bounds_new) self.assertEqual(bounds_new, inner_problem_bounds_new)
def test_init_from_existing_problem(self): inner_prob = self.model.problem self.assertEqual(len(self.model.variables), glp_get_num_cols(inner_prob)) self.assertEqual(len(self.model.constraints), glp_get_num_rows(inner_prob)) self.assertEqual(self.model.variables.keys(), [ glp_get_col_name(inner_prob, i) for i in range(1, glp_get_num_cols(inner_prob) + 1) ]) self.assertEqual(self.model.constraints.keys(), [ glp_get_row_name(inner_prob, j) for j in range(1, glp_get_num_rows(inner_prob) + 1) ])
def set_linear_coefficients(self, coefficients): if self.problem is not None: problem = self.problem.problem self.problem.update() num_cols = glp_get_num_cols(problem) ia = intArray(num_cols + 1) va = doubleArray(num_cols + 1) num_rows = glp_get_mat_row(self.problem.problem, self._index, ia, va) variables_and_coefficients = {var.name: coeff for var, coeff in six.iteritems(coefficients)} final_variables_and_coefficients = { glp_get_col_name(problem, ia[i]): va[i] for i in range(1, num_rows + 1) } final_variables_and_coefficients.update(variables_and_coefficients) ia = intArray(num_cols + 1) va = doubleArray(num_cols + 1) for i, (name, coeff) in enumerate(six.iteritems(final_variables_and_coefficients)): ia[i + 1] = self.problem._variables[name]._index va[i + 1] = float(coeff) glp_set_mat_row(problem, self._index, len(final_variables_and_coefficients), ia, va) else: raise Exception("Can't change coefficients if constraint is not associated with a model.")
def set_linear_coefficients(self, coefficients): if self.problem is not None: problem = self.problem.problem num_cols = glp_get_num_cols(problem) ia = intArray(num_cols + 1) va = doubleArray(num_cols + 1) num_rows = glp_get_mat_row(self.problem.problem, self._index, ia, va) variables_and_coefficients = {var.name: coeff for var, coeff in six.iteritems(coefficients)} final_variables_and_coefficients = { glp_get_col_name(problem, ia[i]): va[i] for i in range(1, num_rows + 1) } final_variables_and_coefficients.update(variables_and_coefficients) ia = intArray(num_cols + 1) va = doubleArray(num_cols + 1) for i, (name, coeff) in enumerate(six.iteritems(final_variables_and_coefficients)): ia[i + 1] = self.problem._variables[name]._index va[i + 1] = coeff glp_set_mat_row(problem, self._index, len(final_variables_and_coefficients), ia, va) else: raise Exception("Can't change coefficients if constraint is not associated with a model.")
def _add_variables(self, variables): for variable in variables: glp_add_cols(self.problem, 1) index = glp_get_num_cols(self.problem) glp_set_col_name(self.problem, index, str(variable.name)) variable.problem = self self._glpk_set_col_bounds(variable) glp_set_col_kind(self.problem, variable.index, _VTYPE_TO_GLPK_VTYPE[variable.type]) super(Model, self)._add_variables(variables)
def _add_variables(self, variables): for variable in variables: glp_add_cols(self.problem, 1) index = glp_get_num_cols(self.problem) glp_set_col_name(self.problem, index, str(variable.name)) variable.problem = self self._glpk_set_col_bounds(variable) glp_set_col_kind(self.problem, variable._index, _VTYPE_TO_GLPK_VTYPE[variable.type]) super(Model, self)._add_variables(variables)
def get_num_cols(self): 'get the number of columns in the lp' cols = glpk.glp_get_num_cols(self.lp) assert cols == len( self.names ), f"lp had {cols} columns, but names list had {len(self.names)} names" return cols
def get_clocks(problem: SwigPyObject) -> Iterable[Tuple[str, float]]: n_recipes = 0 for j in range(1, 1 + lp.glp_get_num_cols(problem)): clock = lp.glp_mip_col_val(problem, j) if clock: name = lp.glp_get_col_name(problem, j) yield name, clock n_recipes += 1 logger.info(f'{n_recipes} recipes in rate solution.')
def test_set_linear_coefficients_constraint(self): constraint = self.model.constraints.M_atp_c constraint.set_linear_coefficients({self.model.variables.R_Biomass_Ecoli_core_w_GAM: 666.}) num_cols = glp_get_num_cols(self.model.problem) ia = intArray(num_cols + 1) da = doubleArray(num_cols + 1) index = constraint._index num = glp_get_mat_row(self.model.problem, index, ia, da) for i in range(1, num + 1): col_name = glp_get_col_name(self.model.problem, ia[i]) if col_name == 'R_Biomass_Ecoli_core_w_GAM': self.assertEqual(da[i], 666.)
def _get_expression(self): if self.problem is not None: col_num = glp_get_num_cols(self.problem.problem) ia = intArray(col_num + 1) da = doubleArray(col_num + 1) nnz = glp_get_mat_row(self.problem.problem, self.index, ia, da) constraint_variables = [self.problem._variables[glp_get_col_name(self.problem.problem, ia[i])] for i in range(1, nnz + 1)] expression = sympy.Add._from_args( [sympy.Mul._from_args((sympy.RealNumber(da[i]), constraint_variables[i - 1])) for i in range(1, nnz + 1)]) self._expression = expression return self._expression
def _get_expression(self): if self.problem is not None: col_num = glp_get_num_cols(self.problem.problem) ia = intArray(col_num + 1) da = doubleArray(col_num + 1) nnz = glp_get_mat_row(self.problem.problem, self._index, ia, da) constraint_variables = [self.problem._variables[glp_get_col_name(self.problem.problem, ia[i])] for i in range(1, nnz + 1)] expression = symbolics.add( [symbolics.mul((symbolics.Real(da[i]), constraint_variables[i - 1])) for i in range(1, nnz + 1)]) self._expression = expression return self._expression
def test_set_linear_coefficients_constraint(self): constraint = self.model.constraints.M_atp_c constraint.set_linear_coefficients( {self.model.variables.R_Biomass_Ecoli_core_w_GAM: 666.}) num_cols = glp_get_num_cols(self.model.problem) ia = intArray(num_cols + 1) da = doubleArray(num_cols + 1) index = constraint._index num = glp_get_mat_row(self.model.problem, index, ia, da) for i in range(1, num + 1): col_name = glp_get_col_name(self.model.problem, ia[i]) if col_name == 'R_Biomass_Ecoli_core_w_GAM': self.assertEqual(da[i], 666.)
def test_change_variable_bounds(self): inner_prob = self.model.problem inner_problem_bounds = [ (glp_get_col_lb(inner_prob, i), glp_get_col_ub(inner_prob, i)) for i in range(1, glp_get_num_cols(inner_prob) + 1) ] bounds = [(var.lb, var.ub) for var in self.model.variables.values()] self.assertEqual(bounds, inner_problem_bounds) for var in self.model.variables.values(): var.lb = random.uniform(-1000, 1000) var.ub = random.uniform(var.lb, 1000) inner_problem_bounds_new = [ (glp_get_col_lb(inner_prob, i), glp_get_col_ub(inner_prob, i)) for i in range(1, glp_get_num_cols(inner_prob) + 1) ] bounds_new = [(var.lb, var.ub) for var in self.model.variables.values()] self.assertNotEqual(bounds, bounds_new) self.assertNotEqual(inner_problem_bounds, inner_problem_bounds_new) self.assertEqual(bounds_new, inner_problem_bounds_new)
def solve_with_glpsol(glp_prob): """Solve glpk problem with glpsol commandline solver. Mainly for testing purposes. # Examples # -------- # >>> problem = glp_create_prob() # ... glp_read_lp(problem, None, "../tests/data/model.lp") # ... solution = solve_with_glpsol(problem) # ... print 'asdf' # 'asdf' # >>> print solution # 0.839784 # Returns # ------- # dict # A dictionary containing the objective value (key ='objval') # and variable primals. """ from swiglpk import glp_get_row_name, glp_get_col_name, glp_write_lp, glp_get_num_rows, glp_get_num_cols row_ids = [glp_get_row_name(glp_prob, i) for i in range(1, glp_get_num_rows(glp_prob) + 1)] col_ids = [glp_get_col_name(glp_prob, i) for i in range(1, glp_get_num_cols(glp_prob) + 1)] with tempfile.NamedTemporaryFile(suffix=".lp", delete=True) as tmp_file: tmp_file_name = tmp_file.name glp_write_lp(glp_prob, None, tmp_file_name) cmd = ['glpsol', '--lp', tmp_file_name, '-w', tmp_file_name + '.sol', '--log', '/dev/null'] term = check_output(cmd) log.info(term) try: with open(tmp_file_name + '.sol') as sol_handle: # print sol_handle.read() solution = dict() for i, line in enumerate(sol_handle.readlines()): if i <= 1 or line == '\n': pass elif i <= len(row_ids): solution[row_ids[i - 2]] = line.strip().split(' ') elif i <= len(row_ids) + len(col_ids) + 1: solution[col_ids[i - 2 - len(row_ids)]] = line.strip().split(' ') else: print(i) print(line) raise Exception("Argggh!") finally: os.remove(tmp_file_name + ".sol") return solution
def get_linear_coefficients(self, variables): if self.problem is not None: num_cols = glp_get_num_cols(self.problem.problem) ia = intArray(num_cols + 1) da = doubleArray(num_cols + 1) nnz = glp_get_mat_row(self.problem.problem, self._index, ia, da) return { self.problem._variables[ia[i + 1] - 1]: da[i + 1] for i in range(nnz) } else: raise Exception( "Can't get coefficients from solver if constraint is not in a model" )
def get_linear_coefficients(self, variables): if self.problem is not None: self.problem.update() num_cols = glp_get_num_cols(self.problem.problem) ia = intArray(num_cols + 1) da = doubleArray(num_cols + 1) nnz = glp_get_mat_row(self.problem.problem, self._index, ia, da) coefs = dict.fromkeys(variables, 0.0) coefs.update({ self.problem._variables[ia[i + 1] - 1]: da[i + 1] for i in range(nnz) if self.problem._variables[ia[i + 1] - 1] in variables}) return coefs else: raise Exception("Can't get coefficients from solver if constraint is not in a model")
def _add_constraints(self, constraints, sloppy=False): super(Model, self)._add_constraints(constraints, sloppy=sloppy) for constraint in constraints: constraint._problem = None # This needs to be dones in order to not trigger constraint._get_expression() glp_add_rows(self.problem, 1) index = glp_get_num_rows(self.problem) glp_set_row_name(self.problem, index, str(constraint.name)) num_cols = glp_get_num_cols(self.problem) index_array = intArray(num_cols + 1) value_array = doubleArray(num_cols + 1) num_vars = 0 # constraint.variables is too expensive for large problems if constraint.expression.is_Atom and constraint.expression.is_Symbol: var = constraint.expression index_array[1] = var.index value_array[1] = 1 num_vars += 1 elif constraint.expression.is_Mul: args = constraint.expression.args if len(args) > 2: raise Exception( "Term(s) %s from constraint %s is not a proper linear term." % (args, constraint)) coeff = float(args[0]) var = args[1] index_array[1] = var.index value_array[1] = coeff num_vars += 1 else: for i, term in enumerate(constraint.expression.args): args = term.args if args == (): assert term.is_Symbol coeff = 1 var = term elif len(args) == 2: assert args[0].is_Number assert args[1].is_Symbol var = args[1] coeff = float(args[0]) elif len(args) > 2: raise Exception( "Term %s from constraint %s is not a proper linear term." % (term, constraint)) index_array[i + 1] = var.index value_array[i + 1] = coeff num_vars += 1 glp_set_mat_row(self.problem, index, num_vars, index_array, value_array) constraint._problem = self self._glpk_set_row_bounds(constraint)
def _get_expression(self): if self.problem is not None: col_num = glp_get_num_cols(self.problem.problem) ia = intArray(col_num + 1) da = doubleArray(col_num + 1) nnz = glp_get_mat_row(self.problem.problem, self.index, ia, da) constraint_variables = [ self.problem._variables[glp_get_col_name( self.problem.problem, ia[i])] for i in range(1, nnz + 1) ] expression = sympy.Add._from_args([ sympy.Mul._from_args( (sympy.RealNumber(da[i]), constraint_variables[i - 1])) for i in range(1, nnz + 1) ]) self._expression = expression return self._expression
def set_objective(self, expression): """Set objective of problem.""" if isinstance(expression, numbers.Number): # Allow expressions with no variables as objective, # represented as a number expression = Expression(offset=expression) # Clear previous objective for i in range(swiglpk.glp_get_num_cols(self._p)): swiglpk.glp_set_obj_coef(self._p, 1 + i, 0) for variable, value in expression.values(): var_index = self._variables[variable] swiglpk.glp_set_obj_coef(self._p, var_index, value) swiglpk.glp_set_obj_coef(self._p, 0, expression.offset)
def _set_coefficients_low_level(self, variables_coefficients_dict): if self.problem is not None: problem = self.problem.problem indices_coefficients_dict = dict( [(variable.index, coefficient) for variable, coefficient in six.iteritems(variables_coefficients_dict)]) num_cols = glp_get_num_cols(problem) ia = intArray(num_cols + 1) da = doubleArray(num_cols + 1) index = self.index num = glp_get_mat_row(self.problem.problem, index, ia, da) for i in range(1, num + 1): try: da[i] = indices_coefficients_dict[ia[i]] except KeyError: pass glp_set_mat_row(self.problem.problem, index, num, ia, da) else: raise Exception( '_set_coefficients_low_level works only if a constraint is associated with a solver instance.')
def _add_constraints(self, constraints, sloppy=False): super(Model, self)._add_constraints(constraints, sloppy=sloppy) for constraint in constraints: constraint._problem = None # This needs to be done in order to not trigger constraint._get_expression() glp_add_rows(self.problem, 1) index = glp_get_num_rows(self.problem) glp_set_row_name(self.problem, index, str(constraint.name)) num_cols = glp_get_num_cols(self.problem) index_array = intArray(num_cols + 1) value_array = doubleArray(num_cols + 1) num_vars = 0 # constraint.variables is too expensive for large problems offset, coef_dict, _ = parse_optimization_expression(constraint, linear=True) num_vars = len(coef_dict) for i, (var, coef) in enumerate(coef_dict.items()): index_array[i + 1] = var._index value_array[i + 1] = float(coef) glp_set_mat_row(self.problem, index, num_vars, index_array, value_array) constraint._problem = self self._glpk_set_row_bounds(constraint)
def _add_constraints(self, constraints, sloppy=False): super(Model, self)._add_constraints(constraints, sloppy=sloppy) for constraint in constraints: constraint._problem = None # This needs to be done in order to not trigger constraint._get_expression() glp_add_rows(self.problem, 1) index = glp_get_num_rows(self.problem) glp_set_row_name(self.problem, index, str(constraint.name)) num_cols = glp_get_num_cols(self.problem) index_array = intArray(num_cols + 1) value_array = doubleArray(num_cols + 1) num_vars = 0 # constraint.variables is too expensive for large problems coef_dict, _ = parse_optimization_expression(constraint, linear=True) num_vars = len(coef_dict) for i, (var, coef) in enumerate(coef_dict.items()): index_array[i + 1] = var._index value_array[i + 1] = float(coef) glp_set_mat_row(self.problem, index, num_vars, index_array, value_array) constraint._problem = self self._glpk_set_row_bounds(constraint)
def _initialize_model_from_problem(self, problem): try: self.problem = problem glp_create_index(self.problem) except TypeError: raise TypeError("Provided problem is not a valid GLPK model.") row_num = glp_get_num_rows(self.problem) col_num = glp_get_num_cols(self.problem) for i in range(1, col_num + 1): var = Variable( glp_get_col_name(self.problem, i), lb=glp_get_col_lb(self.problem, i), ub=glp_get_col_ub(self.problem, i), problem=self, type=_GLPK_VTYPE_TO_VTYPE[ glp_get_col_kind(self.problem, i)] ) # This avoids adding the variable to the glpk problem super(Model, self)._add_variables([var]) variables = self.variables for j in range(1, row_num + 1): ia = intArray(col_num + 1) da = doubleArray(col_num + 1) nnz = glp_get_mat_row(self.problem, j, ia, da) constraint_variables = [variables[ia[i] - 1] for i in range(1, nnz + 1)] # Since constraint expressions are lazily retrieved from the solver they don't have to be built here # lhs = _unevaluated_Add(*[da[i] * constraint_variables[i - 1] # for i in range(1, nnz + 1)]) lhs = 0 glpk_row_type = glp_get_row_type(self.problem, j) if glpk_row_type == GLP_FX: row_lb = glp_get_row_lb(self.problem, j) row_ub = row_lb elif glpk_row_type == GLP_LO: row_lb = glp_get_row_lb(self.problem, j) row_ub = None elif glpk_row_type == GLP_UP: row_lb = None row_ub = glp_get_row_ub(self.problem, j) elif glpk_row_type == GLP_DB: row_lb = glp_get_row_lb(self.problem, j) row_ub = glp_get_row_ub(self.problem, j) elif glpk_row_type == GLP_FR: row_lb = None row_ub = None else: raise Exception( "Currently, optlang does not support glpk row type %s" % str(glpk_row_type) ) log.exception() if isinstance(lhs, int): lhs = symbolics.Integer(lhs) elif isinstance(lhs, float): lhs = symbolics.Real(lhs) constraint_id = glp_get_row_name(self.problem, j) for variable in constraint_variables: try: self._variables_to_constraints_mapping[variable.name].add(constraint_id) except KeyError: self._variables_to_constraints_mapping[variable.name] = set([constraint_id]) super(Model, self)._add_constraints( [Constraint(lhs, lb=row_lb, ub=row_ub, name=constraint_id, problem=self, sloppy=True)], sloppy=True ) term_generator = ( (glp_get_obj_coef(self.problem, index), variables[index - 1]) for index in range(1, glp_get_num_cols(problem) + 1) ) self._objective = Objective( symbolics.add( [symbolics.mul((symbolics.Real(term[0]), term[1])) for term in term_generator if term[0] != 0.] ), problem=self, direction={GLP_MIN: 'min', GLP_MAX: 'max'}[glp_get_obj_dir(self.problem)]) glp_scale_prob(self.problem, GLP_SF_AUTO)
def term_generator(): for index in range(1, glp_get_num_cols(self.problem.problem) + 1): coeff = glp_get_obj_coef(self.problem.problem, index) if coeff != 0.: yield (symbolics.Real(coeff), variables[index - 1])
def __init__(self, problem=None, *args, **kwargs): super(Model, self).__init__(*args, **kwargs) self.configuration = Configuration() if problem is None: self.problem = glp_create_prob() glp_create_index(self.problem) if self.name is not None: glp_set_prob_name(self.problem, str(self.name)) else: try: self.problem = problem glp_create_index(self.problem) except TypeError: raise TypeError("Provided problem is not a valid GLPK model.") row_num = glp_get_num_rows(self.problem) col_num = glp_get_num_cols(self.problem) for i in range(1, col_num + 1): var = Variable( glp_get_col_name(self.problem, i), lb=glp_get_col_lb(self.problem, i), ub=glp_get_col_ub(self.problem, i), problem=self, type=_GLPK_VTYPE_TO_VTYPE[ glp_get_col_kind(self.problem, i)] ) # This avoids adding the variable to the glpk problem super(Model, self)._add_variables([var]) variables = self.variables for j in range(1, row_num + 1): ia = intArray(col_num + 1) da = doubleArray(col_num + 1) nnz = glp_get_mat_row(self.problem, j, ia, da) constraint_variables = [variables[ia[i] - 1] for i in range(1, nnz + 1)] # Since constraint expressions are lazily retrieved from the solver they don't have to be built here # lhs = _unevaluated_Add(*[da[i] * constraint_variables[i - 1] # for i in range(1, nnz + 1)]) lhs = 0 glpk_row_type = glp_get_row_type(self.problem, j) if glpk_row_type == GLP_FX: row_lb = glp_get_row_lb(self.problem, j) row_ub = row_lb elif glpk_row_type == GLP_LO: row_lb = glp_get_row_lb(self.problem, j) row_ub = None elif glpk_row_type == GLP_UP: row_lb = None row_ub = glp_get_row_ub(self.problem, j) elif glpk_row_type == GLP_DB: row_lb = glp_get_row_lb(self.problem, j) row_ub = glp_get_row_ub(self.problem, j) elif glpk_row_type == GLP_FR: row_lb = None row_ub = None else: raise Exception( "Currently, optlang does not support glpk row type %s" % str(glpk_row_type) ) log.exception() if isinstance(lhs, int): lhs = sympy.Integer(lhs) elif isinstance(lhs, float): lhs = sympy.RealNumber(lhs) constraint_id = glp_get_row_name(self.problem, j) for variable in constraint_variables: try: self._variables_to_constraints_mapping[variable.name].add(constraint_id) except KeyError: self._variables_to_constraints_mapping[variable.name] = set([constraint_id]) super(Model, self)._add_constraints( [Constraint(lhs, lb=row_lb, ub=row_ub, name=constraint_id, problem=self, sloppy=True)], sloppy=True ) term_generator = ( (glp_get_obj_coef(self.problem, index), variables[index - 1]) for index in range(1, glp_get_num_cols(problem) + 1) ) self._objective = Objective( _unevaluated_Add( *[_unevaluated_Mul(sympy.RealNumber(term[0]), term[1]) for term in term_generator if term[0] != 0.]), problem=self, direction={GLP_MIN: 'min', GLP_MAX: 'max'}[glp_get_obj_dir(self.problem)]) glp_scale_prob(self.problem, GLP_SF_AUTO)
def term_generator(): for index in range(1, glp_get_num_cols(self.problem.problem) + 1): coeff = glp_get_obj_coef(self.problem.problem, index) if coeff != 0.: yield (sympy.RealNumber(coeff), variables[index - 1])
def test_glpk_read_cplex(): problem = glpk_read_cplex(TESTMODELPATH) nose.tools.assert_equal(glp_get_num_rows(problem), 72) nose.tools.assert_equal(glp_get_num_cols(problem), 95)
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_dimensions(model, glpk_problem): nose.tools.assert_true(glp_get_num_cols(glpk_problem) == len(model.variables))