def solveSchedulingSubproblem(numJobs, totalTime, availResources, jobLength): ''' Input data numJobs: Number of jobs (int) totalTime: Total time blocks (int) availResources: Total amount of resource available for this machine. Assume each job uses one resource. (int) jobLength: The length (in time blocks) of each job (list, by job number) ''' # Create a CPO model model = CpoModel() # Create variables TIME = model.integer_var_list(numJobs, 0, totalTime - 1, "TIME") # For each job, indicate start time RESOURCE = model.integer_var_list( numJobs, 0, availResources - 1, "RESOURCE") # For each job, indicate resource used # Add general constraints for i in range(numJobs): # Jobs must end before the end of the totalTime available model.add(TIME[i] + jobLength[i] <= totalTime) # Jobs can't be scheduled on a machine at the same time for j in range(numJobs): if i != j: model.add((RESOURCE[i] != RESOURCE[j]) | (TIME[i] + jobLength[i] <= TIME[j]) | (TIME[j] + jobLength[j] <= TIME[i])) # If there's only one job, then above constraints will never reference RESOURCE variable. # In that case, RESOURCE won't show up in the problem, and won't get a value. # To prevent this, we add dummy constraints on RESOURCE as follows: if numJobs == 1: model.add(RESOURCE[0] >= 0) # Solve model print("Solving model....") msol = model.solve(TimeLimit=10) if msol: # If the model ran successfully, it returns True print("Solution:") for j in range(numJobs): print("Job " + str(j) + " starts at time " + str(msol[TIME[j]]) + " and uses resource " + str(msol[RESOURCE[j]])) print("Last job time ends at " + str(max(msol[TIME[j]] + jobLength[j] for j in range(numJobs)))) return True else: # Problem is infeasible; print the infeasibility # theConflictsResult = model.refine_conflict() # print(theConflictsResult) return False
def ALBP(TaskTime, nbStations, PrecedenceTasks): """ Prepare the data for modeling """ # tasks set TASKS = range(len(TaskTime)) # workstations set WORKSTATIONS = range(nbStations) """ Build the model """ # Create CPO model myModel = CpoModel() # Assign tasks to workstation WhichWorkstation = myModel.integer_var_list(len(TaskTime), 0, nbStations - 1) # Cycle time CycleTime = myModel.integer_var(max(TaskTime), sum(TaskTime)) # Add station load constraints for k in WORKSTATIONS: myModel.add(sum(TaskTime[i] * (WhichWorkstation[i] == k) for i in TASKS) <= CycleTime) # Add precedence constraints for i in TASKS: for j in PrecedenceTasks[i]: myModel.add(WhichWorkstation[j] <= WhichWorkstation[i]) # Create model objective myModel.add(myModel.minimize(CycleTime)) """ Solve model """ solution = myModel.solve(FailLimit=100000, TimeLimit=10) """ Print solution """ return solution
def solve(self): mdl = CpoModel() power = [2**i for i in range(0, self.U + 1)] M = mdl.integer_var_list(self.n + 1, 0, self.U, "M") T = mdl.integer_var_list(self.n + 1, 0, power[self.U], "T") mdl.add(mdl.element(power, M[i]) == T[i] for i in range(0, self.n + 1)) mdl.add(T[i] >= T[0] for i in range(0, self.n + 1)) mdl.minimize( mdl.sum(self.H[i] * T[i] / self.beta + self.K[i] / (T[i] / self.beta) for i in range(0, self.n + 1))) # Solve model print("Solving model....") msol = mdl.solve( TimeLimit=10, agent='local', execfile= '/Applications/CPLEX_Studio1210/cpoptimizer/bin/x86-64_osx/cpoptimizer' ) # Print solution if msol: stdout.write("Total cost : " + str(msol.get_objective_values()[0]) + "\n") stdout.write("T: [") for t in T: stdout.write(" {}".format(msol[t])) stdout.write("]\n") stdout.write("M: [") for m in M: stdout.write(" {}".format(msol[m])) stdout.write("]\n") return msol.get_objective_values()[0] else: stdout.write("Solve status: {}\n".format(msol.get_solve_status())) return None
#----------------------------------------------------------------------------- # Prepare the data for modeling #----------------------------------------------------------------------------- # Estimate an upper bound to the ruler length MAX_LENGTH = (ORDER - 1)**2 #----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- # Create model mdl = CpoModel() # Create array of variables corresponding to position rule marks marks = mdl.integer_var_list(ORDER, 0, MAX_LENGTH, "M") # Create marks distances that should be all different dist = [marks[i] - marks[j] for i in range(1, ORDER) for j in range(0, i)] mdl.add(mdl.all_diff(dist)) # Avoid symmetric solutions by ordering marks mdl.add(marks[0] == 0) for i in range(1, ORDER): mdl.add(marks[i] > marks[i - 1]) # Avoid mirror solution mdl.add((marks[1] - marks[0]) < (marks[ORDER - 1] - marks[ORDER - 2])) # Minimize ruler size (position of the last mark) mdl.add(mdl.minimize(marks[ORDER - 1]))
""" from docplex.cp.model import CpoModel from sys import stdout # Set model parameters NB_QUEEN = 8 # Number of queens # Create a CPO model model = CpoModel() # Create column index of each queen # Arguments: size, domain_min, domain_max, name # That is, create NB_QUEEN integer variables that take on a value between 0 and NB_QUEEN # The value indicates the row of that ith column with a queen x = model.integer_var_list(NB_QUEEN, 0, NB_QUEEN - 1, "X") # One queen per row model.add(model.all_diff(x)) # Queens cannot be the same number of columns apart as they are rows apart for i in range(NB_QUEEN): for j in range(NB_QUEEN): if i != j: model.add(model.abs(i - j) != model.abs(x[i] - x[j])) # Solve model print("Solving model....") msol = model.solve(TimeLimit=10) # Print solution
from docplex.cp.model import CpoModel mdl = CpoModel(name='buses') nbbus40 = mdl.integer_var(0,1000,name='nbBus40') nbbus30 = mdl.integer_var(0,1000,name='nbBus30') Bus40=[40] nbbus40array=mdl.integer_var_list(1,0,1000,name="nbBus40") mdl.add(nbbus40array[0]==nbbus40) mdl.set_search_phases([mdl.search_phase(nbbus40array)]) mdl.add(nbbus40*40 + nbbus30*30 >= 300) mdl.minimize(nbbus40*500 + nbbus30*400) msol=mdl.solve() print(msol[nbbus40]," buses 40 seats") print(msol[nbbus30]," buses 30 seats") """ which gives 6 buses 40 seats 2 buses 30 seats
#----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- # Create CPO model mdl = CpoModel() # Create one variable per store to contain the index of its supplying warehouse NB_WAREHOUSES = len(WAREHOUSES) supplier = mdl.integer_var_list(NB_STORES, 0, NB_WAREHOUSES - 1, "supplier") # Create one variable per warehouse to indicate if it is open (1) or not (0) open = mdl.integer_var_list(NB_WAREHOUSES, 0, 1, "open") # Add constraints stating that the supplying warehouse of each store must be open for s in supplier: mdl.add(mdl.element(open, s) == 1) # Add constraints stating that the number of stores supplied by each warehouse must not exceed its capacity for wx in range(NB_WAREHOUSES):
# Minimum loss incurred for a given slab usage. # loss[v] = loss when smallest slab is used to produce a total weight of v loss = [0] + [ min([sw - use for sw in AVAILABLE_SLAB_WEIGHTS if sw >= use]) for use in range(1, max_slab_weight + 1) ] #----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- # Create model mdl = CpoModel() # Index of the slab used to produce each coil order production_slab = mdl.integer_var_list(len(ORDERS), 0, MAX_SLABS - 1, "production_slab") # Usage of each slab slab_use = mdl.integer_var_list(MAX_SLABS, 0, max_slab_weight, "slab_use") # The orders are allocated to the slabs with capacity mdl.add(mdl.pack(slab_use, production_slab, [o.weight for o in ORDERS])) # Constrain max number of colors produced by each slab for s in range(MAX_SLABS): su = 0 for c in allcolors: lo = False for i, o in enumerate(ORDERS): if o.color == c: lo |= (production_slab[i] == s)
dirt_amount_dict = dataPrep.dirt_amount_dict index_arc_dict = dataPrep.index_arc_dict num_arcs = dataPrep.num_arcs # ----------------------------------------------------------------------------- # Build the model and variables # ----------------------------------------------------------------------------- # Create CPO model mdl = CpoModel() decision_Arcs = mdl.binary_var_list(dataPrep.num_arcs, name='arc') # nested integer_cplex_list for dis+, dis-, decision_dirt_plus = mdl.integer_var_list(len(dataPrep.valid_nodes) * numScenarios, min=0, name='dplus') decision_dirt_minus = mdl.integer_var_list(len(dataPrep.valid_nodes) * numScenarios, min=0, max=1000, name='dminus') # ----------------------------------------------------------------------------- # Build the constraints # ----------------------------------------------------------------------------- # constraint 2, 3 for source in source_sink_arc_dict: arc_sum_expression = 0 for sink in source_sink_arc_dict[source]: arc_sum_expression += decision_Arcs[source_sink_arc_dict[source][sink]]
nbCustomers = 1 + max(co[0] for co in CUSTOMER_ORDERS) volumes = [co[1] for co in CUSTOMER_ORDERS] productType = [co[2] for co in CUSTOMER_ORDERS] # Max number of truck deliveries (estimated upper bound, to be increased if no solution) maxDeliveries = 15 #----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- # Create CPO model mdl = CpoModel() # Configuration of the truck for each delivery truckConfigs = mdl.integer_var_list(maxDeliveries, 0, nbTruckConfigs - 1, "truckConfigs") # In which delivery is an order where = mdl.integer_var_list(nbOrders, 0, maxDeliveries - 1, "where") # Load of a truck load = mdl.integer_var_list(maxDeliveries, 0, maxLoad, "load") # Number of deliveries that are required nbDeliveries = mdl.integer_var(0, maxDeliveries) # Identification of which customer is assigned to a delivery customerOfDelivery = mdl.integer_var_list(maxDeliveries, 0, nbCustomers, "customerOfTruck") # Transition cost for each delivery transitionCost = mdl.integer_var_list(maxDeliveries - 1, 0, 1000, "transitionCost") # transitionCost[i] = transition cost between configurations i and i+1 for i in range(1, maxDeliveries):
def CP_model_restricted(params): ## NUM_COLORS, NUM_ITEMS, BIN_SIZE, DISCREPANCY, ITEM_SIZES, COLORS, NUM_BINS, Timelimit, SEED = params mdl = CpoModel() X = [mdl.integer_var(min=0, max=NUM_BINS) for item in range(NUM_ITEMS)] CP = mdl.integer_var_list(NUM_BINS, min=0, max=BIN_SIZE) for bin in range(NUM_BINS - 1): mdl.add(CP[bin] >= CP[bin + 1]) mdl.add(pack(CP, [X[item] for item in range(NUM_ITEMS)], ITEM_SIZES)) CC = [ mdl.integer_var_list(NUM_COLORS, min=0, max=BIN_SIZE) for bin in range(NUM_BINS) ] for color in range(NUM_COLORS): mdl.add( distribute([CC[bin][color] for bin in range(NUM_BINS)], [ X[item] for item in range(NUM_ITEMS) if COLORS[item] == color ], [bin for bin in range(NUM_BINS)])) for bin in range(NUM_BINS): TC = mdl.sum(CC[bin]) MC = mdl.max(CC[bin]) # mdl.add_kpi(TC, name="TC_{}".format(bin)) # mdl.add_kpi(MC, name="MC_{}".format(bin)) # mdl.add( # (TC+mdl.mod(TC, 2))/2 >= MC # # ) # mdl.add( # (TC - mdl.mod(TC, NUM_COLORS))/NUM_COLORS >= MC # ) # mdl.add( # mdl.sum( # CC[bin][color] > 0 for color in range(NUM_COLORS) # ) <= MAX_COLORS_IN_BIN # ) for item in range(NUM_ITEMS): for item2 in range(item + 1, NUM_ITEMS): if COLORS[item] == COLORS[item2]: mdl.add( mdl.if_then( X[item] == X[item2], mdl.any([ X[i] == X[item] for i in range(item + 1, item2 + 1) if COLORS[i] != COLORS[item] ]) # mdl.count([mdl.element(COLORS, i) for i in range(item, item2+1)], abs(COLORS[item] -1)) > 0 )) # mdl.add( # mdl.minimize(count_different(X)) # ) # bins_used = mdl.sum(CP[bin] > 0 for bin in range(NUM_BINS)) # mdl.add( # mdl.minimize( # bins_used # ) # ) mdl.add(mdl.minimize(mdl.max(X) + 1)) try: msol = mdl.solve(TimeLimit=20) mdl._myInstance = (NUM_COLORS, NUM_ITEMS, BIN_SIZE, DISCREPANCY, SEED) # # print(ITEM_SIZES) # print(COLORS) # # print([msol[X[item]] for item in range(NUM_ITEMS)]) Xs = np.array([msol[X[i]] for i in range(NUM_ITEMS)]) if solution_checker(Xs, COLORS, ITEM_SIZES, BIN_SIZE, SEED, 'restricted_cp_binary'): write_to_global_cp(msol, mdl, 'restricted_binary') except Exception as err: print(err) write_to_global_failed(NUM_COLORS, NUM_ITEMS, BIN_SIZE, DISCREPANCY, SEED, 'restricted_cp_binary', is_bad_solution=False)
# Letters used to print the different pegs PEG_LETTERS = ('.', 'R', 'B') #----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- # Create model mdl = CpoModel() # Create sequence of states. Each variable has 3 possible values: 0: Hole, 1: red peg, 2: blue peg states = [] for s in range(NB_MOVES + 1): states.append(mdl.integer_var_list(SIZE, HOLE, BLUE, "State_" + str(s) + "_")) # Create variables representing from index and to index for each move fromIndex = mdl.integer_var_list(NB_MOVES, 0, SIZE - 1, "From_") toIndex = mdl.integer_var_list(NB_MOVES, 0, SIZE - 1, "To_") # Add constraints between each state for m in range(NB_MOVES): fvar = fromIndex[m] tvar = toIndex[m] fromState = states[m] toState = states[m + 1] # Constrain location of holes mdl.add(mdl.element(fromState, tvar) == HOLE) # Constrain move size and direction delta = tvar - fvar
See: http://www.slate.fr/story/101809/puzzle-maths-vietnam for more information. Please refer to documentation for appropriate setup of solving configuration. """ from docplex.cp.model import CpoModel #----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- # Create model mdl = CpoModel() # Create model variables V = mdl.integer_var_list(size=9, min=1, max=9, name="V") mdl.add(mdl.all_diff(V)) # Create constraint mdl.add(V[0] + 13 * V[1] / V[2] + V[3] + 12 * V[4] - V[5] - 11 + V[6] * V[7] / V[8] - 10 == 66) #----------------------------------------------------------------------------- # Solve the model and display the result #----------------------------------------------------------------------------- # Solve model print("Solving model....") msol = mdl.solve(TimeLimit=10) print("Solution: ")
nbKids = 300 nbSizes = len(Buses) # Indexes busSize = 0 busCost = 1 for b in Buses: print("buses with ", b[busSize], " seats cost ", b[busCost]) mdl = CpoModel(name='buses') #decision variables mdl.nbBus = mdl.integer_var_list(nbSizes, 0, 1000, name="nbBus") # Constraint mdl.add( sum(mdl.nbBus[b] * Buses[b][busSize] for b in range(0, nbSizes)) >= nbKids) # Objective mdl.minimize(sum(mdl.nbBus[b] * Buses[b][busCost] for b in range(0, nbSizes))) msol = mdl.solve() # Dislay solution for b in range(0, nbSizes): print(msol[mdl.nbBus[b]], " buses with ", Buses[b][busSize], " seats")
from docplex.cp.model import CpoModel from docplex.cp.solution import CpoRefineConflictResult from sys import stdout # Input data numJobs = 10 # Number of jobs totalTime = 15 # Total time blocks availResources = 2 # Total amount of resource available for this machine. Assume each job uses one resource jobLength = [1, 2, 3, 4, 5, 1, 1, 2, 2, 2] # The length (in time blocks) of each job # Create a CPO model model = CpoModel() # Create variables TIME = model.integer_var_list(numJobs, 0, totalTime - 1, "TIME") # For each job, indicate start time RESOURCE = model.integer_var_list( numJobs, 0, availResources - 1, "RESOURCE") # For each job, indicate resource used # Add general constraints for i in range(numJobs): # Jobs must end before the end of the totalTime available model.add(TIME[i] + jobLength[i] <= totalTime) # Jobs can't be scheduled on a machine at the same time for j in range(numJobs): if i != j: model.add((RESOURCE[i] != RESOURCE[j]) | (TIME[i] + jobLength[i] <= TIME[j]) | (TIME[j] + jobLength[j] <= TIME[i]))
demand = list([data.popleft() for c in range(nbCustomer)]) # Initialize fixed cost of each location fixedCost = list([data.popleft() for p in range(nbLocation)]) # Initialize capacity of each location capacity = list([data.popleft() for p in range(nbLocation)]) #----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- mdl = CpoModel() # Create variables identifying which location serves each customer cust = mdl.integer_var_list(nbCustomer, 0, nbLocation - 1, "CustomerLocation") # Create variables indicating which plant location is open open = mdl.integer_var_list(nbLocation, 0, 1, "OpenLocation") # Create variables indicating load of each plant load = [ mdl.integer_var(0, capacity[p], "PlantLoad_" + str(p)) for p in range(nbLocation) ] # Associate plant openness to its load for p in range(nbLocation): mdl.add(open[p] == (load[p] > 0)) # Add constraints
def solve_seer_ilp(companies, facilities, customers, facilityDemands, costs, alpha=1, log_verbose='Quiet'): assert alpha >= 0 # ensure trace-off factor is >= 0, which show the contribution of representative cost assert log_verbose in ['Quiet', 'Terse', 'Normal', 'Verbose'] n_company = len(companies) n_facility = len(facilities) n_customer = len(customers) n_type = len(facilityDemands) mdl = CpoModel() customerSupplier = mdl.integer_var_list(n_customer, 0, n_facility - 1, 'customerSupplier') openFacility = mdl.integer_var_list(n_facility, 0, 1, 'openFacility') facilityType = mdl.integer_var_list(n_facility, 0, n_type, 'facilityType') customerType = mdl.integer_var_list(n_customer, 0, n_type - 1, 'customerType') openCompany = mdl.integer_var_list(n_company, 0, 1, 'openCompany') company2id = {companies[i].name: i for i in range(n_company)} type2id = {facilityDemands[i].type: i for i in range(n_type)} facilityCompany = [ company2id[facilities[i].company] for i in range(n_facility) ] validFacilityType = np.zeros((n_facility, n_type + 1)) validFacilityType[:, n_type] = 1 for i in range(n_facility): validFacilityType[i, type2id[facilities[i].type]] = 1 for i in range(n_customer): mdl.add(mdl.element(openFacility, customerSupplier[i]) == 1) mdl.add( mdl.element(customerType, i) == mdl.element( facilityType, customerSupplier[i])) mdl.add( mdl.element(mdl.element(customerType, i), validFacilityType[i]) == 1) for i in range(n_facility): mdl.add( mdl.element(mdl.element(facilityType, i), validFacilityType[i]) == 1) mdl.add( mdl.element(openFacility, i) <= mdl.element( openCompany, facilityCompany[i])) mdl.add((mdl.element(openFacility, i) == 1) == ( mdl.element(facilityType, i) < n_type)) for i in range(n_type): mdl.add(mdl.count(facilityType, i) == facilityDemands[i].demand) # Objective total_cost = mdl.scal_prod(openCompany, [c.cost for c in companies]) for i in range(n_customer): total_cost += mdl.element(customerSupplier[i], alpha * costs[i]) mdl.add(mdl.minimize(total_cost)) # ----------------------------------------------------------------------------- # Solve the model and display the result # ----------------------------------------------------------------------------- # Solve model msol = mdl.solve(TimeLimit=TIME_LIMIT, LogVerbosity=log_verbose) selectedFacilities = [] selectedCompanies = [] if msol: for i in range(n_facility): if msol[facilityType[i]] < n_type: selectedFacilities.append(i) if facilityCompany[i] not in selectedCompanies: selectedCompanies.append(facilityCompany[i]) return msol, selectedFacilities, selectedCompanies
# Define given data. fixed = 30 nbStores = 10 nbWarehouses = 5 capacity = [1, 4, 2, 1, 3] supplyCost = [[20, 24, 11, 25, 30], [28, 27, 82, 83, 74], [74, 97, 71, 96, 70], [2, 55, 73, 69, 61], [46, 96, 59, 83, 4], [42, 22, 29, 67, 59], [1, 5, 73, 59, 56], [10, 73, 13, 43, 96], [93, 35, 63, 85, 46], [47, 65, 55, 71, 95]] # Define model. wl = CpoModel() # Define decision variables. openwarehouse = wl.integer_var_list(nbWarehouses, 0, 1, "openwarehouse") warehouseservesstore = wl.integer_var_list(nbStores, 0, nbWarehouses - 1, "warehouseservesstore") # Define constraints. for s in warehouseservesstore: wl.add(wl.element(openwarehouse, s) == 1) for w in range(nbWarehouses): wl.add(wl.count(warehouseservesstore, w) <= capacity[w]) # Define objective. fixedArray = [] for i in range(nbWarehouses): fixedArray.append(fixed) total_cost = wl.scal_prod(openwarehouse, fixedArray)