Esempio n. 1
0
    def FindOBD(self):
        """Find the OBD (Optimized Bottleneck Energetics).
       
        Args:
            c_range: a tuple (min, max) for concentrations (in M).
            bounds: a list of (lower bound, upper bound) tuples for compound
                concentrations.
       
        Returns:
            A 3 tuple (optimal dGfs, optimal concentrations, optimal obd).
        """
        lp_primal, x, _ = self._MakeOBDProblem()
        lp_primal.solve(pulp.CPLEX(msg=0))
        if lp_primal.status != pulp.LpStatusOptimal:
            raise pulp.solvers.PulpSolverError("cannot solve OBD primal")
            
        obd = pulp.value(x[-1])
        conc = np.matrix([np.exp(pulp.value(x[j])) for j in xrange(self.Nc)]).T

        lp_dual, w, z, u = self._MakeOBDProblemDual()
        lp_dual.solve(pulp.CPLEX(msg=0))
        if lp_dual.status != pulp.LpStatusOptimal:
            raise pulp.solvers.PulpSolverError("cannot solve OBD dual")
        reaction_prices = np.matrix([pulp.value(w["%d" % i]) for i in xrange(self.Nr)]).T
        compound_prices = np.matrix([pulp.value(z["%d" % j]) for j in xrange(self.Nc)]).T - \
                          np.matrix([pulp.value(u["%d" % j]) for j in xrange(self.Nc)]).T
        
        # find the maximum and minimum total Gibbs energy of the pathway,
        # under the constraint that the driving force of each reaction is >= OBD
        lp_total, total_dg = self._GetTotalEnergyProblem(obd - 1e-6, pulp.LpMinimize)
        lp_total.solve(pulp.CPLEX(msg=0))
        if lp_total.status != pulp.LpStatusOptimal:
            raise pulp.solvers.PulpSolverError("cannot solve total delta-G problem")
        min_tot_dg = pulp.value(total_dg)

        lp_total, total_dg = self._GetTotalEnergyProblem(obd - 1e-6, pulp.LpMaximize)
        lp_total.solve(pulp.CPLEX(msg=0))
        if lp_total.status != pulp.LpStatusOptimal:
            raise pulp.solvers.PulpSolverError("cannot solve total delta-G problem")
        max_tot_dg = pulp.value(total_dg)
        
        params = {'OBD': obd * R * self.T,
                  'concentrations' : conc,
                  'reaction prices' : reaction_prices,
                  'compound prices' : compound_prices,
                  'maximum total dG' : max_tot_dg * R * self.T,
                  'minimum total dG' : min_tot_dg * R * self.T}
        return obd * R * self.T, params
Esempio n. 2
0
def opt(C, X):
    orderNum = len(X)
    routeNum = len(C)
    routeIdx = range(routeNum)
    orderIdx = range(orderNum)
    # print routeIdx,orderIdx
    eps = 1.0 / 10**7
    print eps
    var_choice = lp.LpVariable.dicts('route', routeIdx, cat='Binary')
    # var_choice=lp.LpVariable.dicts('route',routeIdx,lowBound=0)#尝试松弛掉01变量
    exceed_labor = lp.LpVariable('Number of routes exceed 1000', 0)
    prob = lp.LpProblem("lastMile", lp.LpMinimize)

    prob += exceed_labor * 100000 + lp.lpSum(var_choice[i] * C[i]
                                             for i in routeIdx)

    prob += lp.lpSum(var_choice[i]
                     for i in routeIdx) <= 1000 + exceed_labor + eps
    for i in orderIdx:
        prob += lp.lpSum(var_choice[j] for j in X[i]) >= (1 - eps)

    prob.solve(lp.CPLEX(msg=0))
    print "\n\nstatus:", lp.LpStatus[prob.status]
    if lp.LpStatus[prob.status] != 'Infeasible':
        obj = lp.value(prob.objective)
        print "\n\nobjective:", obj
        sol_list = [var_choice[i].varValue for i in routeIdx]
        print "\n\nroutes:", (sum(sol_list))
        # print "\n\noriginal problem:\n",prob
        return obj, sol_list, lp.LpStatus[prob.status]
    else:
        return None, None, lp.LpStatus[prob.status]
Esempio n. 3
0
def main():
    demand = 110
    capacity = 10

    prob = pulp.LpProblem("3 Node Single Commodity Flow", pulp.LpMinimize)

    x12 = pulp.LpVariable('x12', lowBound=0, upBound=capacity, cat='Integer')
    x132 = pulp.LpVariable('x132', lowBound=0, upBound=(10*capacity), cat='Integer')
    z = pulp.LpVariable('z', lowBound=0)

    prob += (z)
    prob += (x12+x132 == demand)
    prob += (z * capacity >= x12)
    prob += (z * 10 *capacity >= x132)

    print(prob)

    prob.writeLP("3node SCF_Loadbalancing")

    # solve the LP using the default solver
    optimization_result = prob.solve(pulp.CPLEX())

    # make sure we got an optimal solution
    assert optimization_result == pulp.LpStatusOptimal

    # display the results
    for var in (x12, x132):
        print('Optimal number of {} to produce: {:1.0f}'.format(var.name, var.value()))
Esempio n. 4
0
    def solve_ilp(self, N):
        # build the A matrix: a_ij is 1 if j-th gram appears in the i-th sentence

        A = np.zeros((len(self.sentences_idx), len(self.ref_ngrams_idx)))
        for i in self.sentences_idx:
            sent = self.sentences[i].untokenized_form
            sngrams = list(
                extract_ngrams2([sent], self.stemmer, self.LANGUAGE, N))
            for j in self.ref_ngrams_idx:
                if self.ref_ngrams[j] in sngrams:
                    A[i][j] = 1

        # Define ILP variable, x_i is 1 if sentence i is selected, z_j is 1 if gram j appears in the created summary
        x = pulp.LpVariable.dicts('sentences',
                                  self.sentences_idx,
                                  lowBound=0,
                                  upBound=1,
                                  cat=pulp.LpInteger)
        z = pulp.LpVariable.dicts('grams',
                                  self.ref_ngrams_idx,
                                  lowBound=0,
                                  upBound=1,
                                  cat=pulp.LpInteger)

        # Define ILP problem, maximum coverage of grams from the reference summaries
        prob = pulp.LpProblem("ExtractiveUpperBound", pulp.LpMaximize)
        prob += pulp.lpSum(z[j] for j in self.ref_ngrams_idx)

        # Define ILP constraints, length constraint and consistency constraint (impose that z_j is 1 if j
        # appears in the created summary)
        prob += pulp.lpSum(x[i] * self.sentences[i].length
                           for i in self.sentences_idx) <= self.sum_length

        for j in self.ref_ngrams_idx:
            prob += pulp.lpSum(A[i][j] * x[i]
                               for i in self.sentences_idx) >= z[j]

        # Solve ILP problem and post-processing to get the summary
        try:
            print('Solving using CPLEX')
            prob.solve(pulp.CPLEX(msg=0))
        except:
            print('Solving using GLPK')
            prob.solve(pulp.GLPK(msg=0))

        summary_idx = []
        for idx in self.sentences_idx:
            if x[idx].value() == 1.0:
                summary_idx.append(idx)

        return summary_idx
Esempio n. 5
0
def main():
    prob = pulp.LpProblem("RSVP_TE_PathAllocation", pulp.LpMinimize)

    x_A_sf_kc = pulp.LpVariable('x_A_sf_kc', cat='Binary')
    x_A_sf_ny_kc = pulp.LpVariable('x_A_sf_ny_kc', cat='Binary')

    x_A_kc_ny = pulp.LpVariable('x_A_kc_ny', cat='Binary')
    x_A_kc_sf_ny = pulp.LpVariable('x_A_kc_sf_ny', cat='Binary')

    x_A_sf_ny = pulp.LpVariable('x_A_sf_ny', cat='Binary')
    x_A_sf_kc_ny = pulp.LpVariable('x_A_sf_kc_ny', cat='Binary')

    x_B_sf_ny = pulp.LpVariable('x_B_sf_ny', cat='Binary')
    x_B_sf_kc_ny = pulp.LpVariable('x_B_sf_kc_ny', cat='Binary')

    x_C_sf_ny = pulp.LpVariable('x_C_sf_ny', cat='Binary')
    x_C_sf_kc_ny = pulp.LpVariable('x_C_sf_kc_ny', cat='Binary')

    prob += (x_A_sf_kc + x_A_sf_ny_kc + x_A_kc_ny + x_A_kc_sf_ny + x_A_sf_ny +
             x_A_sf_kc_ny + x_B_sf_ny + x_B_sf_kc_ny + x_C_sf_ny +
             x_C_sf_kc_ny)

    prob += (x_A_sf_kc + x_A_sf_ny_kc == 1)
    prob += (x_A_kc_ny + x_A_kc_sf_ny == 1)
    prob += (x_A_sf_ny + x_A_sf_kc_ny == 1)
    prob += (x_B_sf_ny + x_B_sf_kc_ny == 1)
    prob += (x_C_sf_ny + x_C_sf_kc_ny == 1)

    prob += (45 * x_A_sf_kc + 60 * x_A_kc_sf_ny + 20 * x_A_sf_kc_ny +
             80 * x_B_sf_kc_ny + 100 * x_C_sf_kc_ny <= 155)
    prob += (45 * x_A_sf_ny_kc + 60 * x_A_kc_sf_ny + 20 * x_A_sf_ny +
             80 * x_B_sf_ny + 100 * x_C_sf_ny <= 155)
    prob += (45 * x_A_sf_ny_kc + 60 * x_A_kc_ny + 20 * x_A_sf_kc_ny +
             80 * x_B_sf_kc_ny + 100 * x_C_sf_kc_ny <= 155)

    print(prob)

    prob.writeLP("RSVP_TE_PathAllocation.lp")

    # solve the LP using the CPLEX
    optimization_result = prob.solve(pulp.CPLEX())

    # make sure we got an optimal solution
    assert optimization_result == pulp.LpStatusOptimal

    # display the results
    for var in (x_A_sf_kc, x_A_sf_ny_kc, x_A_kc_ny, x_A_kc_sf_ny, x_A_sf_ny,
                x_A_sf_kc_ny, x_B_sf_ny, x_B_sf_kc_ny, x_C_sf_ny,
                x_C_sf_kc_ny):
        print('Optimal number of {} to produce:{}'.format(
            var.name, var.varValue))
Esempio n. 6
0
def min_cost_routing_diff_cost():
    c12, c13, c23 = 2,2,2
    c132, c123, c213 = 1,1,1

    h12 = 5
    h13 = 10
    h23 = 7

    cap12 = 10
    cap13 = 10
    cap23 = 15

    prob = pulp.LpProblem("3Node_MultiCommodity_MinCost_Routing", pulp.LpMinimize)

    # Defining the Flow Variables
    x12 = pulp.LpVariable('x12', lowBound=0, upBound=10, cat='Integer')
    x132 = pulp.LpVariable('x132', lowBound=0, upBound=10, cat='Integer')

    x13 = pulp.LpVariable('x13', lowBound=0, upBound=10, cat='Integer')
    x123 = pulp.LpVariable('x123', lowBound=0, upBound=10, cat='Integer')

    x23 = pulp.LpVariable('x23', lowBound=0, upBound=10, cat='Integer')
    x213 = pulp.LpVariable('x213', lowBound=0, upBound=10, cat='Integer')

    # Adding Objective Function
    prob += (c12 * x12 + c132 * x132 + c13 * x13 + c123 * x123 + c23 * x23 + c213 * x213)

    # Subject to Constraints
    prob += (x12 + x132 == h12)
    prob += (x13 + x123 == h13)
    prob += (x23 + x213 == h23)

    prob += (x12 + x123 + x213 <= cap12)
    prob += (x13 + x132 + x213 <= cap13)
    prob += (x23 + x132 + x123 <= cap23)

    # Print the Problem
    print(prob)

    prob.writeLP("3node_MCF_MinCost.lp")

    # solve the LP using the CPLEX Solver
    optimization_result = prob.solve(pulp.CPLEX())

    # make sure we got an optimal solution
    assert optimization_result == pulp.LpStatusOptimal

    # display the results
    for var in (x12, x132, x13, x123, x23, x213):
        print('Optimal Flow for {} is {:1.0f}'.format(var.name, var.value()))
Esempio n. 7
0
def min_max_link_utilization():
    h12 = 5
    h13 = 10
    h23 = 7

    cap12 = 10
    cap13 = 10
    cap23 = 15

    prob = pulp.LpProblem("3Node_MultiCommodity_LoadBalancing",
                          pulp.LpMinimize)

    # Defining the Flow Variables
    x12 = pulp.LpVariable('x12', lowBound=0, cat='Continuous')
    x132 = pulp.LpVariable('x132', lowBound=0, cat='Continuous')

    x13 = pulp.LpVariable('x13', lowBound=0, cat='Continuous')
    x123 = pulp.LpVariable('x123', lowBound=0, cat='Continuous')

    x23 = pulp.LpVariable('x23', lowBound=0, cat='Continuous')
    x213 = pulp.LpVariable('x213', lowBound=0, cat='Continuous')

    z = pulp.LpVariable('z', lowBound=0)

    # Adding Objective Function
    prob += (z)

    # Subject to Constraints
    prob += (x12 + x132 == h12)
    prob += (x13 + x123 == h13)
    prob += (x23 + x213 == h23)

    prob += (z * cap12 >= x12 + x123 + x213)
    prob += (z * cap13 >= x13 + x132 + x213)
    prob += (z * cap23 >= x23 + x132 + x123)

    # Print the Problem
    print(prob)

    prob.writeLP("3node_MCF_LoadBalancing.lp")

    # solve the LP using the CPLEX Solver
    optimization_result = prob.solve(pulp.CPLEX())

    # make sure we got an optimal solution
    assert optimization_result == pulp.LpStatusOptimal

    # display the results
    for var in (x12, x132, x13, x123, x23, x213):
        print('Optimal Flow for {} is {:1.0f}'.format(var.name, var.value()))
Esempio n. 8
0
def solve_SOP(G, precedense, num_node, ss):
    problem = pulp.LpProblem(name='SOP', sense=pulp.LpMinimize)
    x = {(i, j): pulp.LpVariable(cat="Binary", name=f"x_{i}_{j}")
         for (i, j) in G.edges()}
    u = {
        i: pulp.LpVariable(cat="Integer",
                           name=f"u_{i}",
                           lowBound=1,
                           upBound=num_node - 1)
        for i in G.nodes()
    }
    cost = {(i, j): G.adj[i][j]['dist'] for (i, j) in G.edges()}

    problem += pulp.lpSum([x[(i, j)] * cost[(i, j)] for (i, j) in G.edges()])

    for i in G.nodes():
        if i != num_node - 1:
            problem.addConstraint(
                pulp.lpSum([x[(i, j)] for j in range(num_node)
                            if j != i]) == 1, f'outflow_{i}')
        if i != 0:
            problem.addConstraint(
                pulp.lpSum([x[(j, i)] for j in range(num_node)
                            if j != i]) == 1, f'inflow_{i}')

    for i, j in G.edges():
        if i != ss and j != ss:
            problem.addConstraint(
                u[i] - u[j] + (num_node - 1) * x[i, j] <= num_node - 2,
                f'up_{i}_{j}')

    for i, j in precedense:
        problem.addConstraint(u[i] + 1 <= u[j], f'sequential_{i}_{j}')

    u[ss] = 0

    print('start solving')
    start = time.time()
    status = problem.solve(pulp.CPLEX())
    # status = problem.solve()
    print(pulp.LpStatus[status])

    duartion = time.time() - start
    print(duartion)

    if pulp.LpStatus[status] != 'Optimal':
        print('Infeasible!')
        exit()

    return x, u, duartion
Esempio n. 9
0
 def solve_ilp_problem(self,
                       word_num,
                       p,
                       dep_length=None,
                       parents=None,
                       matrix=None,
                       solver='glpk',
                       mx=0.7,
                       mn=0.2,
                       w2=0.5,
                       saved=None):
     max_length = int(mx * word_num)
     min_length = int(mn * word_num)
     prob = pulp.LpProblem('sentence_compression', pulp.LpMaximize)
     # initialize the word binary variables
     c = pulp.LpVariable.dicts(name='c',
                               indexs=range(word_num),
                               lowBound=0,
                               upBound=1,
                               cat='Integer')
     #objective function
     prob += sum((p[i] - w2 * dep_length[i]) * c[i] for i in range(
         word_num))  #p[i] is  the probability for retain the words
     # #constraints
     if parents is not None:
         for j in range(word_num):
             if parents[j] > 0:
                 prob += c[j] <= c[parents[j]]
     if saved is not None:
         for s in saved:
             prob += c[s[0]] >= c[s[1]]
     prob += sum([c[i] for i in range(word_num)]) <= max_length
     prob += sum([c[i] for i in range(word_num)]) >= min_length
     if solver == 'gurobi':
         prob.solve(pulp.GUROBI(msg=0))
     elif solver == 'glpk':
         prob.solve(pulp.GLPK(msg=0))
     elif solver == 'cplex':
         prob.solve(pulp.CPLEX(msg=0))
     else:
         sys.exit('no solver specified')
     values = [c[j].varValue for j in range(word_num)]
     solution = [j for j in range(word_num) if c[j].varValue == 1]
     return (pulp.value(prob.objective), solution, values)
    def compute_consensus_rankings(
            self,
            dataset: Dataset,
            scoring_scheme: ScoringScheme,
            return_at_most_one_ranking=False,
            bench_mode=False
    ) -> Consensus:
        """
        :param dataset: A dataset containing the rankings to aggregate
        :type dataset: Dataset (class Dataset in package 'datasets')
        :param scoring_scheme: The penalty vectors to consider
        :type scoring_scheme: ScoringScheme (class ScoringScheme in package 'distances')
        :param return_at_most_one_ranking: the algorithm should not return more than one ranking
        :type return_at_most_one_ranking: bool
        :param bench_mode: is bench mode activated. If False, the algorithm may return more information
        :type bench_mode: bool
        :return one or more rankings if the underlying algorithm can find several equivalent consensus rankings
        If the algorithm is not able to provide multiple consensus, or if return_at_most_one_ranking is True then, it
        should return a list made of the only / the first consensus found.
        In all scenario, the algorithm returns a list of consensus rankings
        :raise ScoringSchemeNotHandledException when the algorithm cannot compute the consensus because the
        implementation of the algorithm does not fit with the scoring scheme
        """
        rankings = dataset.rankings
        elem_id = {}
        id_elements = {}
        id_elem = 0
        for ranking in rankings:
            for bucket in ranking:
                for element in bucket:
                    if element not in elem_id:
                        elem_id[element] = id_elem
                        id_elements[id_elem] = element
                        id_elem += 1
        nb_elem = len(elem_id)

        positions = ExactAlgorithmGeneric.__positions(rankings, elem_id)

        sc = asarray(scoring_scheme.penalty_vectors)

        graph, mat_score, ties_must_be_checked = self.__graph_of_elements(positions, sc)

        my_values = []
        my_vars = []

        h_vars = {}
        cpt = 0

        for i in range(nb_elem):
            for j in range(nb_elem):
                if not i == j:
                    name_var = "x_%s_%s" % (i, j)
                    my_values.append(mat_score[i][j][0])
                    my_vars.append(pulp.LpVariable(name_var, 0, 1, cat="Binary"))
                    h_vars[name_var] = cpt
                    cpt += 1
                    if i < j:
                        name_var = "t_%s_%s" % (i, j)
                        my_values.append(mat_score[i][j][2])
                        my_vars.append(pulp.LpVariable(name_var, 0, 1, cat="Binary"))
                        h_vars[name_var] = cpt
                        cpt += 1

        prob = pulp.LpProblem("myProblem", pulp.LpMinimize)

        # add the binary order constraints
        for i in range(0, nb_elem - 1):
            for j in range(i + 1, nb_elem):
                if not i == j:
                    prob += my_vars[h_vars["x_%s_%s" % (i, j)]] \
                            + my_vars[h_vars["x_%s_%s" % (j, i)]] \
                            + my_vars[h_vars["t_%s_%s" % (i, j)]] == 1

        # add the transitivity constraints
        for i in range(0, nb_elem):
            for j in range(nb_elem):
                if j != i:
                    i_bef_j = "x_%s_%s" % (i, j)
                    if i < j:
                        i_tie_j = "t_%s_%s" % (i, j)
                    else:
                        i_tie_j = "t_%s_%s" % (j, i)
                    for k in range(nb_elem):
                        if k != i and k != j:
                            j_bef_k = "x_%s_%s" % (j, k)
                            i_bef_k = "x_%s_%s" % (i, k)
                            if j < k:
                                j_tie_k = "t_%s_%s" % (j, k)
                            else:
                                j_tie_k = "t_%s_%s" % (k, j)

                            if i < k:
                                i_tie_k = "t_%s_%s" % (i, k)
                            else:
                                i_tie_k = "t_%s_%s" % (k, i)

                            prob += my_vars[h_vars[i_bef_j]] +\
                                my_vars[h_vars[j_bef_k]] \
                                + my_vars[h_vars[j_tie_k]] \
                                - my_vars[h_vars[i_bef_k]] <= 1

                            prob += my_vars[h_vars[i_bef_j]] + \
                                my_vars[h_vars[i_tie_j]] \
                                + my_vars[h_vars[j_bef_k]] - my_vars[h_vars[i_bef_k]] <= 1

                            prob += 2 * my_vars[h_vars[i_tie_j]] \
                                + 2 * my_vars[h_vars[j_tie_k]] \
                                - my_vars[h_vars[i_tie_k]] <= 3

        # optimization
        if not ties_must_be_checked:
            for i in range(0, nb_elem - 1):
                for j in range(i + 1, nb_elem):
                    if not i == j:
                        prob += my_vars[h_vars["t_%s_%s" % (i, j)]] == 0

        cfc = graph.components()

        for i in range(len(cfc)):
            group_i = cfc[i]
            for j in range(i+1, len(cfc)):
                for elem_i in group_i:
                    for elem_j in cfc[j]:
                        prob += my_vars[h_vars["x_%s_%s" % (elem_i, elem_j)]] == 1
                        prob += my_vars[h_vars["x_%s_%s" % (elem_j, elem_i)]] == 0
                        if elem_i < elem_j:
                            prob += my_vars[h_vars["t_%s_%s" % (elem_i, elem_j)]] == 0
                        else:
                            prob += my_vars[h_vars["t_%s_%s" % (elem_j, elem_i)]] == 0

        # objective function
        prob += pulp.lpSum(my_vars[cpt] * my_values[cpt] for cpt in range(len(my_vars)))

        try:
            prob.solve(pulp.CPLEX(msg=False))
        except:
            prob.solve(pulp.PULP_CBC_CMD(msg=False))

        h_def = {i: 0 for i in range(nb_elem)}

        for var in my_vars:
            if abs(var.value() - 1) < 0.01 and var.name[0] == "x":
                h_def[int(var.name.split("_")[2])] += 1

        ranking = []
        current_nb_def = 0
        bucket = []

        for elem, nb_defeats in (sorted(h_def.items(), key=itemgetter(1))):
            if nb_defeats == current_nb_def:
                bucket.append(id_elements[elem])
            else:
                ranking.append(bucket)
                bucket = [id_elements[elem]]
                current_nb_def = nb_defeats
        ranking.append(bucket)
        return Consensus(consensus_rankings=[ranking],
                         dataset=dataset,
                         scoring_scheme=scoring_scheme,
                         att={ConsensusFeature.IsNecessarilyOptimal: True,
                              ConsensusFeature.KemenyScore: prob.objective.value(),
                              ConsensusFeature.AssociatedAlgorithm: self.get_full_name()
                              })
Esempio n. 11
0
#prob+=pulp.LpSum([h[i][(i,t)] for i in modelList for t in Tm[i]])*1/2== sum([R[l][t] for t in TL])

#prob+=r[l][o]+Pday[l][o]<=(orderPool['deli_date'][o]-datetime.datetime.strptime(plan_dates[0],'%Y-%m-%d')).days
#prob+=r[l][o]>=max(0,(orderPool['epst'][o]-datetime.datetime.strptime(plan_dates[0],'%Y-%m-%d')).days)
#prob+=pulp.lpSum([order_spd[(order_spd['order_id'==o])&(order_spd['line_o']==l)&(order_spd['day_process']==Pday[l][o])] for l in prod_line])==orderPool['order_num'][o]
#prob+=compD[l][o]<=(orderPool['deli_date'][o]-datetime.datetime.strptime(plan_dates[0],'%Y-%m-%d')).days
#prob+=pulp.lpSum([Csums[l][o] for l in prod_line for o in orderList])==orderPool['order_num'].sum()
#5.every line cannot made two orders at the same time

#eps=1e-2
#for o in orderList:
#prob+=Cmax+eps*pulp.lpSum([r[l][o] for l in prod_line])-eps*pulp.lpSum([compD[l][o] for l in prod_line])

prob.writeLP("APSModel.lp")
#solver=pulp.solvers.COIN_CMD(path='/home/yumchaamax/math_dep/cbc/Cbc-2.9/build/Cbc/src/cbc',threads=16,msg=1,fracGap=0.01)
prob.solve(pulp.CPLEX())
print("Status:", pulp.LpStatus[prob.status])

#for o in orderList:
#for l in prod_line:
#print((l,o),r[l,o].value(),compD[l,o].value(),Cmax[l,o].value())
a = []
for v in prob.variables():
    #print(v.name, "=", v.varValue)
    a.append((v.name, v.varValue))
rlt_df = pd.DataFrame(a)

rlt_df.to_csv("test.csv")

print("Total amounts of products by day =", pulp.value(prob.objective))
Esempio n. 12
0
    def _solve_ilp_problem(self,
                           words_limit=100,
                           solver='glpk',
                           excluded_solutions=[],
                           unique=False):
        """Solve the ILP formulation of the concept-based model.
        Args:
            words_limit (int): the maximum size in words of the summary,
              defaults to 100.
            solver (str): the solver used, defaults to glpk.
            excluded_solutions (list of list): a list of subsets of sentences
              that are to be excluded, defaults to []
            unique (bool): modify the model so that it produces only one optimal
              solution, defaults to False
        Returns:
            (value, set) tuple (int, list): the value of the objective function
              and the set of selected sentences as a tuple.
        """
        # initialize container shortcuts
        concepts = self.weights.keys()
        W = self.weights
        L = words_limit
        C = len(concepts)
        S = len(self.sentences)

        assert self.word_frequency, "word_frequency must be calculated first"

        words = self.word_frequency.keys()
        frequency = self.word_frequency
        words_count = len(words)

        concepts = sorted(self.weights, key=self.weights.get, reverse=True)

        # fomulation of the ILP problem
        prob = pulp.LpProblem("ILP for Summarization", pulp.LpMaximize)

        # initialize the concepts binary variables
        c = pulp.LpVariable.dicts(name='c',
                                  indexs=range(C),
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')
        # initialize the sentences binary variables
        s = pulp.LpVariable.dicts(name='s',
                                  indexs=range(S),
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')
        # initialize the word(term) binary variables
        t = pulp.LpVariable.dicts(name='t',
                                  indexs=range(words_count),
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')
        # objective function
        if unique:
            prob += sum(W[concepts[i]] * c[i] for i in range(C)) + \
                    10e-6 * sum(frequency[words[j]] * t[j] for j in range(words_count))
        else:
            prob += sum(W[concepts[i]] * c[i] for i in range(C))

        # constraint for summary size
        prob += sum(s[i] * self._get_sentence_length(self.sentences[i])
                    for i in range(S)) <= L

        # integrity constraint
        for i in range(C):
            for j in range(S):
                if concepts[i] in self.sentences[j].concepts:
                    prob += s[j] <= c[i]

        for i in range(C):
            prob += sum(s[j] for j in range(S)
                        if concepts[i] in self.sentences[j].concepts) >= c[i]

        # word integrity constraint
        if unique:
            for i in range(words_count):
                for j in self.word2sent[words[i]]:
                    prob += s[j] <= t[i]

            for i in range(words_count):
                prob += sum(s[j] for j in self.word2sent[words[i]]) >= t[i]

        # constraint for finding optimal solutions
        for sentence_set in excluded_solutions:
            prob += sum(s[i] for i in sentence_set) <= len(sentence_set) - 1

        # solve the ilp problem
        if solver.lower() == "glpk":
            prob.solve(pulp.GLPK(msg=0))
        elif solver.lower() == "gurobi":
            prob.solve(pulp.GUROBI(msg=0))
        elif solver.lower() == "cplex":
            prob.solve(pulp.CPLEX(msg=0))
        else:
            raise AssertionError("no solver specified")

        # retrieve the optimal subset of sentences
        solution = set([idx for idx in range(S) if s[idx].varValue == 1])

        # return the (objective function value, solution) tuple
        return (pulp.value(prob.objective), solution)
Esempio n. 13
0
def optimizeTrajectory(activeConstraints, 
  N, T, T_end, V, P, W, M, m, minApproachDist, 
  x_ini, x_fin, x_lim, u_lim, objects, r, dynamicsModel, omega):

  # --------------------
  # Calculated Variables
  # --------------------
  del_t = T_end/(T-1)
  numObjects = objects.shape[0]

  # ------------------
  # Decision variables
  # ------------------
  # Thrust
  u = pulp.LpVariable.dicts(
    "input", ((i, p, n) for i in range(T) for p in range(V) for n in range(N)),
    cat='Continuous')
  # Thrust Magnitude
  v = pulp.LpVariable.dicts(
    "inputMag", ((i, p, n) for i in range(T) for p in range(V) for n in range(N)),
    lowBound=0,
    cat='Continuous')
  # State
  x = pulp.LpVariable.dicts(
    "state", ((i, p, k) for i in range(T) for p in range(V) for k in range(2*N)),
    cat='Continuous')

  # ------------------
  # Optimization Model
  # ------------------

  # Instantiate Model
  model = pulp.LpProblem("Satellite Fuel Minimization Problem", pulp.LpMinimize)
  # Objective Function
  model += pulp.lpSum(v[i, p, n] for i in range(T) for p in range(V) for n in range(N)), "Fuel Minimization"

  # -----------
  # Constraints
  # -----------

  # Basic Constraints
  # -----------------
  # Constrain thrust magnitude to abs(u[i, p, n])
  for i in range(T):
    for p in range(V):
      for n in range(N):
        model +=  u[i, p, n] <= v[i, p, n]
        model += -u[i, p, n] <= v[i, p, n]
  # State and Input vector start and end values
  for p in range(V):
    for k in range(2*N):
      model += x[0, p, k]   == x_ini[p, k]
      if(activeConstraints["finalConfigurationSelection"] == False):
        model += x[T-1, p, k] == x_fin[p, k]
  # Model Dynamics
  if dynamicsModel == "freeSpace":
    for constraint in freeSpaceDynamics(x, u, T, V, N, m, del_t):
      model += constraint
  elif dynamicsModel == "hills":
    for constraint in linearHillsDynamics(x, u, T, V, N, m, del_t, omega):
      model += constraint

  # State and Input vector limits
  for i in range(T):
    for p in range(V):
      for n in range(N):
        model += u[i, p, n] <=  u_lim[p, n]
        model += u[i, p, n] >= -u_lim[p, n]
      for k in range(2*N): # Necessary?
        model += x[i, p, k] <=  x_lim[p, k]
        model += x[i, p, k] >= -x_lim[p, k]

  # Obstacle Avoidance
  # ------------------
  if (activeConstraints["obstacleAvoidance"] == True and objects.shape[1] > 0):
    #Obstacle avoidance binary decision variable
    a = pulp.LpVariable.dicts(
      "objCol", ((i, p, l, k) for i in range(T) for p in range(V) for l in range(numObjects) for k in range(2*N)),
      cat='Binary')
    for i in range(T):
      for p in range(V):
        for l in range(objects.shape[0]):
          model += pulp.lpSum(a[i, p, l, n] for n in range(2*N)) <= 2*N-1
          for n in range(N):
            model += x[i, p, n] >= objects[l, n*2+1] + minApproachDist - M*a[i, p, l, N+n]           
            model += x[i, p, n] <= objects[l, n*2] - minApproachDist + M*a[i, p, l, n]

  # Collision Avoidance
  # -------------------
  if (activeConstraints["collisionAvoidance"] == True and V > 1):
    # Collision avoidance binary decision variable
    b = pulp.LpVariable.dicts(
    "satelliteCollisionAvoidance", ((i, p, q, k) for i in range(T) for p in range(V) for q in range(V) for k in range(2*N)),
    cat='Binary')
    for i in range(T):
      for p in range(V):
        for q in range(V):
          if q > p:
            model += pulp.lpSum(b[i, p, q, k] for k in range(2*N)) <= 2*N-1
            for n in range(N):
              model += x[i, p, n] - x[i, q, n] >= r[n] - M*b[i, p, q, n]
              model += x[i, q, n] - x[i, p, n] >= r[n] - M*b[i, p, q, n+N]

  # Plume Avoidance for Vehicles
  # ----------------------------
  if (activeConstraints["plumeAvoidanceVehicle"] == True):
    # Positive thrust
    c_pos = pulp.LpVariable.dicts(
    "plumeAvoidanceVehiclePos", ((i, p, q, n, k) for i in range(T) for p in range(V) for q in range(V) for n in range(N) for k in range(2*N+1)),
    cat='Binary')
    for i in range(T):
      for p in range(V):
        for q in range(V):
          if q != p:
            for n in range(N):
              model += pulp.lpSum(c_pos[i, p, q, n, k] for k in range(2*N+1)) <= 2*N
              model += -u[i, p, n] >= - M*c_pos[i, p, q, n, 0]
              model += x[i, p, n] - x[i, q, n] >= P - M*c_pos[i, p, q, n, n+1]
              model += x[i, q, n] - x[i, p, n] >= - M*c_pos[i, p, q, n, n+N+1]
              for m in range(N):
                if m != n:
                  model += x[i, p, m] - x[i, q, m] >= W - M*c_pos[i, p, q, n, m+1]
                  model += x[i, q, m] - x[i, p, m] >= W - M*c_pos[i, p, q, n, m+N+1]
    c_neg = pulp.LpVariable.dicts(
    "plumeAvoidanceVehicleNeg", ((i, p, q, n, k) for i in range(T) for p in range(V) for q in range(V) for n in range(N) for k in range(2*N+1)),
    cat='Binary')
    for i in range(T):
      for p in range(V):
        for l in range(numObjects):
          for n in range(N):
            model += pulp.lpSum(c_neg[i, p, q, n, k] for k in range(2*N+1)) <= 2*N
            model += u[i, p, n] >= - M*c_neg[i, p, q, n, 0]
            model += x[i, p, n] - x[i, q, n] >= - M*c_neg[i, p, q, n, n+1]
            model += x[i, q, n] - x[i, p, n] >= P - M*c_neg[i, p, q, n, n+N+1]
            for m in range(N):
              if m != n:
                model += x[i, p, m] - x[i, q, m] >= W - M*c_neg[i, p, q, n, m+1]
                model += x[i, q, m] - x[i, p, m] >= W - M*c_neg[i, p, q, n, m+N+1]

  # Plume Avoidance for Obstacles
  # -----------------------------
  if (activeConstraints["plumeAvoidanceObstacle"] == True and objects.shape[1] > 0):
    # Positive thrust
    d_pos = pulp.LpVariable.dicts(
    "plumeAvoidanceObstaclePos", ((i, p, l, n, k) for i in range(T) for p in range(V) for l in range(numObjects) for n in range(N) for k in range(2*N+1)),
    cat='Binary')
    for i in range(T):
      for p in range(V):
        for l in range(numObjects):
          for n in range(N):
            model += pulp.lpSum(d_pos[i, p, l, n, k] for k in range(2*N+1)) <= 2*N
            model += -u[i, p, n] >= - M*d_pos[i, p, l, n, 0]
            model += x[i, p, n] - objects[l, n*2+1] >= P - M*d_pos[i, p, l, n, n+1]
            model += objects[l, n*2] - x[i, p, n]   >= - M*d_pos[i, p, l, n, n+N+1]
            for m in range(N):
              if m != n:
                model += x[i, p, m] - objects[l, m*2+1] >= W - M*d_pos[i, p, l, n, m+1]
                model += objects[l, m*2] - x[i, p, m]   >= W - M*d_pos[i, p, l, n, m+N+1]
    d_neg = pulp.LpVariable.dicts(
    "plumeAvoidanceObstacleNeg", ((i, p, l, n, k) for i in range(T) for p in range(V) for l in range(numObjects) for n in range(N) for k in range(2*N+1)),
    cat='Binary')
    for i in range(T):
      for p in range(V):
        for l in range(numObjects):
          for n in range(N):
            model += pulp.lpSum(d_neg[i, p, l, n, k] for k in range(2*N+1)) <= 2*N
            model += u[i, p, n] >= - M*d_neg[i, p, l, n, 0]
            model += x[i, p, n] - objects[l, n*2+1] >= - M*d_neg[i, p, l, n, n+1]
            model += objects[l, n*2] - x[i, p, n]   >= P - M*d_neg[i, p, l, n, n+N+1]
            for m in range(N):
              if m != n:
                model += x[i, p, m] - objects[l, m*2+1] >= W - M*d_neg[i, p, l, n, m+1]
                model += objects[l, m*2] - x[i, p, m]   >= W - M*d_neg[i, p, l, n, m+N+1]

  # Final Configuration Selection
  # -----------------------------
  if (activeConstraints["finalConfigurationSelection"]):
    G = V
    f = pulp.LpVariable.dicts(
    "finalConfigurationSelection", ((p, g, r) for p in range(V) for g in range(G) for r in range(V)),
    cat='Binary')

    for p in range(V):
      for k in range(2*N):
        model += x[T-1, p, k] == pulp.lpSum(x_fin[r, k]*f[p, g, r] for g in range(G) for r in range(V))

    # model += x[T-1, p, k] == x_fin[p, k]

    for p in range(V):
      model += pulp.lpSum(f[p, g, r] for g in range(G) for r in range(V)) == 1

    for p in range(V):
      for g in range(G):
        model += pulp.lpSum(f[p, g, r] for r in range(V)) == pulp.lpSum(f[r, g, p] for r in range(V))

    for g in range(G):
      model += pulp.lpSum(f[p, g, r] for p in range(V) for r in range(V)) == V*pulp.lpSum(f[0, g, r] for r in range(V))
    

  # Solve model and return results in dictionary
  model.solve(pulp.CPLEX())

  # Create Pandas dataframe for results and return
  return {'model':model, 'x':x, 'u':u}
Esempio n. 14
0
    def __solve_joint_ilp__(self, feedback, non_feedback, summarizer, summary_length,
                            uncertainity={}, labels={}, unique=False, excluded_solutions=[], solver='glpk'):
        """
        :param summary_length: The size of the backpack. i.e. how many words are allowed in the summary.
        :param feedback:
        :param non_feedback:
        :param unique: if True, an boudin_2015 eq. (5) is applied to enforce a unique solution.
        :param solver: default glpk
        :param excluded_solutions:
        :return:
        """
        w = summarizer.weights
        if self.run_config['rank_subset']:
            w = self.sentence_ranker.all_concept_weights

        u = uncertainity
        L = summary_length
        NF = len(non_feedback)
        F = len(feedback)
        S = len(summarizer.sentences)

        if not summarizer.word_frequencies:
            summarizer.compute_word_frequency()

        tokens = summarizer.word_frequencies.keys()
        f = summarizer.word_frequencies
        T = len(tokens)

        # HACK Sort keys
        # concepts = sorted(self.weights, key=self.weights.get, reverse=True)

        # formulation of the ILP problem
        prob = pulp.LpProblem(summarizer.input_directory, pulp.LpMaximize)

        # initialize the concepts binary variables
        nf = pulp.LpVariable.dicts(name='nf',
                                   indexs=range(NF),
                                   lowBound=0,
                                   upBound=1,
                                   cat='Integer')

        f = pulp.LpVariable.dicts(name='F',
                                  indexs=range(F),
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')

        # initialize the sentences binary variables
        s = pulp.LpVariable.dicts(name='s',
                                  indexs=range(S),
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')

        # initialize the word binary variables
        t = pulp.LpVariable.dicts(name='t',
                                  indexs=range(T),
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')

        # OBJECTIVE FUNCTION
        if labels:
            # log.debug('solve for Active learning 2')
            prob += pulp.lpSum(
                w[non_feedback[i]] * (1.0 - u[non_feedback[i]]) * labels[non_feedback[i]] * nf[i] for i in range(NF))
        if not labels:
            if uncertainity:
                # log.debug('solve for Active learning')
                if feedback:
                    # In this phase, we force new concepts to be chosen, and not those we already have feedback on, and
                    # therefore non_feedback is added while feedback is substracted from the problem. I.e. by
                    # substracting the feedback, those sentences will disappear from the solution.
                    prob += pulp.lpSum(w[non_feedback[i]] * u[non_feedback[i]] * nf[i] for i in range(NF)) - pulp.lpSum(
                        w[feedback[i]] * u[feedback[i]] * f[i] for i in range(F))
                else:
                    prob += pulp.lpSum(w[non_feedback[i]] * u[non_feedback[i]] * nf[i] for i in range(NF))
            if not uncertainity:
                # log.debug('solve for ILP feedback')
                if feedback:
                    prob += pulp.lpSum(w[non_feedback[i]] * nf[i] for i in range(NF)) - pulp.lpSum(
                        w[feedback[i]] * f[i] for i in range(F))
                else:
                    prob += pulp.lpSum(w[non_feedback[i]] * nf[i] for i in range(NF))

        if unique:
            prob += pulp.lpSum(w[non_feedback[i]] * nf[i] for i in range(NF)) - pulp.lpSum(w[feedback[i]] * f[i] for i in range(F)) + \
                    10e-6 * pulp.lpSum(f[tokens[k]] * t[k] for k in range(T))

        # CONSTRAINT FOR SUMMARY SIZE
        prob += pulp.lpSum(s[j] * summarizer.sentences[j].length for j in range(S)) <= L

        # INTEGRITY CONSTRAINTS
        for i in range(NF):
            for j in range(S):
                if non_feedback[i] in summarizer.sentences[j].concepts:
                    prob += s[j] <= nf[i]

        for i in range(NF):
            prob += pulp.lpSum(s[j] for j in range(S)
                        if non_feedback[i] in summarizer.sentences[j].concepts) >= nf[i]

        for i in range(F):
            for j in range(S):
                if feedback[i] in summarizer.sentences[j].concepts:
                    prob += s[j] <= f[i]

        for i in range(F):
            prob += pulp.lpSum(s[j] for j in range(S)
                        if feedback[i] in summarizer.sentences[j].concepts) >= f[i]

        # WORD INTEGRITY CONSTRAINTS
        if unique:
            for k in range(T):
                for j in summarizer.w2s[tokens[k]]:
                    prob += s[j] <= t[k]

            for k in range(T):
                prob += pulp.lpSum(s[j] for j in summarizer.w2s[tokens[k]]) >= t[k]

        # CONSTRAINTS FOR FINDING OPTIMAL SOLUTIONS
        for sentence_set in excluded_solutions:
            prob += pulp.lpSum([s[j] for j in sentence_set]) <= len(sentence_set) - 1

        # prob.writeLP('test.lp')

        # solving the ilp problem
        try:
            #print('Solving using CPLEX')
            prob.solve(pulp.CPLEX(msg=0))
        except:
            #print('Fallback to mentioned solver')
            if solver == 'gurobi':
                prob.solve(pulp.GUROBI(msg=0))
            elif solver == 'glpk':
                prob.solve(pulp.GLPK(msg=0))
            else:
                sys.exit('no solver specified')

        # retreive the optimal subset of sentences
        solution = Set([j for j in range(S) if s[j].varValue == 1])

        # returns the (objective function value, solution) tuple
        return (pulp.value(prob.objective), solution)
Esempio n. 15
0
def opt_with_solver(node_ind,
                    order_dict,
                    travel_t,
                    stay_t,
                    pick_t,
                    require_t,
                    num,
                    mini_start,
                    initial=None,
                    load_check=True):
    # order_dict = {ord:(ori_id, dest_id)}, ord in order_set, ori_id, dest_id in node_ind
    # node_ind = range(n), travel_t = {(i,j): travel time between i and j}
    # initial = (given start id, given load)
    big_m = 10000
    eps = 1.0 / 10**7
    n = len(node_ind)
    inter_n = [(i, j) for i in node_ind for j in node_ind if j != i]
    off_time = lp.LpVariable('The route-off time')
    p = lp.LpVariable.dicts('Punish cost', node_ind, lowBound=0)
    x = lp.LpVariable.dicts('Route variable', inter_n, cat='Binary')
    o = lp.LpVariable.dicts('Start-point flag', node_ind, cat='Binary')
    d = lp.LpVariable.dicts('End-point flag', node_ind, cat='Binary')
    a = lp.LpVariable.dicts('Arrival time', node_ind)
    l = lp.LpVariable.dicts('Leave time', node_ind)
    t = lp.LpVariable.dicts('Order count', node_ind, 0, n - 1 + eps)
    if load_check:
        load = lp.LpVariable.dicts('Arrival load', node_ind, 0,
                                   MAX_LOADS + eps)
    else:
        load = lp.LpVariable.dicts('Arrival load', node_ind, 0)
    prob = lp.LpProblem('Optimize a route', lp.LpMinimize)
    # Objective
    prob += off_time + lp.lpSum(p[i] for i in node_ind)
    # Constraints
    for j in node_ind:
        prob += lp.lpSum(x[(i, j)] for i in node_ind if i != j) == 1 - o[j]
    for i in node_ind:
        prob += lp.lpSum(x[(i, j)] for j in node_ind if j != i) == 1 - d[i]
    prob += lp.lpSum(o[i] for i in node_ind) == 1
    prob += lp.lpSum(d[i] for i in node_ind) == 1
    if not (initial is None):
        prob += o[initial[0]] == 1
        prob += load[initial[0]] == initial[1]
    for order in order_dict:
        od = order_dict[order]
        prob += a[od[1]] >= l[od[0]]
    for i in node_ind:
        prob += off_time >= l[i]
        prob += l[i] >= a[i] + stay_t[i]
        prob += l[i] >= pick_t[i]
        prob += a[i] >= mini_start[i]
        prob += p[i] >= PUNISH_CO * (a[i] - require_t[i])
    for i, j in inter_n:
        prob += a[j] >= l[i] + travel_t[(i, j)] + big_m * (x[(i, j)] - 1)
        prob += t[j] >= t[i] + 1 + big_m * (x[(i, j)] - 1)
        prob += load[j] >= load[i] + num[i] + big_m * (x[(i, j)] - 1)
    prob.solve(
        lp.CPLEX(msg=1,
                 timelimit=CPLEX_TIME_LIMIT,
                 options=['set logfile cplex/cplex%d.log' % os.getpid()]))
    # set threads 100
    if lp.LpStatus[prob.status] != 'Infeasible':
        sol_list = [int(round(t[i].varValue)) for i in node_ind]
        return lp.value(prob.objective), sol_list, lp.LpStatus[prob.status]
    else:
        return None, None, lp.LpStatus[prob.status]
Esempio n. 16
0
    def solve_ilp_problem(self,
                          summary_size=100,
                          units="WORDS",
                          solver='glpk',
                          excluded_solutions=[],
                          unique=False):
        """Solve the ILP formulation of the concept-based model.

            :param summary_size: the maximum size in words of the summary, defaults to 100.
            :param units: defaults to "WORDS"
            :param solver: the solver used, defaults to glpk
            :param excluded_solutions: (list of list): a list of subsets of sentences that are to be excluded,
                defaults to []
            :param unique: (bool): modify the model so that it produces only one optimal solution, defaults to False

            :return: (value, set) tuple (int, list): the value of the objective function
                and the set of selected sentences as a tuple.

        """
        # initialize container shortcuts
        concepts = self.weights.keys()

        w = self.weights
        L = summary_size
        C = len(concepts)
        S = len(self.sentences)

        if not self.word_frequencies:
            self.compute_word_frequency()

        tokens = self.word_frequencies.keys()
        f = self.word_frequencies
        T = len(tokens)

        # HACK Sort keys
        concepts = sorted(self.weights, key=self.weights.get, reverse=True)

        # formulation of the ILP problem
        prob = pulp.LpProblem(self.input_directory, pulp.LpMaximize)

        # initialize the concepts binary variables
        c = pulp.LpVariable.dicts(name='c',
                                  indexs=range(C),
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')

        # initialize the sentences binary variables
        s = pulp.LpVariable.dicts(name='s',
                                  indexs=range(S),
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')

        # initialize the word binary variables
        t = pulp.LpVariable.dicts(name='t',
                                  indexs=range(T),
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')

        # OBJECTIVE FUNCTION
        prob += pulp.lpSum(w[concepts[i]] * c[i] for i in range(C))

        if unique:
            prob += pulp.lpSum(w[concepts[i]] * c[i] for i in range(C)) + \
                    10e-6 * pulp.lpSum(f[tokens[k]] * t[k] for k in range(T))

        # CONSTRAINT FOR SUMMARY SIZE
        if units == "WORDS":
            prob += pulp.lpSum(s[j] * self.sentences[j].length
                               for j in range(S)) <= L
        if units == "CHARACTERS":
            prob += pulp.lpSum(s[j] * len(self.sentences[j].untokenized_form)
                               for j in range(S)) <= L

        # INTEGRITY CONSTRAINTS
        for i in range(C):
            for j in range(S):
                if concepts[i] in self.sentences[j].concepts:
                    prob += s[j] <= c[i]

        for i in range(C):
            prob += pulp.lpSum(
                s[j] for j in range(S)
                if concepts[i] in self.sentences[j].concepts) >= c[i]

        # WORD INTEGRITY CONSTRAINTS
        if unique:
            for k in range(T):
                for j in self.w2s[tokens[k]]:
                    prob += s[j] <= t[k]

            for k in range(T):
                prob += pulp.lpSum(s[j] for j in self.w2s[tokens[k]]) >= t[k]

        # CONSTRAINTS FOR FINDING OPTIMAL SOLUTIONS
        for sentence_set in excluded_solutions:
            prob += pulp.lpSum([s[j] for j in sentence_set
                                ]) <= len(sentence_set) - 1

        # prob.writeLP('test.lp')

        # solving the ilp problem
        try:
            print('Solving using Cplex')
            prob.solve(pulp.CPLEX(msg=0))
        except:
            print('Fallback to mentioned solver')
            if solver == 'gurobi':
                prob.solve(pulp.GUROBI(msg=0))
            elif solver == 'glpk':
                prob.solve(pulp.GLPK(msg=0))
            else:
                sys.exit('no solver specified')

        # retreive the optimal subset of sentences
        solution = set([j for j in range(S) if s[j].varValue == 1])

        # returns the (objective function value, solution) tuple
        return (pulp.value(prob.objective), solution)
Esempio n. 17
0
                    for k in storage) >= MinPctDemand * sumdk
model += pulp.lpSum(Xjk[j, k] * TransCostjk.ix[(j, k), 2] for j in warehouse
                    for k in storage) >= MinPctDemand * sumdk
model += pulp.lpSum(Xjk[j, k] * TransCostjk.ix[(j, k), 3] for j in warehouse
                    for k in storage) >= MinPctDemand * sumdk

#Quantity - Quality linking constraint
for i in supplier:
    for j in warehouse:
        model += Xij[(i, j)] * (1 - defective) >= netXij[(i, j)]

#Number of facilities
model += pulp.lpSum([zj[j] for j in warehouse]) >= zmin
model += pulp.lpSum([zj[j] for j in warehouse]) <= zmax

solver = pulp.CPLEX()
model.setSolver(solver)
model.solve()

print(pulp.LpStatus[model.status])
print(pulp.value(model.objective))

count1 = 0
count2 = 0

for j in warehouse:
    if (zj[j].varValue == 1):
        print pulp.lpSum(Xjk[j, k].varValue for k in storage)
        if (pulp.lpSum(Xjk[j, k].varValue for k in storage) >= 1000000):
            FacilityCost = 300000
            count1 = count1 + 1
Esempio n. 18
0
###############################################################

###############################################################
# Fitting the models
# 3 hour time limit, note this does not count the presolve time
tl = 3 * 60 * 60

pmed12 = pmed(Ar=areas,
              Di=dist_dict,
              Co=cont_dict,
              Ca=call_dict,
              Ta=12,
              In=0.1,
              Th=10)
pmed12.solve(solver=pulp.CPLEX(timeLimit=tl,
                               msg=True))  # takes around 10 minutes
#pmed12.solve(solver=pulp.SCIP_CMD(msg=True)) # takes about 5 hours to get the solution
#pmed12.solve(solver=pulp.GLPK_CMD(timeLimit=tl,msg=True)) # does not converge even after 12+ hours

# Showing a map
pmed12.map_plot(carr_report, 'PDGrid')

# Figure out subtours
stres = pmed12.collect_subtours()

# Resolving with warm start with subtour constraints
pmed12.solve(solver=pulp.CPLEX_CMD(timeLimit=tl, msg=False, warmStart=True))

# Now it is OK
stres = pmed12.collect_subtours()
pmed12.map_plot(carr_report, 'PDGrid')
Esempio n. 19
0
import pulp as solver
from pulp import *
import Graph
import os
import gc
import signal
from tqdm import tqdm
z = 0
solvers = [solver.CPLEX(timeLimit=7200), solver.GLPK(), solver.GUROBI()]
solverUsado = 0

problems_packing = [
    "Instances/packing/" + i for i in os.listdir("Instances/packing/")
]
problems_sep = [
    "Instances/separated/" + i for i in os.listdir("Instances/separated/")
]
problems = problems_packing + problems_sep
print(problems)


#problems = problems[3:]
def signal_handler(signum, frame):
    raise Exception("Timed out!")


for ptk in problems:
    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(8100)
    try:
        print("Initializing graph", ptk)
Esempio n. 20
0
def avg_link_utilization():
    h12 = 5
    h13 = 10
    h23 = 7

    cap12 = 10
    cap13 = 10
    cap23 = 15

    prob = pulp.LpProblem("3Node_MultiCommodity_AvgDelay", pulp.LpMinimize)

    # Defining the Flow Variables
    x12 = pulp.LpVariable('x12', lowBound=0, cat='Continuous')
    x132 = pulp.LpVariable('x132', lowBound=0, cat='Continuous')

    x13 = pulp.LpVariable('x13', lowBound=0, cat='Continuous')
    x123 = pulp.LpVariable('x123', lowBound=0, cat='Continuous')

    x23 = pulp.LpVariable('x23', lowBound=0, cat='Continuous')
    x213 = pulp.LpVariable('x213', lowBound=0, cat='Continuous')

    y12 = pulp.LpVariable('y12', lowBound=0, cat='Continuous')
    y13 = pulp.LpVariable('y13', lowBound=0, cat='Continuous')
    y23 = pulp.LpVariable('y23', lowBound=0, cat='Continuous')

    z12 = pulp.LpVariable('z12', lowBound=0)
    z13 = pulp.LpVariable('z13', lowBound=0)
    z23 = pulp.LpVariable('z23', lowBound=0)

    # Adding Objective Function
    prob += (z12 * math.pow(cap12, -1) + z13 * math.pow(cap13, -1) + z23 * math.pow(cap23, -1))

    # Subject to Constraints
    prob += (x12 + x132 == h12)
    prob += (x13 + x123 == h13)
    prob += (x23 + x213 == h23)
    prob += (x12 + x123 + x213 == y12)
    prob += (x13 + x132 + x213 == y13)
    prob += (x23 + x123 + x123 == y23)

    prob += (z12 * 2 >= 3 * y12)
    prob += (z13 * 2 >= 3 * y13)
    prob += (z23 * 2 >= 3 * y23)

    prob += (z12 * 2 >= 9 * y12 - 2 * cap12)
    prob += (z13 * 2 >= 9 * y13 - 2 * cap13)
    prob += (z23 * 2 >= 9 * y23 - 2 * cap23)

    prob += (z12 >= 15 * y12 - 8 * cap12)
    prob += (z13 >= 15 * y13 - 8 * cap13)
    prob += (z23 >= 15 * y23 - 8 * cap23)

    prob += (z12 >= 50 * y12 - 36 * cap12)
    prob += (z13 >= 50 * y13 - 36 * cap13)
    prob += (z23 >= 50 * y23 - 36 * cap23)

    prob += (z12 >= 200 * y12 - 171 * cap12)
    prob += (z13 >= 200 * y13 - 171 * cap13)
    prob += (z23 >= 200 * y23 - 171 * cap23)

    prob += (z12 >= 4000 * y12 - 3781 * cap12)
    prob += (z13 >= 4000 * y13 - 3781 * cap13)
    prob += (z23 >= 4000 * y23 - 3781 * cap23)

    # Print the Problem
    print(prob)

    prob.writeLP("3node_MCF_AvgDelay.lp")

    # solve the LP using the CPLEX Solver
    optimization_result = prob.solve(pulp.CPLEX())

    # make sure we got an optimal solution
    assert optimization_result == pulp.LpStatusOptimal

    # display the results
    for var in (x12, x132, x13, x123, x23, x213):
        print('Optimal Flow for {} is {:1.0f}'.format(var.name, var.value()))
Esempio n. 21
0
def optimizeTrajectory(N, T, T_end, V, P, W, M, m, TSFC, minApproachDist, x_ini, x_fin, x_lim, u_lim, objects, r):

  # --------------------
  # Calculated Variables
  # --------------------
  del_t = T_end/T
  numObjects = objects.shape[0]

  # ------------------
  # Decision variables
  # ------------------
  # Thrust
  u = pulp.LpVariable.dicts(
    "input", ((i, p, n) for i in range(T) for p in range(V) for n in range(N)),
    cat='Continuous')
  # Thrust Magnitude
  v = pulp.LpVariable.dicts(
    "inputMag", ((i, p, n) for i in range(T) for p in range(V) for n in range(N)),
    lowBound=0,
    cat='Continuous')
  # State
  x = pulp.LpVariable.dicts(
    "state", ((i, p, k) for i in range(T) for p in range(V) for k in range(2*N)),
    cat='Continuous')
  # Object collision
  a = pulp.LpVariable.dicts(
    "objCol", ((i, p, l, k) for i in range(T) for p in range(V) for l in range(numObjects) for k in range(2*N)),
    cat='Binary')
  # Satellite Collision Avoidance
  b = pulp.LpVariable.dicts(
    "satelliteCollisionAvoidance", ((i, p, q, k) for i in range(T) for p in range(V) for q in range(V) for k in range(2*N)),
    cat='Binary')
  # Plume Impingement
  c_plus = pulp.LpVariable.dicts(
    "plumeImpingementPositive", ((i, p, q, n, k) for i in range(T) for p in range(V) for q in range(V) for n in range(N) for k in range(2*N)),
    cat='Binary')
  c_minus = pulp.LpVariable.dicts(
    "plumeImpingementNegative", ((i, p, q, n, k) for i in range(T) for p in range(V) for q in range(V) for n in range(N) for k in range(2*N)),
    cat='Binary')

  # ------------------
  # Optimization Model
  # ------------------

  # Instantiate Model
  model = pulp.LpProblem("Satellite Fuel Minimization Problem", pulp.LpMinimize)
  # Objective Function
  model += pulp.lpSum(v[i, p, n] for i in range(T) for p in range(V) for n in range(N)), "Fuel Minimization"

  # -----------
  # Constraints
  # -----------

  # Basic Constraints
  # -----------------
  # Constrain thrust magnitude to abs(u[i, p, n])
  for i in range(T):
    for p in range(V):
      for n in range(N):
        model +=  u[i, p, n] <= v[i, p, n]
        model += -u[i, p, n] <= v[i, p, n]
  # State and Input vector start and end values
  for p in range(V):
    for k in range(2*N):
      model += x[0, p, k]   == x_ini[p, k]
      model += x[T-1, p, k] == x_fin[p, k]
  # Model Dynamics
  for constraint in freeSpaceDynamics(x, u, T, V, N, m, del_t):
    model += constraint
  # State and Input vector limits
  for i in range(T):
    for p in range(V):
      for n in range(N):
        model += u[i, p, n] <=  u_lim[p, n]
        model += u[i, p, n] >= -u_lim[p, n]
      for k in range(2*N): # Necessary?
        model += x[i, p, k] <=  x_lim[p, k]
        model += x[i, p, k] >= -x_lim[p, k]

  # Obstacle Avoidance
  # ------------------
  if objects.shape[1] > 0:
    for i in range(T):
      for p in range(V):
        for l in range(numObjects):
          model += pulp.lpSum(a[i, p, l, n] for n in range(2*N)) <= 2*N-1
          for n in range(N):
            model += x[i, p, n] >= objects[l, N+n] + minApproachDist - M*a[i, p, l, N+n]
            model += x[i, p, n] <= objects[l, n] - minApproachDist + M*a[i, p, l, n]

  # Collision Avoidance
  # -------------------
  if V > 1: # If more than one vehicle
      for i in range(T):
        for p in range(V):
          for q in range(V):
            if q > p:
              model += pulp.lpSum(b[i, p, q, k] for k in range(2*N)) <= 2*N-1
              for n in range(N):
                model += x[i, p, n] - x[i, q, n] >= r[n] - M*b[i, p, q, n]
                model += x[i, q, n] - x[i, p, n] >= r[n] - M*b[i, p, q, n+N]

  # Plume Impingement
  # -----------------
  # Positive thrust
  if V > 1: # If more than one vehicle
      for i in range(T):
        for p in range(V):
          for q in range(V):
            if q != p:
              for n in range(N):
                model += pulp.lpSum(c_plus[i, p, q, n, k] for k in range(2*N)) <= 2*N
                model += -u[i, p, n] >= - M*c_plus[i, p, q, n, 0]
                model += x[i, p, n] - x[i, q, n] >= P - M*c_plus[i, p, q, n, n]
                model += x[i, q, n] - x[i, p, n] >= - M*c_plus[i, p, q, n, n+N]
                for m in range(N):
                  if m != n:
                    x[i, p, m] - x[i, q, m] >= W - M*c_plus[i, p, q, n, m]
                    x[i, q, m] - x[i, p, m] >= W - M*c_plus[i, p, q, n, m+N]
  # Negative thrust
      for i in range(T):
        for p in range(V):
          for q in range(V):
            if q != p:
              for n in range(N):
                model += pulp.lpSum(c_minus[i, p, q, n, k] for k in range(2*N)) <= 2*N
                model += u[i, p, n] >= - M*c_minus[i, p, q, n, 0]
                model += x[i, p, n] - x[i, q, n] >= - M*c_minus[i, p, q, n, n]
                model += x[i, q, n] - x[i, p, n] >= P - M*c_minus[i, p, q, n, n+N]
                for m in range(N):
                  if m != n:
                    x[i, p, m] - x[i, q, n] >= W - M*c_minus[i, p, q, n, m]
                    x[i, q, m] - x[i, p, m] >= W - M*c_minus[i, p, q, n, m+N]


  # Plume Avoidance for Vehicles
  # ----------------------------

  # Plume Avoidance for Obstacles
  # -----------------------------

  # Final Configuration Selection
  # -----------------------------

  # Solve model and return results in dictionary
  model.solve(pulp.CPLEX())

  # Create Pandas dataframe for results and return

  return {'model':model, 'x':x, 'u':u}
Esempio n. 22
0
import pulp as solver
from pulp import *
import time
import gc
z = 0
solvers = [
    solver.CPLEX(timeLimit=30),
    solver.GLPK(),
    solver.GUROBI(),
    solver.PULP_CBC_CMD(),
    solver.COIN()
]
solverUsado = 3


def solver_exact(g, init, final, is_first, is_last, name):
    var = [(i + ',' + str(t)) for i in g.edge for t in range(1, g.z)]
    var2 = [(str(i) + ',' + str(t)) for i in g.vertices for t in range(1, g.z)]

    X = solver.LpVariable.dicts("X", var, cat=solver.LpBinary)
    Y = solver.LpVariable.dicts("Y", var2, cat=solver.LpBinary)
    problem = solver.LpProblem("The_best_Cut", solver.LpMinimize)
    if is_first:
        problem += (solver.lpSum(
            X.get(
                str(i.split(',')[0]) + ',' + str(i.split(',')[1]) + ',' +
                str(t)) * g.mis[i.split(',')[0]][i.split(',')[1]]
            for i in g.edge for t in range(1, g.z)) + solver.lpSum(
                ((g.pis[k.split(',')[0]][k.split(',')[1]])) -
                ((g.mis[k.split(',')[0]][k.split(',')[1]]))
                for k in g.edgeCuts) / 2) + solver.lpSum(
Esempio n. 23
0
    def solve_ilp_problem(self, summary_size=1500,solver='glpk',  excluded_solutions=[]):
        """Solve the ILP formulation of the concept-based model.

        Args:
            summary_size (int): the maximum size in words of the summary,   摘要最大的单词数
              defaults to 100.
            solver (str): the solver used, defaults to glpk.  缺省解决办法glpk
            excluded_solutions (list of list): a list of subsets of sentences
              that are to be excluded, defaults to []


        Returns:
            (value, set) tuple (int, list): the value of the objective function
              and the set of selected sentences as a tuple.

        """
        # initialize container shortcuts
        concepts = self.weights.keys()#权重关键字
        w = self.weights#权重
        L = summary_size#摘要大小
        C = len(concepts)#权重概念数目
        S = len(self.sentences)#句子长度

        if not self.word_frequencies:
            self.compute_word_frequency()#如果不存在单词频率,则计算单词频率

        tokens = self.word_frequencies.keys()#单词频率的标记
        f = self.word_frequencies #单词频率
        T = len(tokens)#单词数目

        # HACK Sort keys
        concepts = sorted(self.weights, key=self.weights.get, reverse=True)#根据weight的key来进行排序

        # formulation of the ILP problem
        prob = pulp.LpProblem(self.input_directory, pulp.LpMaximize)

        # initialize the concepts binary variables
        c = pulp.LpVariable.dicts(name='c',
                                  indexs=range(C), #权重概念数目
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')
        #用来构造变量字典,可以让我们不用一个个地创建Lp变量实例。name指定所有变量的前缀,index是列表,其中的元素会被用来构成变量名
        #lowBound和upBound是下界和上界,默认分别是负无穷到正无穷,cat用来指定变量是离散(Integer,Binary)还是连续(Continuous)。

        # initialize the sentences binary variables
        s = pulp.LpVariable.dicts(name='s',
                                  indexs=range(S), #句子长度
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')

        # initialize the word binary variables
        t = pulp.LpVariable.dicts(name='t',
                                  indexs=range(T), #单词数目
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')

        # OBJECTIVE FUNCTION
        prob += sum(w[concepts[i]] * c[i] for i in range(C))#使得概念权重*概念变量之和最大


        # CONSTRAINT FOR SUMMARY SIZE 摘要大小的限制
        prob += sum(s[j] * self.sentences[j].length for j in range(S)) <= L #判断是否取句子进入摘要,总长度小于L,s[j]取值应该是1/0

        # INTEGRITY CONSTRAINTS 限制
        for i in range(C):
            for j in range(S):
                if concepts[i] in self.sentences[j].concepts:
                    prob += s[j] <= c[i]#如果s[j]小于等于c[i],那么prob加进去,不可能出现s[j]进去,c[j]没有的情况

        for i in range(C):
            prob += sum(s[j] for j in range(S)
                        if concepts[i] in self.sentences[j].concepts) >= c[i]  #c[i]肯定是要小于s[j]的

        # WORD INTEGRITY CONSTRAINTS


        # CONSTRAINTS FOR FINDING OPTIMAL SOLUTIONS
        for sentence_set in excluded_solutions:
            prob += sum([s[j] for j in sentence_set]) <= len(sentence_set)-1

        # prob.writeLP('test.lp')

        # solving the ilp problem
        if solver == 'gurobi':
            prob.solve(pulp.GUROBI(msg=0))
        elif solver == 'glpk':
            prob.solve(pulp.GLPK(msg=0))
        elif solver == 'cplex':
            prob.solve(pulp.CPLEX(msg=0))
        else:
            sys.exit('no solver specified')

        # retreive the optimal subset of sentences
        solution = set([j for j in range(S) if s[j].varValue == 1])

        # returns the (objective function value, solution) tuple
        return (pulp.value(prob.objective), solution)