def computeLambda(state, maximumTime=1.0): activeAgents = state.getActiveAgents() agentNames = getUniqueNames(activeAgents, prefix="Agent ") classNames = getUniqueNames(state.getChoiceClasses(), prefix="Class ") choiceNames = getUniqueNames(state.getChoices(), prefix="") choiceVariables = LpVariable.dicts("p", choiceNames.values(), lowBound=0) lambdaVariable = LpVariable("l", lowBound=0.0, upBound=maximumTime) def createConstraints(problem, variable): problem += lpSum(choiceVariables) <= 1, "Distribution" for choiceClass, height in state.getCurrentClassHeights().items(): problem += createLpSum(choiceClass, choiceNames, choiceVariables) >= \ height, classNames[choiceClass] + " height" for agent in state.getActiveAgents(): problem += createLpSum(state.getCurrentAgentChoiceClass(agent), choiceNames, choiceVariables) >= \ state.getAgentHeight(agent) + variable * state.getAgentSpeed(agent), \ agentNames[agent] + " push" problem = LpProblem("Lambda", LpMaximize) createConstraints(problem, lambdaVariable) problem.setObjective(lambdaVariable) checkPulpStatus(problem.solve(state.getSettings().getSolver())) lambdaOpt = lambdaVariable.value() bouncingAgents = [] stringAgents = [] #TODO just a workaround; find better solution for currentAgent in activeAgents: print "Current agent: " + agentNames[ currentAgent] # name is off by one problem = LpProblem(agentNames[currentAgent], LpMaximize) createConstraints(problem, lambdaOpt) (choiceClass, height, speed) = state.getAgentData(currentAgent) # print "Choice Class: " + repr(choiceClass) + ", print "height: " + repr(height) + " , speed: " + repr(speed) problem.setObjective( createLpSum(choiceClass, choiceNames, choiceVariables) - lambdaOpt * speed - height) checkPulpStatus(problem.solve(state.getSettings().getSolver())) value = problem.objective.value() # print "value: " + repr(value) + "\n" if not state.getSettings().isNonnegative(value): raise ValueError( str(value) + " negative while determining bounce of " + repr(currentAgent) + " from " + repr(choiceClass) + "@" + str(height) + "/" + str(speed)) if state.getSettings().isClose(value, 0): bouncingAgents.append(currentAgent) stringAgents.append(int(currentAgent.getName())) print "climbing time: " + repr(lambdaOpt) + ", bouncingAgents: " + str( stringAgents) + "\n" # print map(Agent.getName(), bouncingAgents) return (lambdaOpt, bouncingAgents)
def computeLambda(state, maximumTime=1.0): ''' @type state: SSRState @type maximumTime: float ''' towerNames = getUniqueNames(state.getTowers(), prefix="T") choiceNames = getUniqueNames(state.getChoices(), prefix="") choiceVariables = LpVariable.dicts("p", choiceNames.values(), lowBound=0.0) lambdaVariable = LpVariable("l", lowBound=0.0, upBound=maximumTime) def createConstraints(problem, variable): problem += lpSum(choiceVariables) <= 1, "Distribution" for tower, towerName in towerNames.items(): problem += createLpSum(tower.getChoiceClass(), choiceNames, choiceVariables) >= \ tower.getHeight() + variable * \ tower.getSpeed(), towerName problem = LpProblem("Lambda", LpMaximize) createConstraints(problem, lambdaVariable) problem.setObjective(lambdaVariable) checkPulpStatus(problem.solve(state.getSettings().getSolver())) lambdaOpt = lambdaVariable.value() freezingTowers = [] for currentTower, towerName in towerNames.items(): if currentTower.isFrozen(): continue problem = LpProblem(towerName, LpMaximize) createConstraints(problem, lambdaOpt) problem.setObjective( createLpSum(currentTower.getChoiceClass(), choiceNames, choiceVariables) - lambdaOpt * currentTower.getSpeed() - currentTower.getHeight()) checkPulpStatus(problem.solve(state.getSettings().getSolver())) value = problem.objective.value() if not state.getSettings().isNonnegative(value): raise ValueError( str(value) + " negative while determining frozen state of " + repr(currentTower)) if state.getSettings().isClose(problem.objective.value(), 0): freezingTowers.append(currentTower) return (lambdaOpt, frozenset(freezingTowers))
} AllStudentsNumber = { "1": [53, 63, 65, 63, 94, 42, 58], "2": [13, 53, 69, 24, 42, 19, 48], "3": [40, 7, 10, 82, 64, 86, 2], "4": [51, 19, 36, 75, 92, 92, 14], "5": [73, 82, 22, 29, 72, 74, 77], "6": [73, 82, 22, 29, 72, 74, 77], } # 今回の問題では総和を最大化するので LpMaximize を指定する problem = LpProblem('GroupAllScore', LpMaximize) # 使用する変数 s1 = LpVariable('S1', 1, 6, 'Continuous') s2 = LpVariable('S2', 1, 6, 'Continuous') s3 = LpVariable('S3', 1, 6, 'Continuous') s4 = LpVariable('S4', 1, 6, 'Continuous') s5 = LpVariable('S5', 1, 6, 'Continuous') s6 = LpVariable('S6', 1, 6, 'Continuous') group1 = [s1, s2] group2 = [s3, s4] group3 = [s5, s6] AllStudentsNumberDup = group1 + group2 + group3 # 目的関数 # score1 = AllStudents[group1[0]][0] + AllStudents[group1[1]][1] # score2 = AllStudents[group2[0]][0] + AllStudents[group2[1]][1] # score3 = AllStudents[group3[0]][0] + AllStudents[group3[1]][1] # problem += score1 + score2 + score3
from pulp.constants import LpMaximize from pulp.pulp import LpProblem, LpVariable # 今回の問題では総和を最大化するので LpMaximize を指定する problem = LpProblem('Restaurant', LpMaximize) # 使用する変数 x = LpVariable('X') y = LpVariable('Y') # 目的関数 problem += 30 * x + 25 * y # 制約条件 problem += 0.5 * x + 0.25 * y <= 10 # ひき肉の総量は 3800g problem += 0.5 * x + 0.75 * y <= 15 # 玉ねぎの総量は 2100g # 解く problem.solve() # 結果表示 print('x: {x}'.format(x=x.value())) print('y: {y}'.format(y=y.value())) print(x.value() * y.value()) # class Node: # def __init__(self, x, y): # self.x = x # self.y = y # self.state = None
def lp_model(cg: ComputationGraph, agentsdef: Iterable[AgentDef], footprint: Callable[[str], float], capacity: Callable[[str], float], route: Callable[[str, str], float], msg_load: Callable[[str, str], float], hosting_cost: Callable[[str, str], float]): comp_names = [n.name for n in cg.nodes] agt_names = [a.name for a in agentsdef] pb = LpProblem('ilp_compref', LpMinimize) # One binary variable xij for each (variable, agent) couple xs = LpVariable.dict('x', (comp_names, agt_names), cat=LpBinary) # One binary variable for computations c1 and c2, and agent a1 and a2 betas = {} count = 0 for a1, a2 in combinations(agt_names, 2): # Only create variables for couple c1, c2 if there is an edge in the # graph between these two computations. for l in cg.links: # As we support hypergraph, we may have more than 2 ends to a link for c1, c2 in combinations(l.nodes, 2): count += 2 b = LpVariable('b_{}_{}_{}_{}'.format(c1, a1, c2, a2), cat=LpBinary) betas[(c1, a1, c2, a2)] = b pb += b <= xs[(c1, a1)] pb += b <= xs[(c2, a2)] pb += b >= xs[(c2, a2)] + xs[(c1, a1)] - 1 b = LpVariable('b_{}_{}_{}_{}'.format(c1, a2, c2, a1), cat=LpBinary) betas[(c1, a2, c2, a1)] = b pb += b <= xs[(c2, a1)] pb += b <= xs[(c1, a2)] pb += b >= xs[(c1, a2)] + xs[(c2, a1)] - 1 # Set objective: communication + hosting_cost pb += _objective(xs, betas, route, msg_load, hosting_cost), \ 'Communication costs and prefs' # Adding constraints: # Constraints: Memory capacity for all agents. for a in agt_names: pb += lpSum([footprint(i) * xs[i, a] for i in comp_names])\ <= capacity(a), \ 'Agent {} capacity'.format(a) # Constraints: all computations must be hosted. for c in comp_names: pb += lpSum([xs[c, a] for a in agt_names]) == 1, \ 'Computation {} hosted'.format(c) # solve using GLPK status = pb.solve(solver=GLPK_CMD(keepFiles=1, msg=False, options=['--pcost'])) if status != LpStatusOptimal: raise ImpossibleDistributionException("No possible optimal" " distribution ") logger.debug('GLPK cost : %s', value(pb.objective)) # print('BETAS:') # for c1, a1, c2, a2 in betas: # print(' ', c1, a1, c2, a2, value(betas[(c1, a1, c2, a2)])) # # print('XS:') # for c, a in xs: # print(' ', c, a, value(xs[(c, a)])) mapping = {} for k in agt_names: agt_computations = [i for i, ka in xs if ka == k and value(xs[(i, ka)]) == 1] # print(k, ' -> ', agt_computations) mapping[k] = agt_computations return mapping