def configure_solver_user_guide(): print("Solver list: {}.".format(pulp.listSolvers())) print("Solver list (available): {}.".format(pulp.listSolvers(onlyAvailable=True))) solver = pulp.getSolver("CPLEX_CMD") solver = pulp.getSolver("CPLEX_CMD", timeLimit=10) path_to_cplex = r"C:\Program Files\IBM\ILOG\CPLEX_Studio128\cplex\bin\x64_win64\cplex.exe" solver = pulp.CPLEX_CMD(path=path_to_cplex)
def _get_solver(self, **kwargs): if SOLVER not in listSolvers(): raise Exception(f"{SOLVER} is not supported by PuLP." + f" Select one of the following:\n {listSolvers()}") if SOLVER in listSolvers(onlyAvailable=True): return getSolver(SOLVER, **kwargs) if SOLVER in SOLVER_PATHS: return getSolver(SOLVER, path=SOLVER_PATHS[SOLVER]) raise Exception( f"{SOLVER} is not available. " + "Please install and enter correct path in config or use other solver.\n" + f"Available solvers are: {listSolvers(onlyAvailable=True)}")
def _check_pulp_solver(solver: str) -> str: """ Depending on how `pulp` is installed, different solver are available. If installed via conda-forge, `COIN_CMD` is available; and if installed via PyPI, `PULP_CBC_CMD` and `PULP_CHOCO_CMD` are available. In fact, `PULP_CBC_CMD` is just a precompiled version of the COIN/CBC method, and it should behave the same as `COIN_CMD`. In this function, we select `PULP_CBC_CMD` if `COIN_CMD` is unavailable. In such, we get the same behavior regardless whether `pulp` is installed via conda-forge or from PyPI. Returns: Either `COIN_CMD` or `PULP_CBC_CMD`. """ solver = solver.upper() avail_solver = pulp.listSolvers(onlyAvailable=True) # switch to the other if requested solver is unavailable if solver not in avail_solver: if solver == "COIN_CMD": solver = "PULP_CBC_CMD" elif solver == "PULP_CBC_CMD": solver = "COIN_CMD" if solver not in avail_solver: raise ReactionMappingError( f"Cannot proceed to do atom mapping, because the default `pulp` solvers " f"`COIN_CMD` or `PULP_CBC_CMD` are unavailable on your machine. Your current " f"`pulp`installation supports {avail_solver}. Try one of these by passing " "`solver=<AVAILABLE_SOLVER>` to the function." "For more information of `pulp` solver, see: " "https://coin-or.github.io/pulp/guides/how_to_configure_solvers.html" ) return solver
def test_get_schema(self): response = self.client.get_schema("solve_model_dag") schema = { "config": get_pulp_jsonschema("solver_config.json"), "instance": get_pulp_jsonschema(), "solution": get_pulp_jsonschema(), } schema["config"]["properties"]["solver"]["enum"] = pl.listSolvers() schema["config"]["properties"]["solver"]["default"] = "PULP_CBC_CMD" for (key, value) in schema.items(): self.assertDictEqual(value, response[key])
def lrs_ilp(s, verbosity=0): if len(s) == 1: return Solution(1, [[s[0]]]) try: try: from pulp import ( LpVariable, LpProblem, LpMaximize, LpInteger, PulpSolverError, ) model = LpProblem("LRS", LpMaximize) # create variables x = [ LpVariable("x_{}".format(i), 0, 1, LpInteger) for i in range(len(s)) ] # node degree for j in range(len(s)): for i in range(j): if s[i].char == s[j].char: model += (j - i) * x[i] + sum([ x[l] if s[l].char != s[i].char else 0 for l in range(i + 1, j) ]) + (j - i) * x[j] <= 2 * (j - i) # objective model += sum([x[i] * s[i].length for i in range(len(s))]) # depending on pulp version, solvers have to be created differently try: from pulp import getSolver, listSolvers solvers = [getSolver(s, msg=0) for s in listSolvers()] except: from pulp import COIN_CMD, PULP_CBC_CMD, PulpSolverError solvers = [COIN_CMD(msg=0), PULP_CBC_CMD(msg=0)] solved = False for solver in solvers: if solved: break try: model.solve(solver) solved = True except PulpSolverError: pass if not solved: raise ImportError sol = [s[i] for i in range(len(s)) if x[i].varValue > 0.999] return Solution(sum([run.length for run in sol]), [sol]) except (ModuleNotFoundError, ImportError) as e: if verbosity == 1: print( "PuLP itself or some of its properties could not be loaded. Solving model with DP instead." ) elif verbosity >= 2: print("Error loading PuLP solver:") print(e) print("Solving model with DP instead.") return lrs_dp(s) except: if verbosity >= 1: print( "Unexpected error occured while loading PuLP. Solving model with DP instead." ) return lrs_dp(s)
注意clpex临时生成的lp文件,默认放在用户临时目录中,可以使用solver = pl.CPLEX_CMD(keepFiles=True),存放临时文件到 本文件同一级目录中,可以solver.tmpdir指定目录。 """ import pulp as pl def getCplexSolver(): """ 获取IBM的CPlex :return: """ solver = pl.CPLEX_CMD(keepFiles=True) return solver if __name__ == '__main__': solver_list = pl.listSolvers() available_solver_list = pl.listSolvers(onlyAvailable=True) print(solver_list) print(available_solver_list) # solver = pl.CPLEX_PY() # solver = pl.CPLEX_CMD(keepFiles=True,options = ['epgap = 0.25']) # print(solver) # path_to_cplex = r'D:\IBM\ILOG\CPLEX_Studio_Community1210\cplex\bin\x64_win64\cplex.exe' # solver = pl.CPLEX_CMD(path=path_to_cplex) # model = pl.LpProblem("Example", pl.LpMinimize) # _var = pl.LpVariable('a') # _var2 = pl.LpVariable('a2') # model += _var + _var2 == 1 # result = model.solve(solver) # print(result)
Pour de nombreuses personnes, la réponse est simple, voire insignifiante. Un siège coûte 12,50 $ pour les autobus de 40 sièges et 13,33 $ pour les autobus de 30 sièges. On devrait donc préférer les bus 40 places aux bus 30 places. Nous dépensons donc d'abord 3500 $ (7 * 500 $) pour 7 autobus et 280 enfants, puis nous ajoutons un huitième autobus pour 400 $ (30 sièges) pour les 20 enfants restants. Le coût total est de 3900 $. Cela a l'air bien. Mais ce n'est pas la meilleure solution. Avec 6 bus 40 places (240 enfants et 3000 $) et 2 bus 30 places (60 enfants, 800 $), nous pouvons déplacer les enfants et ne payer que 3800 $). Nous pouvons économiser 100 $! """ import pulp solver_list = pulp.listSolvers(onlyAvailable=True) print(solver_list) # import cplex bus_problem = pulp.LpProblem("bus", pulp.LpMinimize) nbBus40 = pulp.LpVariable('nbBus40', lowBound=0, cat='Integer') nbBus30 = pulp.LpVariable('nbBus30', lowBound=0, cat='Integer') # Objective function bus_problem += 500 * nbBus40 + 400 * nbBus30, "cost" # Constraints bus_problem += 40 * nbBus40 + 30 * nbBus30 >= 300
lag_total = libpysal.weights.lag_spatial(w, np.ones(data[sel_var].shape)) lag_sel = libpysal.weights.lag_spatial(w, data[sel_var]) lag_nonsel = lag_total - lag_sel # Now calculating edge counts g11 = (lag_sel*data[sel_var]).sum() g12 = (lag_nonsel*data[sel_var]).sum() g1 = g11/(g11+g12) #No correction for minimum edge p1 = data[sel_var].sum()/data.shape[0] # Now calculating CI if (g1 < p1) & (p1 < 0.5): ci = (g1 - p1)/g1 else: ci = (g1 - p1)/(1 - p1) return ci print( pulp.listSolvers(onlyAvailable=True) ) # Much better success with CPLEX than with default coin for more # Weight to the edges part solver = pulp.getSolver('CPLEX_CMD', timeLimit=10) def lp_clumpy(data, w, sel_n, crime_var, theta): gi = list(data.index) crime = data[crime_var] theta_obs = 1.0 - theta P = pulp.LpProblem("Choosing_Cases_to_Audit", pulp.LpMaximize) S = pulp.LpVariable.dicts("Selecting_Grid_Cell", [i for i in gi], lowBound=0, upBound=1, cat=pulp.LpInteger) E = pulp.LpVariable.dicts("Edge_Weights", [i for i in gi], lowBound=0, cat=pulp.LpContinuous) #Objective Function P += pulp.lpSum( theta*crime[i]*S[i] + theta_obs*E[i] for i in gi) # Constraint 1, total areas selected P += pulp.lpSum( S[i] for i in gi ) == sel_n
def __init__(self, Ar, Di, Co, Ca, Ta, In, Th): # Assigning initial properties of object self.Ar = Ar self.Di = Di self.Co = Co self.Ca = Ca self.Ta = Ta self.In = In self.Th = Th self.subtours = [] #empty subtours to start self.objective = -1 #objective values self.pairs = None #where to stuff the matched areas # Creating inequality metrics SumCalls = sum(Ca.values()) MaxIneq = (SumCalls / Ta) * (1 + In) MinIneq = (SumCalls / Ta) * (1 - In) self.ineq = [MaxIneq, MinIneq] # Creating contiguity graph G = networkx.Graph() for i in Ar: for j in Co[i]: G.add_edge(i, j) self.co_graph = G # Creating threshold vectors for decision variables NearAreas = {} Thresh = [] for s in Ar: NearAreas[s] = [] for d in Ar: if Di[s][d] < Th: Thresh.append((s, d)) NearAreas[s].append(d) self.NearAreas = NearAreas self.Thresh = Thresh # Setting up the pulp problem P = pulp.LpProblem("P-Median", pulp.LpMinimize) # Decision variables assign_areas = pulp.LpVariable.dicts("SD", [(s, d) for (s, d) in Thresh], lowBound=0, upBound=1, cat=pulp.LpInteger) # Just setting the y_vars as the diagonal sources/destinations y_vars = {s: assign_areas[(s, s)] for s in Ar} tot_constraints = 0 self.assign_areas = assign_areas self.y_vars = y_vars # Function to minimize P += pulp.lpSum(Ca[d] * Di[s][d] * assign_areas[(s, d)] for (s, d) in Thresh) # Constraint on max number of areas P += pulp.lpSum(y_vars[s] for s in Ar) == Ta tot_constraints += 1 # Constraint nooffbeat if local is not assigned (1) # Second is contiguity constraint for s, d in Thresh: P += assign_areas[(s, d)] - y_vars[s] <= 0 tot_constraints += 1 if s != d: # Identifying locations contiguous in nearest path both = set(networkx.shortest_path(G, s, d)) & set(Co[d]) # Or if nearer to the source nearer = [a for a in Co[d] if Di[s][a] < Di[s][d]] # Combining, should alwayss have at least 1 comb = list(both | set(nearer)) # Contiguity constraint P += pulp.lpSum(assign_areas[(s, a)] for a in comb if a in NearAreas[s]) >= assign_areas[(s, d)] tot_constraints += 1 # Constraint every destination covered once # Then Min/Max inequality constraints for (sl, dl) in zip(Ar, Ar): P += pulp.lpSum(assign_areas[(s, dl)] for s in NearAreas[dl]) == 1 P += pulp.lpSum(assign_areas[(sl, d)] * Ca[d] for d in NearAreas[sl]) <= MaxIneq P += pulp.lpSum(assign_areas[(sl, d)] * Ca[d] for d in NearAreas[sl]) >= MinIneq * y_vars[sl] tot_constraints += 3 self.model = P print(f'Total number of decision variables {len(Thresh)}') print(f'Total number of constraints {tot_constraints}') av_solv = pulp.listSolvers(onlyAvailable=True) print(f'Available solvers from pulp, {av_solv}')
ExperimentCore, get_pulp_jsonschema, ) from cornflow_client.constants import ( SOLUTION_STATUS_FEASIBLE, SOLUTION_STATUS_INFEASIBLE, ) import cornflow_client.airflow.dag_utilities as utils import pulp as pl import orloge as ol import os config = get_pulp_jsonschema("solver_config.json") config["properties"]["solver"]["enum"] = pl.listSolvers() config["properties"]["solver"]["default"] = "PULP_CBC_CMD" class Instance(InstanceCore): schema = get_pulp_jsonschema() class Solution(SolutionCore): schema = get_pulp_jsonschema() class PuLPSolve(ExperimentCore): def solve(self, options: dict): options = dict(options) options["msg"] = 0