コード例 #1
0
 def test_add_non_cplex_conform_variable(self):
     var = self.interface.Variable('12x!!@#5_3', lb=-666, ub=666)
     self.assertEqual(var._index, None)
     self.model.add(var)
     self.assertTrue(var in self.model.variables.values())
     self.assertEqual(var.name, glp_get_col_name(self.model.problem, var._index))
     self.assertEqual(self.model.variables['12x!!@#5_3'].lb, -666)
     self.assertEqual(self.model.variables['12x!!@#5_3'].ub, 666)
     repickled = pickle.loads(pickle.dumps(self.model))
     var_from_pickle = repickled.variables['12x!!@#5_3']
     self.assertEqual(var_from_pickle.name, glp_get_col_name(repickled.problem, var_from_pickle._index))
コード例 #2
0
 def test_add_non_cplex_conform_variable(self):
     var = Variable('12x!!@#5_3', lb=-666, ub=666)
     self.assertEqual(var._index, None)
     self.model.add(var)
     self.assertTrue(var in self.model.variables.values())
     self.assertEqual(var.name,
                      glp_get_col_name(self.model.problem, var._index))
     self.assertEqual(self.model.variables['12x!!@#5_3'].lb, -666)
     self.assertEqual(self.model.variables['12x!!@#5_3'].ub, 666)
     repickled = pickle.loads(pickle.dumps(self.model))
     var_from_pickle = repickled.variables['12x!!@#5_3']
     self.assertEqual(
         var_from_pickle.name,
         glp_get_col_name(repickled.problem, var_from_pickle._index))
コード例 #3
0
    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.")
コード例 #4
0
    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.")
コード例 #5
0
 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))
コード例 #6
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)])
コード例 #7
0
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.')
コード例 #8
0
 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.)
コード例 #9
0
 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.)
コード例 #10
0
 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
コード例 #11
0
 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
コード例 #12
0
ファイル: glpk_interface.py プロジェクト: biosustain/optlang
 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
コード例 #13
0
ファイル: util.py プロジェクト: KristianJensen/optlang
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
コード例 #14
0
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
コード例 #15
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)
     ])
コード例 #16
0
ファイル: glpk_interface.py プロジェクト: hredestig/optlang
 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
コード例 #17
0
    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)
コード例 #18
0
    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)
コード例 #19
0
 def test_changing_variable_names_is_reflected_in_the_solver(self):
     model = self.interface.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))
コード例 #20
0
    def test_add_constraints(self):
        x = self.interface.Variable('x', lb=0, ub=1, type='binary')
        y = self.interface.Variable('y', lb=-181133.3, ub=12000., type='continuous')
        z = self.interface.Variable('z', lb=0., ub=10., type='integer')
        constr1 = self.interface.Constraint(0.3 * x + 0.4 * y + 66. * z, lb=-100, ub=0., name='test')
        constr2 = self.interface.Constraint(2.333 * x + y + 3.333, ub=100.33, name='test2')
        constr3 = self.interface.Constraint(2.333 * x + y + z, lb=-300)
        constr4 = self.interface.Constraint(x, lb=-300, ub=-300)
        constr5 = self.interface.Constraint(3 * x)
        self.model.add(constr1)
        self.model.add(constr2)
        self.model.add(constr3)
        self.model.add([constr4, constr5])
        self.assertIn(constr1.name, self.model.constraints)
        self.assertIn(constr2.name, self.model.constraints)
        self.assertIn(constr3.name, self.model.constraints)
        self.assertIn(constr4.name, self.model.constraints)
        self.assertIn(constr5.name, self.model.constraints)
        # constr1
        ia = intArray(glp_get_num_rows(self.model.problem) + 1)
        da = doubleArray(glp_get_num_rows(self.model.problem) + 1)
        nnz = glp_get_mat_row(self.model.problem, constr1._index, ia, da)
        coeff_dict = dict()
        for i in range(1, nnz + 1):
            coeff_dict[glp_get_col_name(self.model.problem, ia[i])] = da[i]
        self.assertDictEqual(coeff_dict, {'x': 0.3, 'y': 0.4, 'z': 66.})
        self.assertEqual(glp_get_row_type(self.model.problem, constr1._index), GLP_DB)
        self.assertEqual(glp_get_row_lb(self.model.problem, constr1._index), -100)
        self.assertEqual(glp_get_row_ub(self.model.problem, constr1._index), 0)
        # constr2
        ia = intArray(glp_get_num_rows(self.model.problem) + 1)
        da = doubleArray(glp_get_num_rows(self.model.problem) + 1)
        nnz = glp_get_mat_row(self.model.problem, constr2._index, ia, da)
        coeff_dict = dict()
        for i in range(1, nnz + 1):
            coeff_dict[glp_get_col_name(self.model.problem, ia[i])] = da[i]
        self.assertDictEqual(coeff_dict, {'x': 2.333, 'y': 1.})
        self.assertEqual(glp_get_row_type(self.model.problem, constr2._index), GLP_UP)
        self.assertEqual(glp_get_row_lb(self.model.problem, constr2._index), -1.7976931348623157e+308)
        self.assertEqual(glp_get_row_ub(self.model.problem, constr2._index), 96.997)
        # constr3
        ia = intArray(glp_get_num_rows(self.model.problem) + 1)
        da = doubleArray(glp_get_num_rows(self.model.problem) + 1)
        nnz = glp_get_mat_row(self.model.problem, constr3._index, ia, da)
        coeff_dict = dict()
        for i in range(1, nnz + 1):
            coeff_dict[glp_get_col_name(self.model.problem, ia[i])] = da[i]
        self.assertDictEqual(coeff_dict, {'x': 2.333, 'y': 1., 'z': 1.})
        self.assertEqual(glp_get_row_type(self.model.problem, constr3._index), GLP_LO)
        self.assertEqual(glp_get_row_lb(self.model.problem, constr3._index), -300)
        self.assertEqual(glp_get_row_ub(self.model.problem, constr3._index), 1.7976931348623157e+308)
        # constr4
        ia = intArray(glp_get_num_rows(self.model.problem) + 1)
        da = doubleArray(glp_get_num_rows(self.model.problem) + 1)
        nnz = glp_get_mat_row(self.model.problem, constr4._index, ia, da)
        coeff_dict = dict()
        for i in range(1, nnz + 1):
            coeff_dict[glp_get_col_name(self.model.problem, ia[i])] = da[i]
        self.assertDictEqual(coeff_dict, {'x': 1})
        self.assertEqual(glp_get_row_type(self.model.problem, constr4._index), GLP_FX)
        self.assertEqual(glp_get_row_lb(self.model.problem, constr4._index), -300)
        self.assertEqual(glp_get_row_ub(self.model.problem, constr4._index), -300)

        # constr5
        ia = intArray(glp_get_num_rows(self.model.problem) + 1)
        da = doubleArray(glp_get_num_rows(self.model.problem) + 1)
        nnz = glp_get_mat_row(self.model.problem, constr5._index, ia, da)
        coeff_dict = dict()
        for i in range(1, nnz + 1):
            coeff_dict[glp_get_col_name(self.model.problem, ia[i])] = da[i]
        self.assertDictEqual(coeff_dict, {'x': 3})
        self.assertEqual(glp_get_row_type(self.model.problem, constr5._index), GLP_FR)
        self.assertLess(glp_get_row_lb(self.model.problem, constr5._index), -1e30)
        self.assertGreater(glp_get_row_ub(self.model.problem, constr5._index), 1e30)
コード例 #21
0
    def test_add_constraints(self):
        x = Variable('x', lb=0, ub=1, type='binary')
        y = Variable('y', lb=-181133.3, ub=12000., type='continuous')
        z = Variable('z', lb=0., ub=10., type='integer')
        constr1 = Constraint(0.3 * x + 0.4 * y + 66. * z,
                             lb=-100,
                             ub=0.,
                             name='test')
        constr2 = Constraint(2.333 * x + y + 3.333, ub=100.33, name='test2')
        constr3 = Constraint(2.333 * x + y + z, lb=-300)
        constr4 = Constraint(x, lb=-300, ub=-300)
        constr5 = Constraint(3 * x)
        self.model.add(constr1)
        self.model.add(constr2)
        self.model.add(constr3)
        self.model.add([constr4, constr5])
        self.assertIn(constr1.name, self.model.constraints)
        self.assertIn(constr2.name, self.model.constraints)
        self.assertIn(constr3.name, self.model.constraints)
        self.assertIn(constr4.name, self.model.constraints)
        self.assertIn(constr5.name, self.model.constraints)
        # constr1
        ia = intArray(glp_get_num_rows(self.model.problem) + 1)
        da = doubleArray(glp_get_num_rows(self.model.problem) + 1)
        nnz = glp_get_mat_row(self.model.problem, constr1._index, ia, da)
        coeff_dict = dict()
        for i in range(1, nnz + 1):
            coeff_dict[glp_get_col_name(self.model.problem, ia[i])] = da[i]
        self.assertDictEqual(coeff_dict, {'x': 0.3, 'y': 0.4, 'z': 66.})
        self.assertEqual(glp_get_row_type(self.model.problem, constr1._index),
                         GLP_DB)
        self.assertEqual(glp_get_row_lb(self.model.problem, constr1._index),
                         -100)
        self.assertEqual(glp_get_row_ub(self.model.problem, constr1._index), 0)
        # constr2
        ia = intArray(glp_get_num_rows(self.model.problem) + 1)
        da = doubleArray(glp_get_num_rows(self.model.problem) + 1)
        nnz = glp_get_mat_row(self.model.problem, constr2._index, ia, da)
        coeff_dict = dict()
        for i in range(1, nnz + 1):
            coeff_dict[glp_get_col_name(self.model.problem, ia[i])] = da[i]
        self.assertDictEqual(coeff_dict, {'x': 2.333, 'y': 1.})
        self.assertEqual(glp_get_row_type(self.model.problem, constr2._index),
                         GLP_UP)
        self.assertEqual(glp_get_row_lb(self.model.problem, constr2._index),
                         -1.7976931348623157e+308)
        self.assertEqual(glp_get_row_ub(self.model.problem, constr2._index),
                         96.997)
        # constr3
        ia = intArray(glp_get_num_rows(self.model.problem) + 1)
        da = doubleArray(glp_get_num_rows(self.model.problem) + 1)
        nnz = glp_get_mat_row(self.model.problem, constr3._index, ia, da)
        coeff_dict = dict()
        for i in range(1, nnz + 1):
            coeff_dict[glp_get_col_name(self.model.problem, ia[i])] = da[i]
        self.assertDictEqual(coeff_dict, {'x': 2.333, 'y': 1., 'z': 1.})
        self.assertEqual(glp_get_row_type(self.model.problem, constr3._index),
                         GLP_LO)
        self.assertEqual(glp_get_row_lb(self.model.problem, constr3._index),
                         -300)
        self.assertEqual(glp_get_row_ub(self.model.problem, constr3._index),
                         1.7976931348623157e+308)
        # constr4
        ia = intArray(glp_get_num_rows(self.model.problem) + 1)
        da = doubleArray(glp_get_num_rows(self.model.problem) + 1)
        nnz = glp_get_mat_row(self.model.problem, constr4._index, ia, da)
        coeff_dict = dict()
        for i in range(1, nnz + 1):
            coeff_dict[glp_get_col_name(self.model.problem, ia[i])] = da[i]
        self.assertDictEqual(coeff_dict, {'x': 1})
        self.assertEqual(glp_get_row_type(self.model.problem, constr4._index),
                         GLP_FX)
        self.assertEqual(glp_get_row_lb(self.model.problem, constr4._index),
                         -300)
        self.assertEqual(glp_get_row_ub(self.model.problem, constr4._index),
                         -300)

        # constr5
        ia = intArray(glp_get_num_rows(self.model.problem) + 1)
        da = doubleArray(glp_get_num_rows(self.model.problem) + 1)
        nnz = glp_get_mat_row(self.model.problem, constr5._index, ia, da)
        coeff_dict = dict()
        for i in range(1, nnz + 1):
            coeff_dict[glp_get_col_name(self.model.problem, ia[i])] = da[i]
        self.assertDictEqual(coeff_dict, {'x': 3})
        self.assertEqual(glp_get_row_type(self.model.problem, constr5._index),
                         GLP_FR)
        self.assertLess(glp_get_row_lb(self.model.problem, constr5._index),
                        -1e30)
        self.assertGreater(glp_get_row_ub(self.model.problem, constr5._index),
                           1e30)