Skip to content

Instantly share code, notes, and snippets.

@270ajay
Last active November 12, 2020 12:12
Show Gist options
  • Save 270ajay/1654baa1b2e03a98baa142363249235d to your computer and use it in GitHub Desktop.
Save 270ajay/1654baa1b2e03a98baa142363249235d to your computer and use it in GitHub Desktop.
basic constraint programming modeling
from ortools.sat.python import cp_model
''' course: https://www.coursera.org/learn/basic-modeling#about '''
def maximizePowerOfArmyWithinBudget(costList, strengthList, lbUbTupleList, nameList, budget):
model = cp_model.CpModel()
numOfGroupsOfArmy = len(costList)
armyGroupVarList = []
for index, lbUbTuple in enumerate(lbUbTupleList):
armyGroupVarList.append(model.NewIntVar(lbUbTuple[0], lbUbTuple[1], nameList[index]))
varCoeffList = []
for index, armyGroupVar in enumerate(armyGroupVarList):
varCoeffList.append(armyGroupVar * costList[index])
model.AddLinearConstraint(sum(varCoeffList), 0, budget)
varCoeffList = []
for index, armyGroupVar in enumerate(armyGroupVarList):
varCoeffList.append(strengthList[index]* armyGroupVarList[index])
model.Maximize(sum(varCoeffList))
solver = cp_model.CpSolver()
status = solver.Solve(model)
if status == cp_model.INFEASIBLE:
print("Infeasible model")
if status == cp_model.OPTIMAL:
print('Maximum of objective function: %i' % solver.ObjectiveValue(), "\n")
for index in range(numOfGroupsOfArmy):
print(nameList[index], ":", solver.Value(armyGroupVarList[index]))
print("----------------------------")
#----------------------------------------------------------------------------------------------------------------------#
class VarArraySolutionPrinter(cp_model.CpSolverSolutionCallback):
"""Print intermediate solutions."""
def __init__(self, variables):
cp_model.CpSolverSolutionCallback.__init__(self)
self.__variables = variables
self.__solution_count = 0
def on_solution_callback(self):
self.__solution_count += 1
for v in self.__variables:
print('%s = %i' % (v, self.Value(v)), end=' ')
print()
def solution_count(self):
return self.__solution_count
def countSoldiers(lbUbTuple, divisorList, remainderList):
model = cp_model.CpModel()
numOfSoldiersInArmyVar = model.NewIntVar(lbUbTuple[0], lbUbTuple[1], name="numOfPeopleInArmyVar")
for index in range(len(remainderList)):
model.AddModuloEquality(remainderList[index], numOfSoldiersInArmyVar, divisorList[index])
solver = cp_model.CpSolver()
solutionPrinter = VarArraySolutionPrinter([numOfSoldiersInArmyVar])
status = solver.SearchForAllSolutions(model, solutionPrinter)
print('Status = %s' % solver.StatusName(status))
print('Number of solutions found: %i' % solutionPrinter.solution_count())
print("----------------------------")
#----------------------------------------------------------------------------------------------------------------------#
def colorAMap(locationList, adjancentLocList, colorList):
model = cp_model.CpModel()
numOfColors = len(colorList)
locationVarDict = {}
for location in locationList:
locationVarDict[location] = model.NewIntVar(0, numOfColors-1, name="location")
for locList in adjancentLocList:
model.Add(locationVarDict[locList[0]]!= locationVarDict[locList[1]])
solver = cp_model.CpSolver()
status = solver.Solve(model)
if status == cp_model.INFEASIBLE:
print("Infeasible model")
if status == cp_model.OPTIMAL:
for location in locationList:
print("Location:", location, "| Color:", colorList[solver.Value(locationVarDict[location])])
print("----------------------------")
#----------------------------------------------------------------------------------------------------------------------#
def maximizePowerOfWeaponsProduced(productList, profitList, capacityList, consumptionList):
bigM = int(100000)
model = cp_model.CpModel()
produceVarList = []
for product in productList:
produceVarList.append(model.NewIntVar(0, bigM, name=product))
for index, capacity in enumerate(capacityList):
varCoeffList = []
for index2, produceVar in enumerate(produceVarList):
varCoeffList.append(produceVar * consumptionList[index2][index])
model.AddLinearConstraint(sum(varCoeffList), 0, capacity)
varCoeffList = []
for index, profit in enumerate(profitList):
varCoeffList.append(profit * produceVarList[index])
model.Maximize(sum(varCoeffList))
solver = cp_model.CpSolver()
status = solver.Solve(model)
if status == cp_model.INFEASIBLE:
print("Infeasible model")
if status == cp_model.OPTIMAL:
print('Profit: %i' % solver.ObjectiveValue(), "\n")
for index, produceVar in enumerate(produceVarList):
print(productList[index], ":", solver.Value(produceVar))
print("----------------------------")
#----------------------------------------------------------------------------------------------------------------------#
def countingRods():
model = cp_model.CpModel()
rods = [0, 1, 2, 3, 4, 5, 2, 3, 4, 5]
maxNumOfRods = max(rods)
MIN_DIGIT = 1
MAX_DIGIT = 9
M1 = model.NewIntVar(MIN_DIGIT, MAX_DIGIT, "M1")
M2 = model.NewIntVar(MIN_DIGIT, MAX_DIGIT, "M2")
M3 = model.NewIntVar(MIN_DIGIT, MAX_DIGIT, "M3")
M4 = model.NewIntVar(MIN_DIGIT, MAX_DIGIT, "M4")
M5 = model.NewIntVar(MIN_DIGIT, MAX_DIGIT, "M5")
R1 = model.NewIntVar(0, maxNumOfRods, "R1")
R2 = model.NewIntVar(0, maxNumOfRods, "R2")
R3 = model.NewIntVar(0, maxNumOfRods, "R3")
R4 = model.NewIntVar(0, maxNumOfRods, "R4")
R5 = model.NewIntVar(0, maxNumOfRods, "R5")
model.AddElement(M1, rods, R1)
model.AddElement(M2, rods, R2)
model.AddElement(M3, rods, R3)
model.AddElement(M4, rods, R4)
model.AddElement(M5, rods, R5)
model.Add(R1 + R2 + R3 + R4 + R5 == 12)
model.Add(2303 + M1 * 10 + 980 + M2 * 1000 + M3 == 301 + M4 * 1000 + M5 * 10)
model.AddAllDifferent([M1, M2, M3, M4, M5])
solver = cp_model.CpSolver()
status = solver.Solve(model)
if status == cp_model.INFEASIBLE:
print("Infeasible model")
if status == cp_model.OPTIMAL:
print("M1", ":", solver.Value(M1))
print("M2", ":", solver.Value(M2))
print("M3", ":", solver.Value(M3))
print("M4", ":", solver.Value(M4))
print("M5", ":", solver.Value(M5))
print("======")
print("R1", ":", solver.Value(R1))
print("R2", ":", solver.Value(R2))
print("R3", ":", solver.Value(R3))
print("R4", ":", solver.Value(R4))
print("R5", ":", solver.Value(R5))
print("----------------------------")
#----------------------------------------------------------------------------------------------------------------------#
if __name__ == '__main__':
maximizePowerOfArmyWithinBudget(costList=[13, 21, 17, 100],
strengthList=[6, 10, 8, 40],
lbUbTupleList=[(0,1000), (0,400), (0,500), (0,150)],
nameList=["F", "L", "Z", "J"],
budget=10000)
countSoldiers(lbUbTuple=(100,800), divisorList=[5, 7, 12], remainderList=[2, 2, 1])
colorAMap(locationList=["Si", "Yan", "Yu", "Xu", "Qing", "Ji", "You", "Bing", "Yong", "Liang",
"Yi", "Jing", "Yang", "Jiao"],
adjancentLocList=[["Liang","Yong"], ["Yong","Yi"],["Yong","Jing"], ["Yong","Si"], ["Yi","Jing"], ["Yi","Jiao"],
["Jiao","Jing"], ["Jiao","Yang"], ["Jing","Yang"], ["Jing","Yong"], ["Jing","Si"], ["Jing","Yu"],
["Yang","Yu"], ["Yang","Xu"], ["Yu","Si"], ["Yu","Yan"], ["Yu","Xu"], ["Xu","Yan"], ["Xu","Qing"],
["Yan","Si"], ["Yan","Ji"], ["Yan","Ji"], ["Yan","Qing"], ["Qing","Ji"], ["Ji","You"], ["Ji","Bing"],
["Ji","Si"], ["You","Bing"], ["Bing","Si"]],
colorList=["GREEN", "BLUE", "PINK", "YELLOW"])
maximizePowerOfWeaponsProduced(productList=["AXE", "SWORD", "PIKE", "SPEAR", "CLUB"],
profitList=[11, 18, 15, 17, 11],
capacityList=[50000, 75000, 40000, 30000],
consumptionList=[[15, 10, 10, 10],
[20, 0, 20, 0],
[15, 5, 10, 10],
[5, 10, 9, 15],
[1, 25, 1, 25]])
countingRods()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment