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_constraint_bounds(self):
     inner_prob = self.model.problem
     inner_problem_bounds = [(glp_get_row_lb(inner_prob, i), glp_get_row_ub(inner_prob, i)) for i in
                             range(1, glp_get_num_rows(inner_prob) + 1)]
     bounds = [(constr.lb, constr.ub) for constr in self.model.constraints]
     self.assertEqual(bounds, inner_problem_bounds)
     for constr in self.model.constraints:
         constr.lb = random.uniform(-1000, constr.ub)
         constr.ub = random.uniform(constr.lb, 1000)
     inner_problem_bounds_new = [(glp_get_row_lb(inner_prob, i), glp_get_row_ub(inner_prob, i)) for i in
                                 range(1, glp_get_num_rows(inner_prob) + 1)]
     bounds_new = [(constr.lb, constr.ub) for constr in self.model.constraints]
     self.assertNotEqual(bounds, bounds_new)
     self.assertNotEqual(inner_problem_bounds, inner_problem_bounds_new)
     self.assertEqual(bounds_new, inner_problem_bounds_new)
    def add_rows_with_types(self, types, rhs_vec):
        '''add rows to the LP with the given types

        types is a vector of types: swiglpk.GLP_FX, swiglpk.GLP_UP, or swiglpk.GLP_LO
        rhs_vector is the right-hand-side values of the constriants
        '''

        assert len(types) == len(rhs_vec)

        if isinstance(rhs_vec, list):
            rhs_vec = np.array(rhs_vec, dtype=float)

        assert isinstance(rhs_vec, np.ndarray) and len(rhs_vec.shape) == 1, "expected 1-d right-hand-side vector"

        if rhs_vec.shape[0] > 0:
            num_rows = glpk.glp_get_num_rows(self.lp)

            # create new row for each constraint
            glpk.glp_add_rows(self.lp, len(rhs_vec))
            
            for i, pair in enumerate(zip(rhs_vec, types)):
                rhs, ty = pair

                if ty == glpk.GLP_UP:
                    glpk.glp_set_row_bnds(self.lp, num_rows + i + 1, glpk.GLP_UP, 0, rhs)  # '<=' constraint
                elif ty == glpk.GLP_LO:
                    glpk.glp_set_row_bnds(self.lp, num_rows + i + 1, glpk.GLP_LO, rhs, 0)  # '>=' constraint
                else:
                    assert ty == glpk.GLP_FX

                    glpk.glp_set_row_bnds(self.lp, num_rows + i + 1, glpk.GLP_FX, rhs, rhs)  # '>=' constraint
 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)
     ])
Exemple #5
0
    def get_rhs(self, row_indices=None):
        '''get the rhs vector of the constraints

        row_indices - a list of requested indices (None=all)

        this returns an np.array of rhs values for the requested indices
        '''

        rv = []

        if row_indices is None:
            lp_rows = glpk.glp_get_num_rows(self.lp)
            row_indices = range(lp_rows)

        for row in row_indices:
            row_type = glpk.glp_get_row_type(self.lp, row + 1)

            if row_type in [glpk.GLP_FX, glpk.GLP_UP]:
                limit = glpk.glp_get_row_ub(self.lp, row + 1)
            elif row_type == glpk.GLP_LO:
                limit = glpk.glp_get_row_ub(self.lp, row + 1)
            else:
                raise RuntimeError(
                    "Error: Unsupported type ({}) in getRhs() in row {}".
                    format(row_type, row))

            rv.append(limit)

        return np.array(rv, dtype=float)
Exemple #6
0
    def get_types(self):
        '''get the constraint types. These are swiglpk.GLP_FX, swiglpk.GLP_UP, or swiglpk.GLP_LO'''

        lp_rows = glpk.glp_get_num_rows(self.lp)
        rv = []

        for row in range(lp_rows):
            rv.append(glpk.glp_get_row_type(self.lp, row + 1))

        return rv
    def add_rows_equal_zero(self, num):
        '''add rows to the LP with == 0 constraints'''

        if num > 0:
            num_rows = glpk.glp_get_num_rows(self.lp)

            # create new row for each constraint
            glpk.glp_add_rows(self.lp, num)

            for i in range(num):
                glpk.glp_set_row_bnds(self.lp, num_rows + i + 1, glpk.GLP_FX, 0, 0)  # '== 0' constraints
 def test_change_constraint_bounds(self):
     inner_prob = self.model.problem
     inner_problem_bounds = [
         (glp_get_row_lb(inner_prob, i), glp_get_row_ub(inner_prob, i))
         for i in range(1,
                        glp_get_num_rows(inner_prob) + 1)
     ]
     bounds = [(constr.lb, constr.ub) for constr in self.model.constraints]
     self.assertEqual(bounds, inner_problem_bounds)
     for constr in self.model.constraints:
         constr.lb = random.uniform(-1000, constr.ub)
         constr.ub = random.uniform(constr.lb, 1000)
     inner_problem_bounds_new = [
         (glp_get_row_lb(inner_prob, i), glp_get_row_ub(inner_prob, i))
         for i in range(1,
                        glp_get_num_rows(inner_prob) + 1)
     ]
     bounds_new = [(constr.lb, constr.ub)
                   for constr in self.model.constraints]
     self.assertNotEqual(bounds, bounds_new)
     self.assertNotEqual(inner_problem_bounds, inner_problem_bounds_new)
     self.assertEqual(bounds_new, inner_problem_bounds_new)
Exemple #9
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
Exemple #10
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
Exemple #11
0
    def add_rows_equal(self, rhs_vec):
        '''add rows to the LP with == rhs[i] constraints'''

        num = len(rhs_vec)

        if num > 0:
            num_rows = glpk.glp_get_num_rows(self.lp)

            # create new row for each constraint
            glpk.glp_add_rows(self.lp, num)

            for i, val in enumerate(rhs_vec):
                glpk.glp_set_row_bnds(self.lp, num_rows + i + 1, glpk.GLP_FX,
                                      val, val)  # '== val' constraints
 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)
Exemple #13
0
    def add_rows_less_equal(self, rhs_vec):
        '''add rows to the LP with <= constraints

        rhs_vector is the right-hand-side values of the constriants
        '''

        if isinstance(rhs_vec, list):
            rhs_vec = np.array(rhs_vec, dtype=float)

        assert isinstance(rhs_vec, np.ndarray) and len(rhs_vec.shape) == 1, "expected 1-d right-hand-side vector"

        if rhs_vec.shape[0] > 0:
            num_rows = glpk.glp_get_num_rows(self.lp)

            # create new row for each constraint
            glpk.glp_add_rows(self.lp, len(rhs_vec))

            for i, rhs in enumerate(rhs_vec):
                glpk.glp_set_row_bnds(self.lp, num_rows + i + 1, glpk.GLP_UP, 0, rhs)  # '<=' constraint
Exemple #14
0
    def set_constraint_rhs(self, row_index, rhs):
        '''change an existing constraint's right hand side'''

        rows = glpk.glp_get_num_rows(self.lp)

        assert 0 <= row_index < rows, "Invalid row ({}) in set_constraint_rhs() (lp has {})".format(
            row_index, rows)

        row_type = glpk.glp_get_row_type(self.lp, row_index + 1)

        if row_type == glpk.GLP_UP:
            glpk.glp_set_row_bnds(self.lp, row_index + 1, glpk.GLP_UP, 0, rhs)
        elif row_type == glpk.GLP_LO:
            glpk.glp_set_row_bnds(self.lp, row_index + 1, glpk.GLP_LO, rhs, 0)
        elif row_type == glpk.GLP_FX:
            glpk.glp_set_row_bnds(self.lp, row_index + 1, glpk.GLP_FX, rhs, rhs)
        else:
            raise RuntimeError("Invalid constraint type {} in row {} in set_constraint_rhs()".format(
                row_type, row_index))
    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)
Exemple #16
0
    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)
Exemple #17
0
    def get_num_rows(self):
        'get the number of rows in the lp'

        return glpk.glp_get_num_rows(self.lp)
Exemple #18
0
def get_rates(problem: SwigPyObject) -> Iterable[Tuple[str, float]]:
    for i in range(1, 1 + lp.glp_get_num_rows(problem)):
        yield (
            lp.glp_get_row_name(problem, i),
            lp.glp_mip_row_val(problem, i) / 100,
        )
Exemple #19
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)
Exemple #20
0
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)
Exemple #21
0
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)
Exemple #22
0
    Example
    ----------
    >>> with TemporaryFilename() as tmp_file_name:
    >>>     with open(tmp_file_name, "w") as tmp_file:
    >>>         tmp_file.write(stuff)
    >>>     with open(tmp_file) as tmp_file:
    >>>         stuff = tmp_file.read()
    """
    def __init__(self, suffix="tmp", content=None):
        tmp_file = tempfile.NamedTemporaryFile(suffix=suffix, delete=False, mode="w")
        if content is not None:
            tmp_file.write(content)
        self.name = tmp_file.name
        tmp_file.close()

    def __enter__(self):
        return self.name

    def __exit__(self, type, value, traceback):
        os.remove(self.name)


if __name__ == '__main__':
    from swiglpk import glp_create_prob, glp_read_lp, glp_get_num_rows

    problem = glp_create_prob()
    glp_read_lp(problem, None, "../tests/data/model.lp")
    print("asdf", glp_get_num_rows(problem))
    solution = solve_with_glpsol(problem)
    print(solution['R_Biomass_Ecoli_core_w_GAM'])
    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 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)
    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)
Exemple #26
0
    def __getattr__(self, item):
        try:
            return self._functions[item][0]()
        except KeyError:
            raise AttributeError(
                item +
                " is not an available tolerance parameter with this solver")

    def __setattr__(self, key, value):
        if key not in self._functions:
            raise AttributeError(
                key +
                " is not an available tolerance parameter with this solver")
        self._functions[key][1](value)

    def to_dict(self):
        return {key: getattr(self, key) for key in self._functions.keys()}

    def __dir__(self):
        return list(self._functions)


if __name__ == '__main__':
    from swiglpk import glp_create_prob, glp_read_lp, glp_get_num_rows

    problem = glp_create_prob()
    glp_read_lp(problem, None, "../tests/data/model.lp")
    print("asdf", glp_get_num_rows(problem))
    solution = solve_with_glpsol(problem)
    print(solution['R_Biomass_Ecoli_core_w_GAM'])