Python pulp.LpMinimize() Examples
The following are 16
code examples of pulp.LpMinimize().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pulp
, or try the search function
.
Example #1
Source File: run_mskmeans.py From MinSizeKmeans with GNU General Public License v3.0 | 6 votes |
def create_model(self): def distances(assignment): return l2_distance(self.data[assignment[0]], self.centroids[assignment[1]]) clusters = list(range(self.k)) assignments = [(i, j)for i in range(self.n) for j in range(self.k)] # outflow variables for data nodes self.y = pulp.LpVariable.dicts('data-to-cluster assignments', assignments, lowBound=0, upBound=1, cat=pulp.LpInteger) # outflow variables for cluster nodes self.b = pulp.LpVariable.dicts('cluster outflows', clusters, lowBound=0, upBound=self.n-self.min_size, cat=pulp.LpContinuous) # create the model self.model = pulp.LpProblem("Model for assignment subproblem", pulp.LpMinimize) # objective function self.model += pulp.lpSum(distances(assignment) * self.y[assignment] for assignment in assignments) # flow balance constraints for data nodes for i in range(self.n): self.model += pulp.lpSum(self.y[(i, j)] for j in range(self.k)) == 1 # flow balance constraints for cluster nodes for j in range(self.k): self.model += pulp.lpSum(self.y[(i, j)] for i in range(self.n)) - self.min_size == self.b[j] # flow balance constraint for the sink node self.model += pulp.lpSum(self.b[j] for j in range(self.k)) == self.n - (self.k * self.min_size)
Example #2
Source File: label_prop_v2.py From transferlearning with MIT License | 5 votes |
def label_prop(C, nt, Dct, lp="linear"): #Inputs: # C : Number of share classes between src and tar # nt : Number of target domain samples # Dct : All d_ct in matrix form, nt * C # lp : Type of linear programming: linear (default) | binary #Outputs: # Mcj : all M_ct in matrix form, m * C Dct = abs(Dct) model = pulp.LpProblem("Cost minimising problem", pulp.LpMinimize) Mcj = pulp.LpVariable.dicts("Probability", ((i, j) for i in range(C) for j in range(nt)), lowBound=0, upBound=1, cat='Continuous') # Objective Function model += ( pulp.lpSum([Dct[j, i]*Mcj[(i, j)] for i in range(C) for j in range(nt)]) ) # Constraints for j in range(nt): model += pulp.lpSum([Mcj[(i, j)] for i in range(C)]) == 1 for i in range(C): model += pulp.lpSum([Mcj[(i, j)] for j in range(nt)]) >= 1 # Solve our problem model.solve() pulp.LpStatus[model.status] Output = [[Mcj[i, j].varValue for i in range(C)] for j in range(nt)] return np.array(Output)
Example #3
Source File: optimization_model_pulp.py From optimization-tutorial with MIT License | 5 votes |
def __init__(self, input_data, input_params): self.input_data = input_data self.input_params = input_params self.model = pulp.LpProblem(name='prod_planning', sense=pulp.LpMinimize) self._create_decision_variables() self._create_main_constraints() self._set_objective_function() # ================== Decision variables ==================
Example #4
Source File: minmax_kmeans.py From MinSizeKmeans with GNU General Public License v3.0 | 5 votes |
def create_model(self): def distances(assignment): return l2_distance(self.data[assignment[0]], self.centroids[assignment[1]]) clusters = list(range(self.k)) assignments = [(i, j)for i in range(self.n) for j in range(self.k)] # outflow variables for data nodes self.y = pulp.LpVariable.dicts('data-to-cluster assignments', assignments, lowBound=0, upBound=1, cat=pulp.LpInteger) # outflow variables for cluster nodes self.b = pulp.LpVariable.dicts('cluster outflows', clusters, lowBound=0, upBound=self.n-self.min_size, cat=pulp.LpContinuous) # create the model self.model = pulp.LpProblem("Model for assignment subproblem", pulp.LpMinimize) # objective function self.model += pulp.lpSum([distances(assignment) * self.y[assignment] for assignment in assignments]) # flow balance constraints for data nodes for i in range(self.n): self.model += pulp.lpSum(self.y[(i, j)] for j in range(self.k)) == 1 # flow balance constraints for cluster nodes for j in range(self.k): self.model += pulp.lpSum(self.y[(i, j)] for i in range(self.n)) - self.min_size == self.b[j] # capacity constraint on outflow of cluster nodes for j in range(self.k): self.model += self.b[j] <= self.max_size - self.min_size # flow balance constraint for the sink node self.model += pulp.lpSum(self.b[j] for j in range(self.k)) == self.n - (self.k * self.min_size)
Example #5
Source File: weighted_mm_kmeans.py From MinSizeKmeans with GNU General Public License v3.0 | 5 votes |
def create_model(self): def distances(assignment): return l2_distance(self.data[assignment[0]], self.centroids[assignment[1]]) assignments = [(i, j) for i in range(self.n) for j in range(self.k)] # assignment variables self.y = pulp.LpVariable.dicts('data-to-cluster assignments', assignments, lowBound=0, upBound=1, cat=pulp.LpInteger) # create the model self.model = pulp.LpProblem("Model for assignment subproblem", pulp.LpMinimize) # objective function self.model += pulp.lpSum([distances(assignment) * self.weights[assignment[0]] * self.y[assignment] for assignment in assignments]), 'Objective Function - sum weighted squared distances to assigned centroid' # this is also weighted, otherwise the weighted centroid computation don't make sense. # constraints on the total weights of clusters for j in range(self.k): self.model += pulp.lpSum([self.weights[i] * self.y[(i, j)] for i in range(self.n)]) >= self.min_weight, "minimum weight for cluster {}".format(j) self.model += pulp.lpSum([self.weights[i] * self.y[(i, j)] for i in range(self.n)]) <= self.max_weight, "maximum weight for cluster {}".format(j) # make sure each point is assigned at least once, and only once for i in range(self.n): self.model += pulp.lpSum([self.y[(i, j)] for j in range(self.k)]) == 1, "must assign point {}".format(i)
Example #6
Source File: space.py From qmpy with MIT License | 5 votes |
def _gclp(self, composition={}, mus={}, phases=[]): if not qmpy.FOUND_PULP: raise Exception('Cannot do GCLP without installing PuLP and an LP', 'solver') prob = pulp.LpProblem('GibbsEnergyMin', pulp.LpMinimize) phase_vars = pulp.LpVariable.dicts('lib', phases, 0.0) prob += pulp.lpSum([ (p.energy - sum([ p.unit_comp.get(elt,0)*mu for elt, mu in mus.items() ])) * phase_vars[p] for p in phases]),\ "Free Energy" for elt, constraint in composition.items(): prob += pulp.lpSum([ p.unit_comp.get(elt,0)*phase_vars[p] for p in phases ]) == float(constraint),\ 'Conservation of '+elt ##[vh] ##print prob if pulp.GUROBI().available(): prob.solve(pulp.GUROBI(msg=False)) elif pulp.COIN_CMD().available(): prob.solve(pulp.COIN_CMD()) else: prob.solve() phase_comp = dict([ (p, phase_vars[p].varValue) for p in phases if phase_vars[p].varValue > 1e-5]) energy = sum( p.energy*amt for p, amt in phase_comp.items() ) energy -= sum([ a*composition.get(e, 0) for e,a in mus.items()]) return energy, phase_comp
Example #7
Source File: space.py From qmpy with MIT License | 5 votes |
def get_minima(self, phases, bounds): """ Given a set of Phases, get_minima will determine the minimum free energy elemental composition as a weighted sum of these compounds """ prob = pulp.LpProblem('GibbsEnergyMin', pulp.LpMinimize) pvars = pulp.LpVariable.dicts('phase', phases, 0) bvars = pulp.LpVariable.dicts('bound', bounds, 0.0, 1.0) prob += pulp.lpSum( self.phase_energy(p)*pvars[p] for p in phases ) - \ pulp.lpSum( self.phase_energy(bound)*bvars[bound] for bound in bounds ), \ "Free Energy" for elt in self.bound_space: prob += sum([ p.unit_comp.get(elt,0)*pvars[p] for p in phases ])\ == \ sum([ b.unit_comp.get(elt, 0)*bvars[b] for b in bounds ]),\ 'Contraint to the proper range of'+elt prob += sum([ bvars[b] for b in bounds ]) == 1, \ 'sum of bounds must be 1' if pulp.GUROBI().available(): prob.solve(pulp.GUROBI(msg=False)) elif pulp.COIN_CMD().available(): prob.solve(pulp.COIN_CMD()) elif pulp.COINMP_DLL().available(): prob.solve(pulp.COINMP_DLL()) else: prob.solve() E = pulp.value(prob.objective) xsoln = defaultdict(float, [(p, pvars[p].varValue) for p in phases if abs(pvars[p].varValue) > 1e-4]) return xsoln, E
Example #8
Source File: multiplier_model.py From pyDEA with MIT License | 5 votes |
def get_objective_type(self): ''' Returns pulp.LpMinimize - we minimize objective function in case of output-oriented multiplier model. Returns: pulp.LpMinimize. ''' return pulp.LpMinimize
Example #9
Source File: envelopment_model.py From pyDEA with MIT License | 5 votes |
def get_objective_type(self): ''' Returns pulp.LpMinimize - we minimize objective function in case of input-oriented envelopment model. Returns: pulp.LpMaximize: type of objective function. ''' return pulp.LpMinimize
Example #10
Source File: envelopment_model.py From pyDEA with MIT License | 5 votes |
def get_objective_type(self): ''' Returns pulp.LpMinimize - we maximize objective function in case of output-oriented envelopment model. Returns: pulp.LpMaximize: objective function type. ''' return pulp.LpMaximize
Example #11
Source File: simplex_test.py From GiMPy with Eclipse Public License 1.0 | 5 votes |
def solve(g): el = g.get_edge_list() nl = g.get_node_list() p = LpProblem('min_cost', LpMinimize) capacity = {} cost = {} demand = {} x = {} for e in el: capacity[e] = g.get_edge_attr(e[0], e[1], 'capacity') cost[e] = g.get_edge_attr(e[0], e[1], 'cost') for i in nl: demand[i] = g.get_node_attr(i, 'demand') for e in el: x[e] = LpVariable("x"+str(e), 0, capacity[e]) # add obj objective = lpSum (cost[e]*x[e] for e in el) p += objective # add constraints for i in nl: out_neig = g.get_out_neighbors(i) in_neig = g.get_in_neighbors(i) p += lpSum(x[(i,j)] for j in out_neig) -\ lpSum(x[(j,i)] for j in in_neig)==demand[i] p.solve() return x, value(objective)
Example #12
Source File: chemistry.py From chempy with BSD 2-Clause "Simplified" License | 5 votes |
def _solve_balancing_ilp_pulp(A): import pulp x = [pulp.LpVariable('x%d' % i, lowBound=1, cat='Integer') for i in range(A.shape[1])] prob = pulp.LpProblem("chempy balancing problem", pulp.LpMinimize) prob += reduce(add, x) for expr in [pulp.lpSum([x[i]*e for i, e in enumerate(row)]) for row in A.tolist()]: prob += expr == 0 prob.solve() return [pulp.value(_) for _ in x]
Example #13
Source File: LEMON.py From cdlib with BSD 2-Clause "Simplified" License | 5 votes |
def __min_one_norm(B, initial_seed, seed): weight_initial = 1 / float(len(initial_seed)) weight_later_added = weight_initial / float(0.5) difference = len(seed) - len(initial_seed) [r, c] = B.shape prob = pulp.LpProblem("Minimum one norm", pulp.LpMinimize) indices_y = range(0, r) y = pulp.LpVariable.dicts("y_s", indices_y, 0) indices_x = range(0, c) x = pulp.LpVariable.dicts("x_s", indices_x) f = dict(zip(indices_y, [1.0] * r)) prob += pulp.lpSum(f[i] * y[i] for i in indices_y) # objective function prob += pulp.lpSum(y[s] for s in initial_seed) >= 1 prob += pulp.lpSum(y[r] for r in seed) >= 1 + weight_later_added * difference for j in range(r): temp = dict(zip(indices_x, list(B[j, :]))) prob += pulp.lpSum(y[j] + (temp[k] * x[k] for k in indices_x)) == 0 prob.solve() result = [] for var in indices_y: result.append(y[var].value()) return result
Example #14
Source File: process_path.py From Cogent with BSD 3-Clause Clear License | 5 votes |
def make_into_lp_problem(good_for, N, add_noise=False): """ Helper function for solve_with_lp_and_reduce() N --- number of isoform sequences good_for --- dict of <isoform_index> --> list of matched paths index """ prob = LpProblem("The Whiskas Problem",LpMinimize) # each good_for is (isoform_index, [list of matched paths index]) # ex: (0, [1,2,4]) # ex: (3, [2,5]) used_paths = [] for t_i, p_i_s in good_for: used_paths += p_i_s used_paths = list(set(used_paths)) variables = [LpVariable(str(i),0,1,LpInteger) for i in used_paths] #variables = [LpVariable(str(i),0,1,LpInteger) for i in xrange(N)] # objective is to minimize sum_{Xi} prob += sum(v for v in variables) already_seen = set() # constraints are for each isoform, expressed as c_i * x_i >= 1 # where c_i = 1 if x_i is matched for the isoform # ex: (0, [1,2,4]) becomes t_0 = x_1 + x_2 + x_4 >= 1 for t_i, p_i_s in good_for: #c_i_s = [1 if i in p_i_s else 0 for i in xrange(N)] #prob += sum(variables[i]*(1 if i in p_i_s else 0) for i in xrange(N)) >= 1 p_i_s.sort() pattern = ",".join(map(str,p_i_s)) #print >> sys.stderr, t_i, p_i_s, pattern if pattern not in already_seen: if add_noise: prob += sum(variables[i]*(1+random.random() if p in p_i_s else 0) for i,p in enumerate(used_paths)) >= 1 else: prob += sum(variables[i]*(1 if p in p_i_s else 0) for i,p in enumerate(used_paths)) >= 1 already_seen.add(pattern) prob.writeLP('cogent.lp') return prob
Example #15
Source File: wordmoverdist.py From PyShortTextCategorization with MIT License | 4 votes |
def word_mover_distance_probspec(first_sent_tokens, second_sent_tokens, wvmodel, distancefunc=euclidean, lpFile=None): """ Compute the Word Mover's distance (WMD) between the two given lists of tokens, and return the LP problem class. Using methods of linear programming, supported by PuLP, calculate the WMD between two lists of words. A word-embedding model has to be provided. The problem class is returned, containing all the information about the LP. Reference: Matt J. Kusner, Yu Sun, Nicholas I. Kolkin, Kilian Q. Weinberger, "From Word Embeddings to Document Distances," *ICML* (2015). :param first_sent_tokens: first list of tokens. :param second_sent_tokens: second list of tokens. :param wvmodel: word-embedding models. :param distancefunc: distance function that takes two numpy ndarray. :param lpFile: log file to write out. :return: a linear programming problem contains the solution :type first_sent_tokens: list :type second_sent_tokens: list :type wvmodel: gensim.models.keyedvectors.KeyedVectors :type distancefunc: function :type lpFile: str :rtype: pulp.LpProblem """ all_tokens = list(set(first_sent_tokens+second_sent_tokens)) wordvecs = {token: wvmodel[token] for token in all_tokens} first_sent_buckets = tokens_to_fracdict(first_sent_tokens) second_sent_buckets = tokens_to_fracdict(second_sent_tokens) T = pulp.LpVariable.dicts('T_matrix', list(product(all_tokens, all_tokens)), lowBound=0) prob = pulp.LpProblem('WMD', sense=pulp.LpMinimize) prob += pulp.lpSum([T[token1, token2]*distancefunc(wordvecs[token1], wordvecs[token2]) for token1, token2 in product(all_tokens, all_tokens)]) for token2 in second_sent_buckets: prob += pulp.lpSum([T[token1, token2] for token1 in first_sent_buckets])==second_sent_buckets[token2] for token1 in first_sent_buckets: prob += pulp.lpSum([T[token1, token2] for token2 in second_sent_buckets])==first_sent_buckets[token1] if lpFile!=None: prob.writeLP(lpFile) prob.solve() return prob
Example #16
Source File: covering.py From pyspatialopt with MIT License | 4 votes |
def create_lscp_model(coverage_dict, model_file=None, delineator="$", ): """ Creates a LSCP (Location set covering problem) using the provided coverage and parameters. Writes a .lp file which can be solved with Gurobi Church, R., & Murray, A. (2009). Coverage Business Site Selection, Location Analysis, and GIS (pp. 209-233). Hoboken, New Jersey: Wiley. :param coverage_dict: (dictionary) The coverage to use to generate the model :param model_file: (string) The model file to output :param delineator: (string) The character(s) to use to delineate the layer from the ids :return: (Pulp problem) The generated problem to solve """ validate_coverage(coverage_dict, ["coverage"], ["binary"]) if not isinstance(coverage_dict, dict): raise TypeError("coverage_dict is not a dictionary") if model_file and not (isinstance(model_file, str)): raise TypeError("model_file is not a string") if not isinstance(delineator, str): raise TypeError("delineator is not a string") # create the variables demand_vars = {} for demand_id in coverage_dict["demand"]: demand_vars[demand_id] = pulp.LpVariable("Y{}{}".format(delineator, demand_id), 0, 1, pulp.LpInteger) facility_vars = {} for facility_type in coverage_dict["facilities"]: facility_vars[facility_type] = {} for facility_id in coverage_dict["facilities"][facility_type]: facility_vars[facility_type][facility_id] = pulp.LpVariable( "{}{}{}".format(facility_type, delineator, facility_id), 0, 1, pulp.LpInteger) # create the problem prob = pulp.LpProblem("LSCP", pulp.LpMinimize) # Create objective, minimize number of facilities to_sum = [] for facility_type in coverage_dict["facilities"]: for facility_id in coverage_dict["facilities"][facility_type]: to_sum.append(facility_vars[facility_type][facility_id]) prob += pulp.lpSum(to_sum) # add coverage constraints for demand_id in coverage_dict["demand"]: to_sum = [] for facility_type in coverage_dict["demand"][demand_id]["coverage"]: for facility_id in coverage_dict["demand"][demand_id]["coverage"][facility_type]: to_sum.append(facility_vars[facility_type][facility_id]) # Hack to get model to "solve" when infeasible with GLPK. # Pulp will automatically add dummy variables when the sum is empty, since these are all the same name, # it seems that GLPK doesn't read the lp problem properly and fails if not to_sum: to_sum = [pulp.LpVariable("__dummy{}{}".format(delineator, demand_id), 0, 0, pulp.LpInteger)] prob += pulp.lpSum(to_sum) >= 1, "D{}".format(demand_id) if model_file: prob.writeLP(model_file) return prob