def test_threshold(self): threshold = covering.create_threshold_model( self.binary_coverage_point2, 30) threshold_i = covering.create_threshold_model( self.binary_coverage_point2, 100) threshold.solve(pulp.GLPK()) threshold_i.solve(pulp.GLPK()) ids = utilities.get_ids(threshold, "facility2_service_areas") self.assertEqual(['10', '17', '4'], ids) self.assertEqual(threshold_i.status, pulp.constants.LpStatusInfeasible)
def test_traumah(self): traumah = covering.create_traumah_model(self.traumah_coverage, 5, 10) traumah_i = covering.create_traumah_model(self.traumah_coverage, 100, 100) traumah.solve(pulp.GLPK()) traumah_i.solve(pulp.GLPK()) ad_ids = utilities.get_ids(traumah, "AirDepot") tc_ids = utilities.get_ids(traumah, "TraumaCenter") self.assertEqual(['0', '1', '2', '3', '5'], ad_ids) self.assertEqual( ['10', '12', '15', '16', '18', '19', '21', '22', '7', '9'], tc_ids) self.assertEqual(traumah_i.status, pulp.constants.LpStatusInfeasible)
def test_cc_threshold(self): ccthreshold = covering.create_cc_threshold_model( self.partial_coverage2, 80) ccthreshold_i = covering.create_cc_threshold_model( self.partial_coverage2, 100) ccthreshold.solve(pulp.GLPK()) ccthreshold_i.solve(pulp.GLPK()) ids = utilities.get_ids(ccthreshold, "facility2_service_areas") self.assertEqual([ '1', '11', '13', '15', '17', '19', '20', '21', '22', '3', '4', '5', '7', '9' ], ids) self.assertEqual(ccthreshold_i.status, pulp.constants.LpStatusInfeasible)
def solve(self): # solve each LP sequentially start_time = time.time() for j, lp in enumerate(self.LPs): lp['prob'].solve(plp.GLPK(keepFiles=0, msg=0)) # save solution time (without overhead) self.solution_time = time.time() - start_time # select the LP that yielded the highest objective value optimal_LPs = filter(lambda x: x['prob'].status == plp.LpStatusOptimal, self.LPs) objective_values = list( map(lambda x: plp.value(x['prob'].objective), optimal_LPs)) opt_q, opt_value = max(enumerate(objective_values), \ key=operator.itemgetter(1)) # save the solution in instance variables self.opt_attacker_pure_strategy = opt_q self.opt_defender_payoff = opt_value self.opt_defender_mixed_strategy = \ list(map(lambda x: plp.value(x), self.LPs[opt_q]['x'])) # save solution time with overhead self.solution_time_with_overhead = time.time() - start_time
def optimal_matching(candidates_lhs, candidates_rhs, match_cost_function, nonmatch_cost_function, cost_threshold=None): '''Match two sets of candidates by minimizing total association costs. The elements at the left-hand side (lhs) are paired with the elements at the right-hand side (rhs) in a globally optimal manner with respect to the association costs. Returns a dictionary of associations of the form: {'lhs': {lhs_instance: rhs_instance}, 'rhs': {rhs_instance: lhs_instance}} In case of a nonmatch, the instance is associated with None. candidates_lhs -- iterable of candidate instances candidates_rhs -- iterable of candidate instances match_cost_function -- f(candidate_lhs, candidate_lhs) :: instance -> instance -> number nonmatch_cost_function -- f(candidate_lhs_or_rhs) :: instance -> number cost_threshold -- only consider associations below this threshold (runtime tuning parameter); applies only to match costs ''' if candidates_lhs or candidates_rhs: # at least one set has to be non-empty; else, ilp would be rejected by solver graph = _construct_match_graph(candidates_lhs, candidates_rhs, match_cost_function, nonmatch_cost_function, cost_threshold) ilp, variables = _formulate_integer_linear_program(graph) ilp.solve(_pulp.GLPK(msg=False)) assoc = _formulate_associations(graph, variables) else: assoc = {'lhs': {}, 'rhs': {}} return assoc
def run_example(): providers = QgsProviderRegistry.instance().providerList() for provider in providers: print(provider) print(QgsApplication.showSettings()) demand_points = QgsVectorLayer("/Users/andrewlaird/Desktop/QGIS Mapping/points_2.shp", "demand_points", "ogr") print(demand_points.isValid()) service_areas = QgsVectorLayer("/Users/andrewlaird/Desktop/QGIS Mapping/zones.shp", "service_areas", "ogr") print(service_areas.isValid()) binary_coverage_polygon = pyqgis_analysis.generate_binary_coverage(demand_points, service_areas, "od_rate", "point_id", "zone_id") print(binary_coverage_polygon) # Create the mclp model # Maximize the total coverage (binary polygon) using at most 5 out of 8 facilities logger.info("Creating MCLP model...") mclp = covering.create_threshold_model(binary_coverage_polygon, 100.0) # Solve the model using GLPK logger.info("Solving MCLP...") mclp.solve(pulp.GLPK()) # Get the unique ids of the 5 facilities chosen logger.info("Extracting results") ids = utilities.get_ids(mclp, "zones") # Generate a query that could be used as a definition query or selection in arcpy select_query = pyqgis_analysis.generate_query(ids, unique_field_name="zone_id") logger.info("Output query to use to generate maps is: {}".format(select_query)) # Determine how much demand is covered by the results service_areas.setSubsetString(select_query) total_coverage = pyqgis_analysis.get_covered_demand(demand_points, "od_rate", "binary", service_areas) logger.info("{0:.2f}% of demand is covered".format((100 * total_coverage) / binary_coverage_polygon["totalDemand"]))
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 += sum(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 += sum(x[i] * self.sentences[i].length for i in self.sentences_idx) <= self.sum_length for j in self.ref_ngrams_idx: prob += sum(A[i][j] * x[i] for i in self.sentences_idx) >= z[j] # Solve ILP problem and post-processing to get the summary 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
def test_glpk(self, ilp): """Test method for GLPK.""" try: ilp.solve(pulp.GLPK()) assert round(pulp.value(ilp.objective), 0) == 5 except pulp.solvers.PulpSolverError: pytest.fail(f"Solver not installed")
def solve(self): # use GLPK solver start_time = time.time() self.prob.solve(plp.GLPK(keepFiles=0, msg=0)) # save solution time (without overhead) self.solution_time = time.time() - start_time # save status self.status = plp.LpStatus[self.prob.status] # compute optimal attacked target and defender payoff self.opt_defender_payoff = plp.value(self.prob.objective) # derive and save the optimal defender mixed strategy self.opt_defender_mixed_strategy = np.zeros((self.X)) for i in range(self.X): for j in range(self.Q): if plp.value(self.z[i, j, 0]) > 0: self.opt_defender_mixed_strategy[i] = \ plp.value(self.z[i,j,0]) break # derive and save the optimal attacked target for each attacker type self.opt_attacker_pure_strategy = np.zeros((self.L), dtype=np.int8) f = np.vectorize(plp.value) qs = f(self.q) for l in range(self.L): self.opt_attacker_pure_strategy[l] = np.nonzero(qs[:, l])[0][0] # convert to tuple self.opt_attacker_pure_strategy = tuple( self.opt_attacker_pure_strategy) # save solution time with overhead self.solution_time_with_overhead = time.time() - start_time
def test_multiple_supply_arcgis(self): demand_col = "Population" demand_id_col = "GEOID10" supply_id_col = "ORIG_ID" d = arcgis.GeoAccessor.from_featureclass( os.path.join(self.dir_name, "../test_data/demand_point.shp")) s = arcgis.GeoAccessor.from_featureclass( os.path.join(self.dir_name, "../test_data/facility_service_areas.shp")) s2 = arcgis.GeoAccessor.from_featureclass( os.path.join(self.dir_name, "../test_data/facility2_service_areas.shp")) coverage = Coverage.from_spatially_enabled_dataframes( d, s, demand_id_col, supply_id_col, demand_col=demand_col) coverage2 = Coverage.from_spatially_enabled_dataframes( d, s2, demand_id_col, supply_id_col, demand_name=coverage.demand_name, demand_col=demand_col) problem = Problem.lscp([coverage, coverage2]) problem.solve(pulp.GLPK()) selected_locations = problem.selected_supply(coverage) selected_locations2 = problem.selected_supply(coverage2) covered_demand = d.query( f"{demand_id_col} in ({[f'{i}' for i in problem.selected_demand(coverage)]})" ) coverage = math.ceil( (covered_demand[demand_col].sum() / d[demand_col].sum()) * 100) assert (len(selected_locations) >= 5) assert (len(selected_locations2) >= 17) assert (coverage == 100)
def solve(definition): print >> sys.stderr, '-' * 20, 'problem' print >> sys.stderr, definition if debug > 1: print >> sys.stderr, '-' * 20, 'parse' exs, vars_, target, cat, mm = parse(definition) if debug > 1: print >> sys.stderr, '-' * 20, 'setup' prob, target2, lpvar = setup(exs, vars_, target, cat, mm) if debug > 1: print >> sys.stderr, '-' * 20, 'solve' status = prob.solve(pulp.GLPK(msg=0)) print >> sys.stderr, '-' * 20, 'result' print pulp.LpStatus[status] if pulp.LpStatus[status] == 'Optimal': def sort_var_name(x, y): t = cmp(len(x), len(y)) return t if t != 0 else cmp(x, y) res = {} for n in sorted(vars_, sort_var_name): v = pulp.value(lpvar[n]) res[n] = v print n, ':', v print 'target:', eval(target, res), '=', target2
def __solveEdgeCost__(self, solver, fileName="network.dmx"): # Add objective objective = [] for v, edge in self.__edges.items(): objective.append(edge.getCost() * edge.getLPVar()) self.__prob__ += pulp.lpSum(objective) # Add Constraints for loop in self.loops: self.__prob__.addConstraint(loop.getLPFlowConstraint()) # Solve the objective function if solver == 'glpk': log.info('Using GLPK MIP solver') MIPsolver = lambda: self.__prob__.solve(pulp.GLPK(msg=0)) elif solver == 'pulp': log.info('Using PuLP MIP solver') MIPsolver = lambda: self.__prob__.solve() elif solver == 'gurobi': log.info('Using Gurobi MIP solver') MIPsolver = lambda: self.__prob__.solve(pulp.GUROBI_CMD()) log.info('Time Taken (in sec) to solve: %f', T.timeit(MIPsolver, number=1)) # Get solution for v, edge in self.__edges.items(): flow = pulp.value(edge.getLPVar()) edge.updateFlow(flow)
def add_box_bounds(c_vec, A_mat, b_vec): A_bounded = list(A_mat.copy()) b_bounded = list(b_vec.copy()) prob = pulp.LpProblem('prob', pulp.LpMinimize) m, n = A_mat.shape x = [pulp.LpVariable('x{}'.format(ix)) for ix in range(n)] prob += pulp.lpSum([ci * xi for ci, xi in zip(c_vec, x)]) for ix in range(m): prob += pulp.lpSum([ai * xi for ai, xi in zip(A_mat[ix], x) ]) >= b_vec[ix], 'con{}'.format(ix) prob.solve(pulp.GLPK(msg=0)) if prob.status in [1, -2]: bound = np.max(np.abs([xi.varValue for xi in x])) * 1.1 else: raise Exception('Failed to add box bounds. Problem infeasible.') for ix in range(n): row_ub = np.zeros(n) row_ub[ix] = -1 A_bounded.append(row_ub) b_bounded.append(-1 * bound) row_lb = np.zeros(n) row_lb[ix] = 1 A_bounded.append(row_lb) b_bounded.append(-1 * bound) A_new = np.array(A_bounded) b_new = np.array(b_bounded) feas_exists = check_lpsolver(c_vec, A_new, b_new) assert feas_exists == True, 'Box bounds made the problem infeasible.' return A_new, b_new
def solve_ilp(objective, constraints): """Solve the integer programming problem. Args: objective: the function you are going to minimize constraints: the possible constraints you are going to follow while optimizing the objective Returns: None: if there is no possible solution for the optimization problem otherwise, returns the variables suitable for the optimization problem """ print("objective", objective) print("constraaints", constraints) prob = pulp.LpProblem('LP1', pulp.LpMinimize) prob += objective for cons in constraints: prob += cons print("prob", prob) # The MIP solver will terminate (with an optimal result) # when the gap between the lower and upper objective bound # is less than MIPGap times the absolute value of the upper bound. status = prob.solve(pulp.GLPK(options=['--mipgap', '0', '--cgr'])) # status = prob.solve(pulp.COIN_CMD(fracGap = 0)); # status = prob.solve(pulp.PULP_CBC_CMD()); # default if status != 1: # print('status', status) # LpStatus = {-3: 'Undefined', -2: 'Unbounded', -1: 'Infeasible', 0: # 'No... return None else: return [v.varValue.real for v in prob.variables()]
def test_lscp(self): merged_dict = covering.merge_coverages( [self.binary_coverage_point, self.binary_coverage_point2]) merged_dict = covering.update_serviceable_demand( merged_dict, self.serviceable_demand_point) lscp = covering.create_lscp_model(merged_dict) lscp_i = covering.create_lscp_model(self.binary_coverage_point2) lscp.solve(pulp.GLPK()) lscp_i.solve(pulp.GLPK()) ids = utilities.get_ids(lscp, "facility_service_areas") ids2 = utilities.get_ids(lscp, "facility2_service_areas") self.assertEqual(['3', '4', '5', '6', '7'], ids) self.assertEqual([ '0', '1', '11', '12', '13', '14', '15', '16', '17', '18', '19', '2', '20', '21', '22', '4', '5', '6', '9' ], ids2) self.assertEqual(lscp_i.status, pulp.constants.LpStatusInfeasible)
def test_cc_threshold(self): ccthreshold = covering.create_cc_threshold_model( self.partial_coverage2, 80, "ccthreshold.lp") ccthreshold.solve(pulp.GLPK()) ids = utilities.get_ids(ccthreshold, "facility2_service_areas") self.assertEqual([ '1', '11', '13', '15', '17', '19', '20', '21', '22', '3', '4', '5', '7', '9' ], ids)
def find_max(cutoff, data): N = len(data) indices = [] weights = [] for i in range(2, N): indices.append((i, i-1, i-2)) w = data[i] + data[i-1] + data[i-2] if w > cutoff: weights.append(w) else: weights.append(0) # print '' # print 'Nonzero cumulative sums:' # for (i, w) in enumerate(weights): # if w > 0: print 'weights[%d] = %.2f' % (i, w) # Nothing to do in the degenerate case. if [x for x in weights if x > 0] == []: return None prob = pulp.LpProblem('maxcsums', pulp.LpMaximize) x_vars = [ pulp.LpVariable('x' + str(i), cat='Binary') for (i, _) in enumerate(weights) ] prob += reduce(lambda a,b: a+b, [ weights[i]*x_vars[i] for i in range(len(weights))]) def is_adjacent(x, y): assert len(x) == 3 assert len(y) == 3 (x0, x1, x2) = x return (x0 in y or x1 in y or x2 in y) for (i, x) in enumerate(indices): for (j, y) in enumerate(indices): if x < y: if is_adjacent(x, y): prob += x_vars[i] + x_vars[j] <= 1 pulp.GLPK(options=['--mipgap', MIPGAP]).solve(prob) soln = [] data_ix = {} for v in prob.variables(): this_var = int(v.name[1:]) if v.varValue == 1: soln.append(this_var) data_ix[this_var] = indices[this_var] return (data_ix, indices, weights, soln, pulp.value(prob.objective))
def test_bclpcc(self): merged_dict = covering.merge_coverages( [self.partial_coverage, self.partial_coverage2]) merged_dict = covering.update_serviceable_demand( merged_dict, self.serviceable_demand_polygon) bclpcc = covering.create_bclpcc_model(merged_dict, {"total": 3}, 0.2) bclpcc.solve(pulp.GLPK()) ids = utilities.get_ids(bclpcc, "facility_service_areas") ids2 = utilities.get_ids(bclpcc, "facility2_service_areas") self.assertEqual(['4'], ids) self.assertEqual(['10'], ids2)
def test_single_supply_arcgis(self): demand_id_col = "GEOID10" supply_id_col = "ORIG_ID" d = arcgis.GeoAccessor.from_featureclass( os.path.join(self.dir_name, "../test_data/demand_point.shp")) s = arcgis.GeoAccessor.from_featureclass( os.path.join(self.dir_name, "../test_data/facility_service_areas.shp")) coverage = Coverage.from_spatially_enabled_dataframes( d, s, demand_id_col, supply_id_col) problem = Problem.lscp(coverage) with pytest.raises((InfeasibleException, UndefinedException)) as e: problem.solve(pulp.GLPK())
def test_single_supply(self): demand_id_col = "GEOID10" supply_id_col = "ORIG_ID" d = geopandas.read_file( os.path.join(self.dir_name, "../test_data/demand_point.shp")) s = geopandas.read_file( os.path.join(self.dir_name, "../test_data/facility_service_areas.shp")) coverage = Coverage.from_geodataframes(d, s, demand_id_col, supply_id_col) problem = Problem.lscp(coverage) with pytest.raises((InfeasibleException, UndefinedException)) as e: problem.solve(pulp.GLPK())
def lp_solver(c_vec, A_mat, b_vec): prob = pulp.LpProblem('prob', pulp.LpMinimize) m, n = A_mat.shape x = [pulp.LpVariable('x{}'.format(ix)) for ix in range(n)] prob += pulp.lpSum([ ci * xi for ci, xi in zip(c_vec, x) ]) for ix in range(m): prob += pulp.lpSum([ ai * xi for ai, xi in zip(A_mat[ix], x) ]) >= b_vec[ix], 'con{}'.format(ix) prob.solve(pulp.GLPK(msg=0)) if prob.status in [1, -2, -3]: x_vec = np.array([ xi.varValue for xi in x ]) return x_vec else: return None
def get_solve(data): x = [] for i in range(data.get('num_caches')): x.append([]) for j in range(data.get('num_videos')): x[i].append(pulp.LpVariable('x{}{}'.format(i, j), 0, 1)) prob = pulp.LpProblem('problem', pulp.LpMaximize) video_sizes = data.get('video_sizes') cache_sizes = data.get('cache_size') dc_latency = data.get('data_center_latency') latency = data.get('endpoint_cache_latency') reqs = data.get('endpoint_video_requests') n_caches = data.get('num_caches') n_endpoints = data.get('num_endpoints') n_videos = data.get('num_videos') for i in range(data.get('num_caches')): condition = pulp.lpSum( [x[i][j] * video_sizes[j] for j in range(data.get('num_videos'))]) prob += condition <= cache_sizes, 'Sizes for {} cache'.format(i) aim = [] from math import pow for e in range(data.get('num_endpoints')): for v in range(data.get('num_videos')): # cache_lat = latency[e][c] or dc_latency[e] # for c in range(data.get('num_caches')): # print(reqs[e][v]) dob = reqs[e][v] # print(pow(dob, 1 / n_caches)) # print(dob) d = pulp.LpAffineExpression([ (x[c][v], dob * (dc_latency[e] - (latency[e][c] or dc_latency[e]))) for c in range(n_caches) ]) aim.append(d) prob += pulp.lpSum(aim) print(12312312312, prob) status = prob.solve(pulp.GLPK(msg=0)) print(pulp.LpStatus[status]) res = [] for i in range(data.get('num_caches')): res.append([]) for j in range(data.get('num_videos')): res[i].append(pulp.value(x[i][j])) results = np.array(res) return results
def _get_solver(solver_name, timelimit): if solver_name == "cplex": return pulp.CPLEX_PY(msg=0, timeLimit=timelimit) elif solver_name == "gurobi": return pulp.GUROBI(msg=0, timeLimit=timelimit) elif solver_name == "glpk": return pulp.GLPK(msg=0, options=["--tmlim", str(timelimit)]) elif solver_name == "cbc": return pulp.COIN(msg=0, maxSeconds=timelimit) elif solver_name == "scip": return pulp.SCIP(msg=0, options=["-c", f"set limits time {timelimit}"]) raise ValueError("Invalid Solver Name")
def check_validity(buckets): prob = pulp.LpProblem('Nodal_feasibility', pulp.LpMinimize) vars = [] for bucket in buckets.keys(): if buckets[bucket][1] == 'node': vars.append( pulp.LpVariable('power_' + bucket, lowBound=buckets[bucket][2], upBound=buckets[bucket][3])) prob += pulp.lpSum(vars) prob += pulp.lpSum(vars) == 0 status = prob.solve(pulp.GLPK()) # We now know if the system is feasible, but we need to return that value. return pulp.LpStatus[status]
def test_backup(self): merged_dict = covering.merge_coverages( [self.binary_coverage_point, self.binary_coverage_point2]) merged_dict = covering.update_serviceable_demand( merged_dict, self.serviceable_demand_point) bclp = covering.create_backup_model(merged_dict, {"total": 30}, "backup.lp") bclp.solve(pulp.GLPK()) ids = utilities.get_ids(bclp, "facility_service_areas") ids2 = utilities.get_ids(bclp, "facility2_service_areas") self.assertEqual(['1', '3', '4', '5', '6', '7'], ids) self.assertEqual([ '0', '1', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '2', '20', '22', '3', '4', '5', '6', '8', '9' ], ids2)
def __call__(self, distribution, proposal, subset): self.counter += 1 assignments, value = subset if all(i is not None for i in assignments): return distribution.negative_energy(assignments) else: prob, spin_vars, edge_vars = distribution.make_problem(subset) prob.solve(pulp.GLPK(msg=0)) for i in range(len(value)): if isinstance(spin_vars[i], int): value[i] = spin_vars[i] else: value[i] = spin_vars[i].varValue return -pulp.value(prob.objective)
def _solve(self, timeout=None): start_time = time.time() # CPLEX will tell us that the problem in infeasible for large datasets # self._rez = self._model.solve(pulp.CPLEX()) # import pdb; pdb.set_trace() options = ['--binarize'] if timeout: options.extend(["--tmlim", str(timeout)]) solver = pulp.GLPK(options=options) self._rez = self._model.solve(solver) delta_time = time.time() - start_time self._delta_time = delta_time return self._rez, self._delta_time
def solve_ilp(objective, constraints): print("objective", objective) print("constraaints", constraints) prob = pulp.LpProblem('LP1', pulp.LpMinimize) prob += objective for cons in constraints: prob += cons print("prob", prob) status = prob.solve(pulp.GLPK(options=['--mipgap', '0.000001', '--cgr'])) # status = prob.solve(pulp.COIN_CMD(fracGap = 0)); # status = prob.solve(pulp.PULP_CBC_CMD()); # default if status != 1: # print('status', status) # LpStatus = {-3: 'Undefined', -2: 'Unbounded', -1: 'Infeasible', 0: 'No... return None else: return [v.varValue.real for v in prob.variables()]
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 optimLogic(excessNachwa, capacityNW, NW_LowLevel, NW_HigherLevel, MalwathuOya, SpecialCanal): prob = pulp.LpProblem("test1", pulp.LpMaximize) #logging.critical("came here !!!!!!!!") # variables x1 = pulp.LpVariable("x1", 0) x2 = pulp.LpVariable("x2", 0) x3 = pulp.LpVariable("x3", 0) x4 = pulp.LpVariable("x4", 0) # objective prob += x1 + x2 + x3 + x4 # Constraints prob += x1 <= MalwathuOya prob += x2 <= SpecialCanal prob += x3 <= NW_HigherLevel prob += x4 <= NW_LowLevel prob += x3 + x4 == capacityNW prob += x1 + x2 + x3 + x4 == excessNachwa # prob += x3 + x4 == 10000 # prob += x1 + x2 + x3 + x4 == 20000 pulp.GLPK().solve(prob) i = 0 valueList = [] # solution for v in prob.variables(): print v.name, "=", v.varValue valueList.insert(i, v.varValue) i = i + 1 print "objective=", pulp.value(prob.objective) objtve = pulp.value(prob.objective) if (objtve != 0): result.viewOutput(valueList[0], valueList[1], valueList[2], valueList[3], objtve) else: tkMessageBox.showinfo("Warning", "Sorry !!! There is no optimum solution")