Beispiel #1
0
    def __init__(self, **kwargs):
        self._p = swiglpk.glp_create_prob()

        self._variables = {}
        self._constraints = {}

        self._result = None
Beispiel #2
0
    def __init__(self, quadratic_objective=False):
        if quadratic_objective:
            raise Exception('Quadratic objective not supported for GLPK')

        self._lp = glp.glp_create_prob()
        self._smcp = glp.glp_smcp()  # simplex solver control parameters
        glp.glp_init_smcp(self._smcp)
        self._smcp.msg_lev = glp.GLP_MSG_ERR
        self.simplex_iteration_limit = 10000
        self._n_vars = 0
        self._n_eq_constraints = 0

        self._flows = {}
        self._lb = {}
        self._ub = {}
        self._objective = {}
        self._materialCoeffs = defaultdict(list)
        self._materialIdxLookup = {}

        self._eqConstBuilt = False
        self._solved = False

        self.inf = np.inf

        self._lowerBoundDefault = 0
        self._upperBoundDefault = self.inf
Beispiel #3
0
 def _initialize_problem(self):
     self.problem = glp_create_prob()
     glp_create_index(self.problem)
     glp_scale_prob(self.problem, GLP_SF_AUTO)
     if self.name is not None:
         _glpk_validate_id(self.name)
         glp_set_prob_name(self.problem, str(self.name))
Beispiel #4
0
    def __init__(self, **kwargs):
        self._p = swiglpk.glp_create_prob()

        self._variables = {}
        self._constraints = {}

        self._result = None
 def __setstate__(self, repr_dict):
     with TemporaryFilename(suffix=".glpk", content=repr_dict["glpk_repr"]) as tmp_file_name:
         problem = glp_create_prob()
         glp_read_prob(problem, 0, tmp_file_name)
     self.__init__(problem=problem)
     self.configuration = Configuration.clone(repr_dict['config'], problem=self)
     if repr_dict['glpk_status'] == 'optimal':
         self.optimize()  # since the start is an optimal solution, nothing will happen here
	def test_swiglpk(self):
		"""Test the underlying GLPK lib and its SWIG interface based on
		the example from https://github.com/biosustain/swiglpk
		"""
		ia = glp.intArray(1 + 1000)
		ja = glp.intArray(1 + 1000)
		ar = glp.doubleArray(1 + 1000)

		lp = glp.glp_create_prob()
		smcp = glp.glp_smcp()
		glp.glp_init_smcp(smcp)
		smcp.msg_lev = glp.GLP_MSG_ALL  # use GLP_MSG_ERR?

		glp.glp_set_prob_name(lp, "sample")
		glp.glp_set_obj_dir(lp, glp.GLP_MAX)

		glp.glp_add_rows(lp, 3)
		glp.glp_set_row_name(lp, 1, "p")
		glp.glp_set_row_bnds(lp, 1, glp.GLP_UP, 0.0, 100.0)
		glp.glp_set_row_name(lp, 2, "q")
		glp.glp_set_row_bnds(lp, 2, glp.GLP_UP, 0.0, 600.0)
		glp.glp_set_row_name(lp, 3, "r")
		glp.glp_set_row_bnds(lp, 3, glp.GLP_UP, 0.0, 300.0)
		glp.glp_add_cols(lp, 3)
		glp.glp_set_col_name(lp, 1, "x1")
		glp.glp_set_col_bnds(lp, 1, glp.GLP_LO, 0.0, 0.0)
		glp.glp_set_obj_coef(lp, 1, 10.0)
		glp.glp_set_col_name(lp, 2, "x2")
		glp.glp_set_col_bnds(lp, 2, glp.GLP_LO, 0.0, 0.0)
		glp.glp_set_obj_coef(lp, 2, 6.0)
		glp.glp_set_col_name(lp, 3, "x3")
		glp.glp_set_col_bnds(lp, 3, glp.GLP_LO, 0.0, 0.0)
		glp.glp_set_obj_coef(lp, 3, 4.0)

		ia[1] = 1; ja[1] = 1; ar[1] = 1.0  # a[1,1] = 1
		ia[2] = 1; ja[2] = 2; ar[2] = 1.0  # a[1,2] = 1
		ia[3] = 1; ja[3] = 3; ar[3] = 1.0  # a[1,3] = 1
		ia[4] = 2; ja[4] = 1; ar[4] = 10.0  # a[2,1] = 10
		ia[5] = 3; ja[5] = 1; ar[5] = 2.0  # a[3,1] = 2
		ia[6] = 2; ja[6] = 2; ar[6] = 4.0  # a[2,2] = 4
		ia[7] = 3; ja[7] = 2; ar[7] = 2.0  # a[3,2] = 2
		ia[8] = 2; ja[8] = 3; ar[8] = 5.0  # a[2,3] = 5
		ia[9] = 3; ja[9] = 3; ar[9] = 6.0  # a[3,3] = 6

		glp.glp_load_matrix(lp, 9, ia, ja, ar)
		glp.glp_simplex(lp, smcp)

		Z = glp.glp_get_obj_val(lp)
		x1 = glp.glp_get_col_prim(lp, 1)
		x2 = glp.glp_get_col_prim(lp, 2)
		x3 = glp.glp_get_col_prim(lp, 3)

		self.assertAlmostEqual(Z, 733.3333, 4)
		self.assertAlmostEqual(x1, 33.3333, 4)
		self.assertAlmostEqual(x2, 66.6667, 4)
		self.assertAlmostEqual(x3, 0)

		glp.glp_delete_prob(lp)
 def __setstate__(self, repr_dict):
     tmp_file = tempfile.mktemp(suffix=".glpk")
     open(tmp_file, 'w').write(repr_dict['glpk_repr'])
     problem = glp_create_prob()
     glp_read_prob(problem, 0, tmp_file)
     self.__init__(problem=problem)
     self.configuration = Configuration.clone(repr_dict['config'], problem=self)
     if repr_dict['glpk_status'] == 'optimal':
         self.optimize()  # since the start is an optimal solution, nothing will happen here
 def read_netlib_sif_glpk(fhandle):
     tmp_file = tempfile.mktemp(suffix='.mps')
     with open(tmp_file, 'w') as tmp_handle:
         content = ''.join([str(s) for s in fhandle if str(s.strip())])
         tmp_handle.write(content)
         fhandle.close()
     problem = glp_create_prob()
     glp_read_mps(problem, GLP_MPS_DECK, None, tmp_file)
     # glp_read_mps(problem, GLP_MPS_FILE, None, tmp_file)
     return problem
Beispiel #9
0
 def read_netlib_sif_glpk(fhandle):
     tmp_file = tempfile.mktemp(suffix='.mps')
     with open(tmp_file, 'w') as tmp_handle:
         content = ''.join([str(s) for s in fhandle if str(s.strip())])
         tmp_handle.write(content)
         fhandle.close()
     problem = glp_create_prob()
     glp_read_mps(problem, GLP_MPS_DECK, None, tmp_file)
     # glp_read_mps(problem, GLP_MPS_FILE, None, tmp_file)
     return problem
 def __setstate__(self, repr_dict):
     with TemporaryFilename(
             suffix=".glpk",
             content=repr_dict["glpk_repr"]) as tmp_file_name:
         problem = glp_create_prob()
         glp_read_prob(problem, 0, tmp_file_name)
     self.__init__(problem=problem)
     self.configuration = Configuration.clone(repr_dict['config'],
                                              problem=self)
     if repr_dict['glpk_status'] == 'optimal':
         self.optimize(
         )  # since the start is an optimal solution, nothing will happen here
Beispiel #11
0
 def __setstate__(self, repr_dict):
     with TemporaryFilename(suffix=".glpk", content=repr_dict["glpk_repr"]) as tmp_file_name:
         problem = glp_create_prob()
         code = glp_read_prob(problem, 0, tmp_file_name)
         if code != 0:
             with open(tmp_file_name) as tmp_file:
                 invalid_problem = tmp_file.read()
             raise Exception("The GLPK file " + tmp_file_name + " does not seem to contain a valid GLPK problem:\n\n" + invalid_problem)
     self.__init__(problem=problem)
     self.configuration = Configuration.clone(repr_dict['config'], problem=self)
     if repr_dict['glpk_status'] == 'optimal':
         self.optimize()  # since the start is an optimal solution, nothing will happen here
Beispiel #12
0
 def __setstate__(self, repr_dict):
     with TemporaryFilename(suffix=".glpk", content=repr_dict["glpk_repr"]) as tmp_file_name:
         problem = glp_create_prob()
         code = glp_read_prob(problem, 0, tmp_file_name)
         if code != 0:
             with open(tmp_file_name) as tmp_file:
                 invalid_problem = tmp_file.read()
             raise Exception("The GLPK file " + tmp_file_name + " does not seem to contain a valid GLPK problem:\n\n" + invalid_problem)
     self.__init__(problem=problem)
     self.configuration = Configuration.clone(repr_dict['config'], problem=self)
     if repr_dict['glpk_status'] == 'optimal':
         self.optimize()  # since the start is an optimal solution, nothing will happen here
Beispiel #13
0
def glpk_read_cplex(path):
    """Reads cplex file and returns glpk problem.

    Returns
    -------
    glp_prob
        A glpk problems (same type as returned by glp_create_prob)
    """
    from swiglpk import glp_create_prob, glp_read_lp

    problem = glp_create_prob()
    glp_read_lp(problem, None, path)
    return problem
Beispiel #14
0
def glpk_read_cplex(path):
    """Reads cplex file and returns glpk problem.

    Returns
    -------
    glp_prob
        A glpk problems (same type as returned by glp_create_prob)
    """
    from swiglpk import glp_create_prob, glp_read_lp

    problem = glp_create_prob()
    glp_read_lp(problem, None, path)
    return problem
Beispiel #15
0
def _linprog(c, A, b, obj):

    lp = glpk.glp_create_prob()
    glpk.glp_set_obj_dir(lp, obj)

    params = glpk.glp_smcp()
    glpk.glp_init_smcp(params)
    params.msg_lev = glpk.GLP_MSG_OFF  #Only print error messages from GLPK

    num_rows = A.shape[0]
    num_cols = A.shape[1]
    mat_size = num_rows * num_cols

    glpk.glp_add_rows(lp, num_rows)

    for row_ind in range(num_rows):
        glpk.glp_set_row_bnds(lp, row_ind + 1, glpk.GLP_UP, 0.0,
                              float(b[row_ind]))

    glpk.glp_add_cols(lp, num_cols)

    for col_ind in range(num_cols):
        glpk.glp_set_col_bnds(lp, col_ind + 1, glpk.GLP_FR, 0.0, 0.0)
        glpk.glp_set_obj_coef(lp, col_ind + 1, c[col_ind])

    'Swig arrays are used for feeding constraints in GLPK'

    ia, ja, ar = [], [], []
    for i, j in product(range(num_rows), range(num_cols)):
        ia.append(i + 1)
        ja.append(j + 1)
        ar.append(float(A[i][j]))

    ia = glpk.as_intArray(ia)
    ja = glpk.as_intArray(ja)
    ar = glpk.as_doubleArray(ar)

    glpk.glp_load_matrix(lp, mat_size, ia, ja, ar)
    glpk.glp_simplex(lp, params)

    fun = glpk.glp_get_obj_val(lp)
    x = [
        i for i in map(lambda x: glpk.glp_get_col_prim(lp, x + 1),
                       range(num_cols))
    ]

    glpk.glp_delete_prob(lp)
    glpk.glp_free_env()

    return LPSolution(x, fun)
Beispiel #16
0
 def __setstate__(self, repr_dict):
     with tempfile.NamedTemporaryFile(suffix=".glpk",
                                      delete=True) as tmp_file:
         tmp_file_name = tmp_file.name
         with open(tmp_file_name, 'w') as tmp_file:
             tmp_file.write(repr_dict['glpk_repr'])
             problem = glp_create_prob()
         glp_read_prob(problem, 0, tmp_file_name)
     self.__init__(problem=problem)
     self.configuration = Configuration.clone(repr_dict['config'],
                                              problem=self)
     if repr_dict['glpk_status'] == 'optimal':
         self.optimize(
         )  # since the start is an optimal solution, nothing will happen here
def load_problem(mps_file):
    prob_tmp_file = tempfile.mktemp(suffix='.mps')
    with open(prob_tmp_file, 'wb') as tmp_handle:
        f = gzip.open(mps_file, 'rb')
        tmp_handle.write(f.read())
        f.close()

    problem = glp_create_prob()
    glp_read_mps(problem, GLP_MPS_FILE, None, prob_tmp_file)
    model = Model(problem=problem)
    model.configuration.presolve = True
    model.configuration.verbosity = 3
    model.configuration.timeout = 60 * 9
    return problem, model
Beispiel #18
0
    def __init__(self):
        'initialize the lp instance'

        self.lp = glpk.glp_create_prob()  # pylint: disable=invalid-name

        # these are assigned on set_reach_vars()
        self.dims = None
        self.basis_mat_rect = None  # 4-tuple, x, y, w, h
        self.cur_vars_offset = None

        # internal bookkeeping
        self.obj_cols = [
        ]  # columns in the LP with an assigned objective coefficient
        self.names = []  # column names

        self.freeze_attrs()
Beispiel #19
0
    def __init__(self):
        'initialize the lp instance'

        self.lp = glpk.glp_create_prob() # pylint: disable=invalid-name

        # these are assigned on set_reach_vars()
        self.dims = None
        self.basis_mat_pos = None # 2-tuple, row, column (NOT X/Y)
        self.cur_vars_offset = None
        self.input_effects_offsets = None # None or 2-tuple, row of input constraints / col of accumulated input effects

        # internal bookkeeping
        self.obj_cols = [] # columns in the LP with an assigned objective coefficient
        self.names = [] # column names
        self.bm_indices = None # a list of intArray for each row, assigned on set_reach_vars

        self.freeze_attrs()
Beispiel #20
0
    def __init__(self, other_lpi=None):
        'initialize the lp instance'

        self.lp = glpk.glp_create_prob()  # pylint: disable=invalid-name

        if other_lpi is None:
            # internal bookkeeping
            self.names = []  # column names

            # setup lp params
        else:
            # initialize from other lpi
            self.names = other_lpi.names.copy()

            Timers.tic('glp_copy_prob')
            glpk.glp_copy_prob(self.lp, other_lpi.lp, glpk.GLP_OFF)
            Timers.toc('glp_copy_prob')

        self.freeze_attrs()
Beispiel #21
0
def setup_linprog(
    recipes: Dict[str, 'Recipe'],
    min_rates: Optional[Dict[str, float]] = None,
    min_clocks: Optional[Dict[str, int]] = None,
    fixed_clocks: Optional[Dict[str, int]] = None,
) -> SwigPyObject:
    if min_rates is None:
        min_rates = {}
    if min_clocks is None:
        min_clocks = {}
    if fixed_clocks is None:
        fixed_clocks = {}

    resources = sorted({p for r in recipes.values() for p in r.rates.keys()})
    resource_indices: Dict[str,
                           int] = {r: i
                                   for i, r in enumerate(resources, 1)}
    m = len(resources)
    n = len(recipes)

    problem: SwigPyObject = lp.glp_create_prob()
    lp.glp_set_prob_name(problem, 'satisfactory')
    lp.glp_set_obj_name(problem, 'percentage_sum')
    lp.glp_set_obj_dir(problem, lp.GLP_MIN)
    lp.glp_add_rows(problem, m)
    lp.glp_add_cols(problem, n)

    for i, resource in enumerate(resources, 1):
        setup_row(problem, i, resource, min_rates.get(resource, 0))

    for j, recipe in enumerate(recipes.values(), 1):
        setup_col(
            problem,
            j,
            recipe,
            resource_indices,
            min_clocks.get(recipe.name),
            fixed_clocks.get(recipe.name),
        )

    lp.glp_create_index(problem)

    return problem
Beispiel #22
0
    def __init__(self, **kwargs):
        self._p = swiglpk.glp_create_prob()

        self._variables = {}
        self._constraints = {}

        self._do_presolve = True

        # Initialize simplex tolerances to default values
        parm = swiglpk.glp_smcp()
        swiglpk.glp_init_smcp(parm)
        self._feasibility_tolerance = parm.tol_bnd
        self._optimality_tolerance = parm.tol_dj

        # Initialize mip tolerance to default value
        parm = swiglpk.glp_iocp()
        swiglpk.glp_init_iocp(parm)
        self._integrality_tolerance = parm.tol_int

        self._result = None
Beispiel #23
0
    def deserialize(self):
        'deserialize self.lp from a tuple into a glpk_instance'

        assert isinstance(self.lp, tuple)

        Timers.tic('deserialize')

        data, glpk_indices, indptr, rhs, col_bounds = self.lp

        self.lp = glpk.glp_create_prob()

        # add cols
        names = self.names
        self.names = []  # adding columns populates self.names

        num_cols = len(col_bounds)

        for i, (lb, ub) in enumerate(col_bounds):
            name = names[i]

            if ub == np.inf:
                if lb == -np.inf:
                    # free variable
                    self.add_cols([name])
                else:
                    assert lb == 0

                    self.add_positive_cols([name])
            else:
                self.add_double_bounded_cols([name], lb, ub)

        # add rows
        num_rows = len(rhs)
        self.add_rows_less_equal(rhs)

        # set constraints
        shape = (num_rows, num_cols)
        self.set_constraints_csr(data, glpk_indices, indptr, shape)

        Timers.toc('deserialize')
Beispiel #24
0
    def solve_IP(self):
        #clear solution file
        open("lp.sol", "w").close()

        #create the LP
        lp = glpk.glp_create_prob()

        #create the model translator
        tran = glpk.glp_mpl_alloc_wksp()

        #read the model intro translator
        glpk.glp_mpl_read_model(tran, "lp.mod", 0)
        #generate the model
        glpk.glp_mpl_generate(tran, None)
        #build the LP from the model
        glpk.glp_mpl_build_prob(tran, lp)

        #create and init params for MIP solver
        params = glpk.glp_iocp()
        glpk.glp_init_iocp(params)
        params.presolve = glpk.GLP_ON

        #solve the MIP
        glpk.glp_intopt(lp, params)

        #save solution
        #glpk.glp_write_sol(lp,"lp2.sol")
        glpk.glp_mpl_postsolve(tran, lp, glpk.GLP_MIP)

        #free resources
        glpk.glp_mpl_free_wksp(tran)
        glpk.glp_delete_prob(lp)

        #read solution from model
        self.read_solution()

        #delete model and solution files
        os.remove("lp.mod")
        os.remove("lp.sol")
 def from_lp(cls, lp_form):
     problem = glp_create_prob()
     with TemporaryFilename(suffix=".lp", content=lp_form) as tmp_file_name:
         glp_read_lp(problem, None, tmp_file_name)
     model = cls(problem=problem)
     return model
Beispiel #26
0
 def from_lp(cls, lp_form):
     problem = glp_create_prob()
     with TemporaryFilename(suffix=".lp", content=lp_form) as tmp_file_name:
         glp_read_lp(problem, None, tmp_file_name)
     model = cls(problem=problem)
     return model
Beispiel #27
0
def create_minimization_problem():
    glpk.glp_term_out(glpk.GLP_OFF)

    lp = glpk.glp_create_prob()
    glpk.glp_set_obj_dir(lp, glpk.GLP_MIN)
    return lp
Beispiel #28
0
    c2 = Constraint(10 * x1 + 4 * x2 + 5 * x3, ub=600, name='c2')
    c3 = Constraint(2 * x1 + 2 * x2 + 6 * x3, ub=300, name='c3')
    obj = Objective(10 * x1 + 6 * x2 + 4 * x3, direction='max')
    model = Model(name='Simple model')
    model.objective = obj
    model.add([c1, c2, c3])
    status = model.optimize()
    print("status:", model.status)
    print("objective value:", model.objective.value)

    for var_name, var in model.variables.items():
        print(var_name, "=", var.primal)

    print(model)

    problem = glp_create_prob()
    glp_read_lp(problem, None, "tests/data/model.lp")

    solver = Model(problem=problem)
    print(solver.optimize())
    print(solver.objective)

    import time

    t1 = time.time()
    print("pickling")
    pickle_string = pickle.dumps(solver)
    resurrected_solver = pickle.loads(pickle_string)
    t2 = time.time()
    print("Execution time: %s" % (t2 - t1))
Beispiel #29
0
def test_solve_with_glpsol():
    problem = glp_create_prob()
    glp_read_lp(problem, None, TESTMODELPATH)
    glp_create_index(problem)
    result = solve_with_glpsol(problem)
    reference = {
        'M_13dpg_c': ['5', '0', '-0.0471054946649844'],
        'R_ME1': ['2', '0', '-0.00509248590972805'],
        'R_ME2': ['2', '0', '-0.00381936443229605'],
        'R_EX_acald_e': ['2', '0', '-0.0343742798906643'],
        'R_EX_pi_e': ['1', '-3.21489504768477', '0'],
        'R_PTAr': ['1', '0', '0'],
        'M_g6p_c': ['5', '0', '-0.0980303537622649'],
        'R_THD2': ['2', '0', '-0.00127312147743202'],
        'M_s7p_c': ['5', '0', '-0.113307811491449'],
        'M_glu_L_c': ['5', '0', '-0.0700216812587607'],
        'R_TKT1': ['1', '1.49698375726157', '0'],
        'M_glu_L_e': ['5', '0', '-0.0687485597813287'],
        'R_CO2t': ['1', '-22.809833310205', '0'],
        'R_PFL': ['1', '5.31182206840464e-31', '0'],
        'M_nadp_c': ['5', '0', '0.00891185034202407'],
        'R_ICL': ['1', '0', '0'],
        'M_h2o_c': ['5', '0', '-0'],
        'M_amp_c': ['5', '0', '0.0101849718194561'],
        'M_f6p_c': ['5', '0', '-0.0980303537622649'],
        'M_h2o_e': ['5', '0', '-0'],
        'M_ac_c': ['5', '0', '-0.0241893080712082'],
        'M_ac_e': ['5', '0', '-0.0229161865937762'],
        'R_NH4t': ['1', '4.76531919319746', '0'],
        'M_adp_c': ['5', '0', '0.00509248590972805'],
        'M_nh4_e': ['5', '0', '-0'],
        'M_gln_L_c': ['5', '0', '-0.0751141671684887'],
        'M_gln_L_e': ['5', '0', '-0.0700216812587607'],
        'M_succoa_c': ['5', '0', '-0.0547442235295765'],
        'M_nh4_c': ['5', '0', '-0'],
        'R_H2Ot': ['1', '-29.1758271355658', '0'],
        'R_EX_glu_L_e': ['2', '0', '-0.0687485597813287'],
        'M_icit_c': ['5', '0', '-0.0712948027361927'],
        'M_q8h2_c': ['1', '-7.105427357601e-15', '0'],
        'R_FORt2': ['2', '0', '-0.00127312147743201'],
        'R_ADK1': ['1', '0', '0'],
        'M_glx_c': ['5', '0', '-0.0203699436389122'],
        'M_glc_D_e': ['5', '0', '-0.0916647463751049'],
        'M_lac_D_c': ['5', '0', '-0.0420130087552564'],
        'M_lac_D_e': ['5', '0', '-0.0407398872778244'],
        'M_acald_e': ['5', '0', '-0.0343742798906643'],
        'M_acald_c': ['5', '0', '-0.0343742798906643'],
        'R_RPE': ['1', '2.67848185050753', '0'],
        'R_EX_for_e': ['2', '0', '-0.00763872886459208'],
        'M_dhap_c': ['5', '0', '-0.0521979805747125'],
        'M_pyr_c': ['5', '0', '-0.0356474013680963'],
        'M_pyr_e': ['5', '0', '-0.0343742798906643'],
        'M_fdp_c': ['5', '0', '-0.104395961149425'],
        'R_PGM': ['1', '-14.7161395687428', '0'],
        'R_PGL': ['1', '4.95998494457466', '0'],
        'R_PGK': ['1', '-16.0235261431676', '0'],
        'M_3pg_c': ['5', '0', '-0.0420130087552564'],
        'M_coa_c': ['1', '-1.77635683940025e-15', '0'],
        'R_FRD7': ['2', '0', '0'],
        'R_EX_gln_L_e': ['2', '0', '-0.0700216812587607'],
        'R_GLCpts': ['1', '10', '0'],
        'R_SUCCt3': ['1', '0', '0'],
        'R_ATPM': ['2', '8.39', '-0.00509248590972805'],
        'M_succ_e': ['5', '0', '-0.0521979805747125'],
        'M_succ_c': ['5', '0', '-0.0509248590972805'],
        'R_EX_lac_D_e': ['2', '0', '-0.0407398872778244'],
        'R_O2t': ['1', '21.7994926559988', '0'],
        'M_2pg_c': ['5', '0', '-0.0420130087552564'],
        'R_CS': ['1', '6.00724957535033', '0'],
        'R_PDH': ['1', '9.28253259916661', '0'],
        'R_CYTBD': ['1', '43.5989853119975', '0'],
        'R_ETOHt2r': ['1', '-0', '0'],
        'R_FBP': ['2', '0', '-0.00509248590972805'],
        'R_ACKr': ['1', '0', '0'],
        'R_GLUSy': ['2', '0', '-0.00509248590972804'],
        'M_fru_e': ['5', '0', '-0.0916647463751049'],
        'R_G6PDH2r': ['1', '4.95998494457466', '0'],
        'R_EX_co2_e': ['1', '22.809833310205', '0'],
        'R_TKT2': ['1', '1.18149809324596', '0'],
        'R_GLUDy': ['1', '-4.54185746386563', '0'],
        'R_EX_fru_e': ['2', '0', '-0.0916647463751049'],
        'R_NADTRHD': ['2', '0', '-0.001273121477432'],
        'R_PYRt2r': ['1', '-0', '0'],
        'R_FUMt2_2': ['1', '0', '0'],
        'R_SUCDi': ['1', '5.06437566148209', '0'],
        'R_ALCD2x': ['1', '-5.84859702315521e-30', '0'],
        'R_EX_o2_e': ['1', '-21.7994926559988', '0'],
        'M_g3p_c': ['5', '0', '-0.0521979805747125'],
        'R_EX_akg_e': ['2', '0', '-0.0611098309167366'],
        'R_GLUt2r': ['1', '-0', '0'],
        'M_pi_c': ['5', '0', '-0.00127312147743201'],
        'M_pi_e': ['5', '0', '-0'],
        'R_LDH_D': ['1', '0', '0'],
        'M_o2_c': ['5', '0', '-0'],
        'M_atp_c': ['1', '0', '0'],
        'M_o2_e': ['5', '0', '-0'],
        'R_MALt2_2': ['1', '0', '0'],
        'R_FBA': ['1', '7.47738196216028', '0'],
        'M_for_c': ['5', '0', '-0.00763872886459208'],
        'R_EX_pyr_e': ['2', '0', '-0.0343742798906643'],
        'R_EX_h_e': ['1', '17.5308654297867', '0'],
        'R_MALS': ['2', '0', '-0.001273121477432'],
        'M_h_c': ['5', '0', '0.00127312147743201'],
        'M_h_e': ['5', '0', '-0'],
        'R_TALA': ['1', '1.49698375726157', '0'],
        'R_SUCOAS': ['1', '-5.06437566148209', '0'],
        'M_pep_c': ['5', '0', '-0.0420130087552564'],
        'R_ICDHyr': ['1', '6.00724957535033', '0'],
        'R_RPI': ['1', '-2.28150309406713', '0'],
        'M_accoa_c': ['5', '0', '-0.0280086725035043'],
        'R_EX_ac_e': ['2', '0', '-0.0229161865937762'],
        'M_6pgl_c': ['5', '0', '-0.0903916248976729'],
        'R_PFK': ['1', '7.47738196216028', '0'],
        'M_oaa_c': ['5', '0', '-0.0420130087552564'],
        'R_EX_glc_e': ['2', '-10', '-0.0916647463751049'],
        'R_EX_h2o_e': ['1', '29.1758271355658', '0'],
        'M_mal_L_c': ['5', '0', '-0.0483786161424165'],
        'R_EX_nh4_e': ['1', '-4.76531919319746', '0'],
        'M_acon_C_c': ['5', '0', '-0.0712948027361927'],
        'R_ACALDt': ['1', '0', '0'],
        'R_GLNS': ['1', '0.223461729331828', '0'],
        'M_r5p_c': ['5', '0', '-0.0827528960330808'],
        'R_ACONTb': ['1', '6.00724957535033', '0'],
        'M_actp_c': ['5', '0', '-0.0292817939809363'],
        'M_cit_c': ['5', '0', '-0.0712948027361927'],
        'M_mal_L_e': ['5', '0', '-0.0458323731875524'],
        'M_akg_c': ['5', '0', '-0.0623829523941686'],
        'M_akg_e': ['5', '0', '-0.0611098309167366'],
        'R_D_LACt2': ['1', '-0', '0'],
        'R_ATPS4r': ['1', '45.5140097745175', '0'],
        'M_ru5p_D_c': ['5', '0', '-0.0827528960330808'],
        'R_TPI': ['1', '7.47738196216028', '0'],
        'R_PPCK': ['2', '0', '-0.00509248590972805'],
        'R_SUCCt2_2': ['2', '0', '-0.00381936443229604'],
        'M_e4p_c': ['5', '0', '-0.0674754383038966'],
        'R_NADH16': ['1', '38.5346096505154', '0'],
        'R_Biomass_Ecoli_core_w_GAM': ['1', '0.87392150696843', '0'],
        'R_GAPD': ['1', '16.0235261431676', '0'],
        'R_PGI': ['1', '4.86086114649682', '0'],
        'R_GLNabc': ['1', '0', '0'],
        'R_AKGDH': ['1', '5.06437566148209', '0'],
        'R_MDH': ['1', '5.06437566148209', '0'],
        'R_EX_fum_e': ['2', '0', '-0.0458323731875524'],
        'R_PYK': ['1', '1.75817744410678', '0'],
        'M_etoh_c': ['5', '0', '-0.0407398872778244'],
        'M_fum_c': ['5', '0', '-0.0483786161424165'],
        'M_q8_c': ['5', '0', '0.00254624295486403'],
        'M_etoh_e': ['5', '0', '-0.0394667658003924'],
        'M_fum_e': ['5', '0', '-0.0458323731875524'],
        'R_FRUpts2': ['1', '0', '0'],
        'M_nadph_c': ['1', '-8.88178419700125e-16', '0'],
        'R_ENO': ['1', '14.7161395687428', '0'],
        'R_PIt2r': ['1', '3.21489504768477', '0'],
        'R_EX_mal_L_e': ['2', '0', '-0.0458323731875524'],
        'R_ACALD': ['1', '-5.84859702315521e-30', '0'],
        'M_for_e': ['5', '0', '-0.00763872886459208'],
        'M_nad_c': ['5', '0', '0.00763872886459208'],
        'M_6pgc_c': ['5', '0', '-0.0916647463751049'],
        'R_FORti': ['1', '5.31182206840464e-31', '0'],
        'M_co2_c': ['5', '0', '-0'],
        'R_PPS': ['2', '0', '-0.00509248590972805'],
        'M_co2_e': ['5', '0', '-0'],
        'R_EX_succ_e': ['2', '0', '-0.0521979805747125'],
        'R_ACONTa': ['1', '6.00724957535033', '0'],
        'M_nadh_c': ['1', '5.32907051820075e-15', '0'],
        'R_FUM': ['1', '5.06437566148209', '0'],
        'R_GND': ['1', '4.95998494457465', '0'],
        'R_ACt2r': ['1', '-0', '0'],
        'R_PPC': ['1', '2.50430947036873', '0'],
        'R_EX_etoh_e': ['2', '0', '-0.0394667658003924'],
        'R_AKGt2r': ['1', '-0', '0'],
        'R_GLUN': ['2', '0', '-0.00509248590972805']
    }
    for key, val in six.iteritems(result):
        assert val == reference[key]
    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)
Beispiel #31
0
def test_solve_with_glpsol():
    problem = glp_create_prob()
    glp_read_lp(problem, None, TESTMODELPATH)
    glp_create_index(problem)
    result = solve_with_glpsol(problem)
    reference = {'M_13dpg_c': ['5', '0', '-0.0471054946649844'], 'R_ME1': ['2', '0', '-0.00509248590972805'],
                 'R_ME2': ['2', '0', '-0.00381936443229605'], 'R_EX_acald_e': ['2', '0', '-0.0343742798906643'],
                 'R_EX_pi_e': ['1', '-3.21489504768477', '0'], 'R_PTAr': ['1', '0', '0'],
                 'M_g6p_c': ['5', '0', '-0.0980303537622649'], 'R_THD2': ['2', '0', '-0.00127312147743202'],
                 'M_s7p_c': ['5', '0', '-0.113307811491449'], 'M_glu_L_c': ['5', '0', '-0.0700216812587607'],
                 'R_TKT1': ['1', '1.49698375726157', '0'], 'M_glu_L_e': ['5', '0', '-0.0687485597813287'],
                 'R_CO2t': ['1', '-22.809833310205', '0'], 'R_PFL': ['1', '5.31182206840464e-31', '0'],
                 'M_nadp_c': ['5', '0', '0.00891185034202407'], 'R_ICL': ['1', '0', '0'], 'M_h2o_c': ['5', '0', '-0'],
                 'M_amp_c': ['5', '0', '0.0101849718194561'], 'M_f6p_c': ['5', '0', '-0.0980303537622649'],
                 'M_h2o_e': ['5', '0', '-0'], 'M_ac_c': ['5', '0', '-0.0241893080712082'],
                 'M_ac_e': ['5', '0', '-0.0229161865937762'], 'R_NH4t': ['1', '4.76531919319746', '0'],
                 'M_adp_c': ['5', '0', '0.00509248590972805'], 'M_nh4_e': ['5', '0', '-0'],
                 'M_gln_L_c': ['5', '0', '-0.0751141671684887'], 'M_gln_L_e': ['5', '0', '-0.0700216812587607'],
                 'M_succoa_c': ['5', '0', '-0.0547442235295765'], 'M_nh4_c': ['5', '0', '-0'],
                 'R_H2Ot': ['1', '-29.1758271355658', '0'], 'R_EX_glu_L_e': ['2', '0', '-0.0687485597813287'],
                 'M_icit_c': ['5', '0', '-0.0712948027361927'], 'M_q8h2_c': ['1', '-7.105427357601e-15', '0'],
                 'R_FORt2': ['2', '0', '-0.00127312147743201'], 'R_ADK1': ['1', '0', '0'],
                 'M_glx_c': ['5', '0', '-0.0203699436389122'], 'M_glc_D_e': ['5', '0', '-0.0916647463751049'],
                 'M_lac_D_c': ['5', '0', '-0.0420130087552564'], 'M_lac_D_e': ['5', '0', '-0.0407398872778244'],
                 'M_acald_e': ['5', '0', '-0.0343742798906643'], 'M_acald_c': ['5', '0', '-0.0343742798906643'],
                 'R_RPE': ['1', '2.67848185050753', '0'], 'R_EX_for_e': ['2', '0', '-0.00763872886459208'],
                 'M_dhap_c': ['5', '0', '-0.0521979805747125'], 'M_pyr_c': ['5', '0', '-0.0356474013680963'],
                 'M_pyr_e': ['5', '0', '-0.0343742798906643'], 'M_fdp_c': ['5', '0', '-0.104395961149425'],
                 'R_PGM': ['1', '-14.7161395687428', '0'], 'R_PGL': ['1', '4.95998494457466', '0'],
                 'R_PGK': ['1', '-16.0235261431676', '0'], 'M_3pg_c': ['5', '0', '-0.0420130087552564'],
                 'M_coa_c': ['1', '-1.77635683940025e-15', '0'], 'R_FRD7': ['2', '0', '0'],
                 'R_EX_gln_L_e': ['2', '0', '-0.0700216812587607'], 'R_GLCpts': ['1', '10', '0'],
                 'R_SUCCt3': ['1', '0', '0'], 'R_ATPM': ['2', '8.39', '-0.00509248590972805'],
                 'M_succ_e': ['5', '0', '-0.0521979805747125'], 'M_succ_c': ['5', '0', '-0.0509248590972805'],
                 'R_EX_lac_D_e': ['2', '0', '-0.0407398872778244'], 'R_O2t': ['1', '21.7994926559988', '0'],
                 'M_2pg_c': ['5', '0', '-0.0420130087552564'], 'R_CS': ['1', '6.00724957535033', '0'],
                 'R_PDH': ['1', '9.28253259916661', '0'], 'R_CYTBD': ['1', '43.5989853119975', '0'],
                 'R_ETOHt2r': ['1', '-0', '0'], 'R_FBP': ['2', '0', '-0.00509248590972805'], 'R_ACKr': ['1', '0', '0'],
                 'R_GLUSy': ['2', '0', '-0.00509248590972804'], 'M_fru_e': ['5', '0', '-0.0916647463751049'],
                 'R_G6PDH2r': ['1', '4.95998494457466', '0'], 'R_EX_co2_e': ['1', '22.809833310205', '0'],
                 'R_TKT2': ['1', '1.18149809324596', '0'], 'R_GLUDy': ['1', '-4.54185746386563', '0'],
                 'R_EX_fru_e': ['2', '0', '-0.0916647463751049'], 'R_NADTRHD': ['2', '0', '-0.001273121477432'],
                 'R_PYRt2r': ['1', '-0', '0'], 'R_FUMt2_2': ['1', '0', '0'], 'R_SUCDi': ['1', '5.06437566148209', '0'],
                 'R_ALCD2x': ['1', '-5.84859702315521e-30', '0'], 'R_EX_o2_e': ['1', '-21.7994926559988', '0'],
                 'M_g3p_c': ['5', '0', '-0.0521979805747125'], 'R_EX_akg_e':
                     ['2', '0', '-0.0611098309167366'], 'R_GLUt2r': ['1', '-0', '0'],
                 'M_pi_c': ['5', '0', '-0.00127312147743201'],
                 'M_pi_e': ['5', '0', '-0'], 'R_LDH_D': ['1', '0', '0'], 'M_o2_c': ['5', '0', '-0'],
                 'M_atp_c': ['1', '0', '0'], 'M_o2_e': ['5', '0', '-0'], 'R_MALt2_2': ['1', '0', '0'],
                 'R_FBA': ['1', '7.47738196216028', '0'], 'M_for_c': ['5', '0', '-0.00763872886459208'],
                 'R_EX_pyr_e': ['2', '0', '-0.0343742798906643'], 'R_EX_h_e': ['1', '17.5308654297867', '0'],
                 'R_MALS': ['2', '0', '-0.001273121477432'], 'M_h_c': ['5', '0', '0.00127312147743201'],
                 'M_h_e': ['5', '0', '-0'], 'R_TALA': ['1', '1.49698375726157', '0'],
                 'R_SUCOAS': ['1', '-5.06437566148209', '0'], 'M_pep_c': ['5', '0', '-0.0420130087552564'],
                 'R_ICDHyr': ['1', '6.00724957535033', '0'], 'R_RPI': ['1', '-2.28150309406713', '0'],
                 'M_accoa_c': ['5', '0', '-0.0280086725035043'], 'R_EX_ac_e': ['2', '0', '-0.0229161865937762'],
                 'M_6pgl_c': ['5', '0', '-0.0903916248976729'], 'R_PFK': ['1', '7.47738196216028', '0'],
                 'M_oaa_c': ['5', '0', '-0.0420130087552564'], 'R_EX_glc_e': ['2', '-10', '-0.0916647463751049'],
                 'R_EX_h2o_e': ['1', '29.1758271355658', '0'], 'M_mal_L_c': ['5', '0', '-0.0483786161424165'],
                 'R_EX_nh4_e': ['1', '-4.76531919319746', '0'], 'M_acon_C_c': ['5', '0', '-0.0712948027361927'],
                 'R_ACALDt': ['1', '0', '0'], 'R_GLNS': ['1', '0.223461729331828', '0'],
                 'M_r5p_c': ['5', '0', '-0.0827528960330808'], 'R_ACONTb': ['1', '6.00724957535033', '0'],
                 'M_actp_c': ['5', '0', '-0.0292817939809363'], 'M_cit_c': ['5', '0', '-0.0712948027361927'],
                 'M_mal_L_e': ['5', '0', '-0.0458323731875524'], 'M_akg_c': ['5', '0', '-0.0623829523941686'],
                 'M_akg_e': ['5', '0', '-0.0611098309167366'], 'R_D_LACt2': ['1', '-0', '0'],
                 'R_ATPS4r': ['1', '45.5140097745175', '0'], 'M_ru5p_D_c': ['5', '0', '-0.0827528960330808'],
                 'R_TPI': ['1', '7.47738196216028', '0'], 'R_PPCK': ['2', '0', '-0.00509248590972805'],
                 'R_SUCCt2_2': ['2', '0', '-0.00381936443229604'], 'M_e4p_c': ['5', '0', '-0.0674754383038966'],
                 'R_NADH16': ['1', '38.5346096505154', '0'],
                 'R_Biomass_Ecoli_core_w_GAM': ['1', '0.87392150696843', '0'], 'R_GAPD': ['1', '16.0235261431676', '0'],
                 'R_PGI': ['1', '4.86086114649682', '0'], 'R_GLNabc': ['1', '0', '0'],
                 'R_AKGDH': ['1', '5.06437566148209', '0'], 'R_MDH': ['1', '5.06437566148209', '0'],
                 'R_EX_fum_e': ['2', '0', '-0.0458323731875524'], 'R_PYK': ['1', '1.75817744410678', '0'],
                 'M_etoh_c': ['5', '0', '-0.0407398872778244'], 'M_fum_c': ['5', '0', '-0.0483786161424165'],
                 'M_q8_c': ['5', '0', '0.00254624295486403'], 'M_etoh_e': ['5', '0', '-0.0394667658003924'],
                 'M_fum_e': ['5', '0', '-0.0458323731875524'], 'R_FRUpts2': ['1', '0', '0'],
                 'M_nadph_c': ['1', '-8.88178419700125e-16', '0'], 'R_ENO': ['1', '14.7161395687428', '0'],
                 'R_PIt2r': ['1', '3.21489504768477', '0'], 'R_EX_mal_L_e': ['2', '0', '-0.0458323731875524'],
                 'R_ACALD': ['1', '-5.84859702315521e-30', '0'], 'M_for_e': ['5', '0', '-0.00763872886459208'],
                 'M_nad_c': ['5', '0', '0.00763872886459208'], 'M_6pgc_c': ['5', '0', '-0.0916647463751049'],
                 'R_FORti': ['1', '5.31182206840464e-31', '0'], 'M_co2_c': ['5', '0', '-0'],
                 'R_PPS': ['2', '0', '-0.00509248590972805'], 'M_co2_e': ['5', '0', '-0'],
                 'R_EX_succ_e': ['2', '0', '-0.0521979805747125'], 'R_ACONTa': ['1', '6.00724957535033', '0'],
                 'M_nadh_c': ['1', '5.32907051820075e-15', '0'], 'R_FUM': ['1', '5.06437566148209', '0'],
                 'R_GND': ['1', '4.95998494457465', '0'], 'R_ACt2r': ['1', '-0', '0'],
                 'R_PPC': ['1', '2.50430947036873', '0'], 'R_EX_etoh_e': ['2', '0', '-0.0394667658003924'],
                 'R_AKGt2r': ['1', '-0', '0'], 'R_GLUN': ['2', '0', '-0.00509248590972805']}
    for key, val in six.iteritems(result):
        assert val == reference[key]
Beispiel #32
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)
Beispiel #33
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'])
Beispiel #34
0
def solve(nutrition_target, foods):
    '''
    Calculate food amounts to reach the nutrition target
    
    Parameters
    ----------
    nutrition_target : soylent_recipes.nutrition_target.NormalizedNutritionTarget
        The desired nutrition
    foods : np.array
        The foods to use to achieve the nutrition target. Contains exactly the
        nutrients required by the nutrition target in the exact same order. Rows
        represent foods, columns represent nutrients.
        
    Returns
    -------
    amounts : np.array(int) or None
        The amounts of each food to use to optimally achieve the nutrition
        target. ``amounts[i]`` is the amount of the i-th food to use. If the
        nutrition target cannot be achieved, returns None.
    '''
    # Implementation: using the GLPK C library via ecyglpki Python library binding
    # GLPK documentation: download it and look inside the package (http://ftp.gnu.org/gnu/glpk/)
    # GLPK wikibook: https://en.wikibooks.org/wiki/GLPK
    #
    # GPLK lingo: rows and columns refer to Ax=b where b_i are auxiliary
    # variables, x_i are structural variables. Setting constraints on rows, set
    # constraints on b_i, while column constraints are applied to x_i.
    
    # Note: glpk is powerful. We're using mostly the default settings.
    # Performance likely can be improved by tinkering with the settings; or even
    # by providing the solution to the least squares equivalent, with amounts
    # rounded afterwards, as starting point could improve performance.
    
    nutrition_target = nutrition_target.values
    
    problem = glp.glp_create_prob()
    try:
        glp.glp_add_rows(problem, len(nutrition_target))
        glp.glp_add_cols(problem, len(foods))
        
        # Configure columns/amounts
        for i in range(len(foods)):
            glp.glp_set_col_kind(problem, i+1, glp.GLP_IV)  # int
            glp.glp_set_col_bnds(problem, i+1, glp.GLP_LO, 0.0, np.nan)  # >=0
        
        # Configure rows/nutrients
        for i, extrema in enumerate(nutrition_target):
            if np.isnan(extrema[0]):
                bounds_type = glp.GLP_UP
            elif np.isnan(extrema[1]):
                bounds_type = glp.GLP_LO
            else:
                # Note: a nutrition target has either min, max or both and min!=max
                bounds_type = glp.GLP_DB
            glp.glp_set_row_bnds(problem, i+1, bounds_type, *extrema)
            
        # Load A of our Ax=b
        non_zero_count = foods.size
        row_indices = glp.intArray(non_zero_count+1)  # +1 because (insane) 1-indexing
        column_indices = glp.intArray(non_zero_count+1)
        values = glp.doubleArray(non_zero_count+1)
        for i, ((row, column), value) in enumerate(np.ndenumerate(foods.transpose())):
            row_indices[i+1] = row+1
            column_indices[i+1] = column+1
            values[i+1] = value
        glp.glp_load_matrix(problem, non_zero_count, row_indices, column_indices, values)
        
        # Solve
        int_opt_args = glp.glp_iocp()
        glp.glp_init_iocp(int_opt_args)
        int_opt_args.presolve = glp.GLP_ON  # without this, you have to provide an LP relaxation basis
        int_opt_args.msg_lev = glp.GLP_MSG_OFF  # be quiet, no stdout
        glp.glp_intopt(problem, int_opt_args)  # returns an error code; can safely ignore
        
        # Check we've got a valid solution
        #
        # Note: glp_intopt returns whether the algorithm completed successfully.
        # This does not imply you've got a good solution, it could even be
        # infeasible. glp_mip_status returns whether the solution is optimal,
        # feasible, infeasible or undefined. An optimal/feasible solution is not
        # necessarily a good solution. An optimal solution may even violate
        # bounds constraints. The thing you actually need to use is
        # glp_check_kkt and check that the solution satisfies KKT.PB (all within
        # bounds)
        max_error = glp.doubleArray(1)
        glp.glp_check_kkt(problem, glp.GLP_MIP, glp.GLP_KKT_PB, max_error, None, None, None)
        if not np.isclose(max_error[0], 0.0):
            # A row/column value exceeds its bounds
            return None
        
        # Return solution
        amounts = np.fromiter((glp.glp_mip_col_val(problem, i+1) for i in range(len(foods))), int)
        
        return amounts
    finally:
        glp.glp_delete_prob(problem)
Beispiel #35
0
    def _import_problem(self):
        import swiglpk as glpk

        if self.verbosity() >= 1:
            glpk.glp_term_out(glpk.GLP_ON)
        else:
            glpk.glp_term_out(glpk.GLP_OFF)

        # Create a problem instance.
        p = self.int = glpk.glp_create_prob();

        # Set the objective.
        if self.ext.objective[0] in ("find", "min"):
            glpk.glp_set_obj_dir(p, glpk.GLP_MIN)
        elif self.ext.objective[0] is "max":
            glpk.glp_set_obj_dir(p, glpk.GLP_MAX)
        else:
            raise NotImplementedError("Objective '{0}' not supported by GLPK."
                .format(self.ext.objective[0]))

        # Set objective function shift
        if self.ext.objective[1] is not None \
        and self.ext.objective[1].constant is not None:
            if not isinstance(self.ext.objective[1], AffinExp):
                raise NotImplementedError("Non-linear objective function not "
                    "supported by GLPK.")

            if self.ext.objective[1].constant.size != (1,1):
                raise NotImplementedError("Non-scalar objective function not "
                    "supported by GLPK.")

            glpk.glp_set_obj_coef(p, 0, self.ext.objective[1].constant[0])

        # Add variables.
        # Multideminsional variables are split into multiple scalar variables
        # represented as matrix columns within GLPK.
        for varName in self.ext.varNames:
            var = self.ext.variables[varName]

            # Add a column for every scalar variable.
            numCols = var.size[0] * var.size[1]
            glpk.glp_add_cols(p, numCols)

            for localIndex, picosIndex \
            in enumerate(range(var.startIndex, var.endIndex)):
                glpkIndex = self._picos2glpk_variable_index(picosIndex)

                # Assign a name to the scalar variable.
                scalarName = varName
                if numCols > 1:
                    x = localIndex // var.size[0]
                    y = localIndex % var.size[0]
                    scalarName += "_{:d}_{:d}".format(x + 1, y + 1)
                glpk.glp_set_col_name(p, glpkIndex, scalarName)

                # Assign bounds to the scalar variable.
                lower, upper = var.bnd.get(localIndex, (None, None))
                if lower is not None and upper is not None:
                    if lower == upper:
                        glpk.glp_set_col_bnds(
                            p, glpkIndex, glpk.GLP_FX, lower, upper)
                    else:
                        glpk.glp_set_col_bnds(
                            p, glpkIndex, glpk.GLP_DB, lower, upper)
                elif lower is not None and upper is None:
                    glpk.glp_set_col_bnds(p, glpkIndex, glpk.GLP_LO, lower, 0)
                elif lower is None and upper is not None:
                    glpk.glp_set_col_bnds(p, glpkIndex, glpk.GLP_UP, 0, upper)
                else:
                    glpk.glp_set_col_bnds(p, glpkIndex, glpk.GLP_FR, 0, 0)

                # Assign a type to the scalar variable.
                if var.vtype in ("continuous", "symmetric"):
                    glpk.glp_set_col_kind(p, glpkIndex, glpk.GLP_CV)
                elif var.vtype == "integer":
                    glpk.glp_set_col_kind(p, glpkIndex, glpk.GLP_IV)
                elif var.vtype == "binary":
                    glpk.glp_set_col_kind(p, glpkIndex, glpk.GLP_BV)
                else:
                    raise NotImplementedError("Variable type '{0}' not "
                        "supported by GLPK.".format(var.vtype()))

                # Set objective function coefficient of the scalar variable.
                if self.ext.objective[1] is not None \
                and var in self.ext.objective[1].factors:
                    glpk.glp_set_obj_coef(p, glpkIndex,
                        self.ext.objective[1].factors[var][localIndex])

        # Add constraints.
        # Multideminsional constraints are split into multiple scalar
        # constraints represented as matrix rows within GLPK.
        rowOffset = 1
        for constraintNum, constraint in enumerate(self.ext.constraints):
            if not isinstance(constraint, AffineConstraint):
                raise NotImplementedError(
                    "Non-linear constraints not supported by GLPK.")

            # Add a row for every scalar constraint.
            # Internally, GLPK uses an auxiliary variable for every such row,
            # bounded by the right hand side of the scalar constraint in a
            # canonical form.
            numRows = len(constraint)
            glpk.glp_add_rows(p, numRows)

            self._debug("Handling PICOS Constraint: " + str(constraint))

            # Split multidimensional constraints into multiple scalar ones.
            for localConIndex, (glpkVarIndices, coefficients, rhs) in \
                    enumerate(constraint.sparse_Ab_rows(
                    None, indexFunction = lambda picosVar, i:
                    self._picos2glpk_variable_index(picosVar.startIndex + i))):
                # Determine GLPK's row index of the scalar constraint.
                glpkConIndex = rowOffset + localConIndex
                numColumns   = len(glpkVarIndices)

                # Name the auxiliary variable associated with the current row.
                if constraint.name:
                    name = constraint.name
                else:
                    name = "rhs_{:d}".format(constraintNum)
                if numRows > 1:
                    x = localConIndex // constraint.size[0]
                    y = localConIndex % constraint.size[0]
                    name += "_{:d}_{:d}".format(x + 1, y + 1)
                glpk.glp_set_row_name(p, glpkConIndex, name)

                # Assign bounds to the auxiliary variable.
                if constraint.is_equality():
                    glpk.glp_set_row_bnds(p, glpkConIndex, glpk.GLP_FX, rhs,rhs)
                elif constraint.is_increasing():
                    glpk.glp_set_row_bnds(p, glpkConIndex, glpk.GLP_UP, 0, rhs)
                elif constraint.is_decreasing():
                    glpk.glp_set_row_bnds(p, glpkConIndex, glpk.GLP_LO, rhs, 0)
                else:
                    assert False, "Unexpected constraint relation."

                # Set coefficients for current row.
                # Note that GLPK requires a glpk.intArray containing column
                # indices and a glpk.doubleArray of same size containing the
                # coefficients for the listed column index. The first element
                # of both arrays (with index 0) is skipped by GLPK.
                glpkVarIndicesArray = glpk.intArray(numColumns + 1)
                for i in range(numColumns):
                    glpkVarIndicesArray[i + 1] = glpkVarIndices[i]

                coefficientsArray = glpk.doubleArray(numColumns + 1)
                for i in range(numColumns):
                    coefficientsArray[i + 1] = coefficients[i]

                glpk.glp_set_mat_row(p, glpkConIndex, numColumns,
                    glpkVarIndicesArray, coefficientsArray)

            rowOffset += numRows