def covering_model(conf_mat, len_demand): """ :param conf_mat: :param len_demand: :return: """ num_conf, num_shape = conf_mat.shape prob = LpProblem("cutting_stock", LpMinimize) # build model y = LpVariable.dict("configurations", range(num_conf), lowBound=0, cat=LpInteger) # decision variable prob += lpSum(y[i] for i in range(num_conf)) # objective # add constraints for j in range(num_shape): prob += lpSum(y[i] * conf_mat[i, j] for i in range(num_conf)) >= len_demand[j] prob.writeLP("cutting_stock.lp") prob.solve() # get variable values res = np.zeros(num_conf, dtype=int) for i in range(num_conf): val = prob.variables()[i].value() if val > 0.9: res[i] = round(val) return res
def linear_prog(numStates, numActions, rewards, transition, discount, mdpType, end): lin_prog = LpProblem("MDP", LpMinimize) decision_var = LpVariable.dict("value_function", range(numStates)) LpSolverDefault.msg = 0 # The Objective Function lin_prog += lpSum([decision_var[i] for i in range(numStates)]) # adding constraints V = np.zeros((numStates, 1), dtype=LpVariable) for i in range(numStates): V[i][0] = decision_var[i] for state in range(numStates): for action in range(numActions): lowerBound = bellman_equations(transition[state][action], rewards[state][action], V, discount) lin_prog += decision_var[state] >= lowerBound if (mdpType == "episodic"): for i in end: lin_prog += (decision_var[i] == 0) lin_prog.solve(pulp.PULP_CBC_CMD(msg=0)) V = np.zeros((numStates, 1)) for i in range(numStates): V[i][0] = decision_var[i].varValue P = np.zeros((numStates, 1), dtype=int) tmp = np.zeros((numActions, )) for state in range(numStates): for action in range(numActions): tmp[action] = bellman_equations(transition[state][action], rewards[state][action], V, discount) P[state][0] = np.argmax(tmp) return P, V
def _eta_max(energies, productions, co2s, turn_overs, dmu_right): ''' eta max ''' energy_right = dmu_right.energy.total co2_right = dmu_right.co2.total turn_over_right = dmu_right.turn_over.turn_over produciton_right = dmu_right.production.production prob = LpProblem('eta max', LpMaximize) variables_count = len(productions) ingredients = [str(symbols + 1) for symbols in range(variables_count)] symbols = LpVariable.dict('x_%s', ingredients, lowBound=0) cost = dict(zip(ingredients, productions)) prob += lpSum([cost[i] * symbols[i] for i in ingredients]) energy_dict = dict(zip(ingredients, energies)) turn_over_dict = dict(zip(ingredients, turn_overs)) co2_dict = dict(zip(ingredients, co2s)) prob += lpSum([energy_dict[i] * symbols[i] for i in ingredients]) <= energy_right prob += lpSum([turn_over_dict[i] * symbols[i] for i in ingredients]) >= turn_over_right prob += lpSum([co2_dict[i] * symbols[i] for i in ingredients]) == co2_right if prob.solve() != 1: logging.error('eta max unsolved situation occurs') raise UserWarning else: return prob.objective.value() / produciton_right
def LinearProgramming(numStates, numActions, rewards, transition, discount, mdpType): mdpProblem = LpProblem("MDP", LpMinimize) dictVar = LpVariable.dict("value_function", range(numStates)) # adding objective function mdpProblem += lpSum([dictVar[i] for i in range(numStates)]) # adding constraints V = np.zeros((numStates, 1), dtype=LpVariable) for i in range(numStates): V[i][0] = dictVar[i] for state in range(numStates): for action in range(numActions): lowerBound = Bellman(transition[state][action], rewards[state][action], V, discount) mdpProblem += dictVar[state] >= lowerBound # additional constraint for episodic MDPs if (mdpType == "episodic"): mdpProblem += (dictVar[numStates - 1] == 0) # solve the linear programming problem mdpProblem.solve() V = np.zeros((numStates, 1)) for i in range(numStates): V[i][0] = dictVar[i].varValue # getting the optimum policy P = np.zeros((numStates, 1), dtype=int) tmp = np.zeros((numActions, )) for state in range(numStates): for action in range(numActions): tmp[action] = Bellman(transition[state][action], rewards[state][action], V, discount) P[state][0] = np.argmax(tmp) return P, V
def optimize_pulp(self): from pulp import LpVariable,LpProblem,LpMaximize,LpBinary,PULP_CBC_CMD p = LpProblem("knapsackP",LpMaximize) x = LpVariable.dict("x",indexs=(range(self.num)),lowBound=0,upBound=1,cat=LpBinary) #価値最大化 #p += sum(x[i]*self.p[i].get_value() for i in range(self.num)) #p += lpDot(x,[self.p[i].get_value() for i in range(self.num)]) p += lpSum(x[i]*self.p[i].get_value() for i in range(self.num)) #重量を制限以内 p += lpSum(x[i]*self.p[i].get_weight() for i in range(self.num)) <= self.limit_weight #解く solver=PULP_CBC_CMD(msg=0,threads=10) p.solve(solver) if p.status == 1: print("## Pulp Optimized Result") self.print([int(x[i].value()) for i in range(self.num)]) ret = sum([x[i].value()*self.p[i].get_value() for i in range(self.num)]) del x,p gc.collect() return ret else: print("## Pulp Optimizing Failed")
def _build_alphaijk_binvars(cg: ComputationsFactorGraph, agents_names: Iterable[str]): # As these variables are only used in the objective function, # when optimizing communication cost, we only need them when (i,j) is an # edge in the factor graph alphas = LpVariable.dict('a', ([(link.variable_node, link.factor_node) for link in cg.links], agents_names), cat=LpBinary) return alphas
def _build_alphaijk_binvars(cg: ComputationConstraintsHyperGraph, agents_names: Iterable[str]): # As these variables are only used in the objective function, # when optimizing communication cost, we only need them when (i,j) is an # edge in the factor graph edge_indexes = [] for link in cg.links: for end1, end2 in combinations(link.nodes, 2): edge_indexes.append((end1, end2)) alphas = LpVariable.dict("a", (edge_indexes, agents_names), cat=LpBinary) return alphas
def lp(numStates, numActions, end, rewards, probability, transitions, discount): problem = LpProblem("MDP", LpMinimize) values = LpVariable.dict("valueFunction", range(numStates)) LpSolverDefault.msg = 0 problem += lpSum([values[i] for i in range(numStates)]) V = np.zeros((numStates, 1), dtype=LpVariable) for i in range(numStates): V[i][0] = values[i] for i in transitions: if i not in end: for j in transitions[i]: value = 0 for trans in transitions[i][j]: value += trans[2] * (trans[1] + discount * values[trans[0]]) problem += (values[i] >= value) # additional constraint for episodic MDPs for i in end: problem += (values[i] == 0) # solve the linear programming problem problem.solve() newValues = np.zeros(numStates) for i in range(numStates): newValues[i] = values[i].varValue # getting the optimum policy actions = np.zeros(numStates) for i in transitions: if i not in end: maxValue = -float('inf') bestAction = 0 for j in transitions[i]: value = 0 for trans in transitions[i][j]: value += trans[2] * (trans[1] + discount * newValues[trans[0]]) if value > maxValue: maxValue = value bestAction = j actions[i] = bestAction return newValues, actions
def _theta_max(enengies, productions, co2s, energy_right, production_right, co2_right): ''' _theta_max ''' # the linear programming objective is maximize prob = LpProblem("theta_max", LpMaximize) variablecount = len(enengies) ingredients = [str(symbols + 1) for symbols in range(variablecount)] # the variable symbols x1, x2, x3 .... xn symbols = LpVariable.dict('x_%s', ingredients, lowBound=0) cost = dict(zip(ingredients, productions)) prob += lpSum([cost[i] * symbols[i] for i in ingredients]) ene_dict = dict(zip(ingredients, enengies)) co2_dict = dict(zip(ingredients, co2s)) prob += lpSum([ene_dict[i] * symbols[i] for i in ingredients]) <= energy_right prob += lpSum([co2_dict[i] * symbols[i] for i in ingredients]) == co2_right if prob.solve() != 1: raise UserWarning else: return prob.objective.value() / production_right
def _lambda_min(enengies, productions, co2s, energy_right, production_right, co2_right): ''' _lambda_min ''' # the linear programming objective is minimize prob = LpProblem("lambda_min", LpMinimize) variablecount = len(enengies) ingredients = [str(symbols + 1) for symbols in range(variablecount)] # variable symbols such x1, x2, x3 ... xn symbols = LpVariable.dict('x_%s', ingredients, lowBound=0) cost = dict(zip(ingredients, enengies)) prob += lpSum([cost[i] * symbols[i] for i in ingredients]) pro_dict = dict(zip(ingredients, productions)) co2_dict = dict(zip(ingredients, co2s)) # linear constraint condition prob += lpSum([pro_dict[i] * symbols[i] for i in ingredients]) >= production_right prob += lpSum([co2_dict[i] * symbols[i] for i in ingredients]) == co2_right if prob.solve() != 1: raise UserWarning return prob.objective.value() / energy_right
product_manufactured: Dict = {0: "CP320", 1: "AF250"} product_sales: Dict = {0: "CP320", 1: "AF250", 2: "clinker"} components: Dict = {0: "clinker", 1: "slag", 2: "plaster", 3: "additive"} composition: List = [[0.85, 0.50], [0.07, 0.45], [0.03, 0.03], [0.05, 0.02]] limit_manufacture: int = 1100000 clinker_sales: int = 200000 slag_orders: int = 180000 plaster_orders: int = 50000 margin: List = [41.00, 37.80, 34.40] slag_price: float = 22.10 plaster_price: float = 34.20 additive_price: float = 1.90 # Model and variables model = LpProblem("Cement_production", LpMaximize) var = LpVariable.dict("Product_sale", product_sales, lowBound=0, cat="Integer") # Goal function model += (lpSum(var[x] * margin[x] for x in product_sales) - slag_price * lpSum( (var[x] * composition[1][x] for x in product_manufactured)) - margin[2] * lpSum( (var[x] * composition[2][x] for x in product_manufactured)) - additive_price * lpSum( (var[x] * composition[3][x] for x in product_manufactured))) # Constrains model += var[2] <= clinker_sales model += lpSum(var[x] for x in product_manufactured) <= limit_manufacture model += (lpSum(composition[0][x] * var[x]
def ilp_cgdp( 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], ): agt_names = [a.name for a in agentsdef] pb = LpProblem("oilp_cgdp", LpMinimize) # One binary variable xij for each (variable, agent) couple xs = LpVariable.dict("x", (cg.node_names(), agt_names), cat=LpBinary) # TODO: Do not create var for computation that are already assigned to an agent with hosting = 0 ? # Force computation with hosting cost of 0 to be hosted on that agent. # This makes the work much easier for glpk ! x_fixed_to_0 = [] x_fixed_to_1 = [] for agent in agentsdef: for comp in cg.node_names(): assigned_agent = None if agent.hosting_cost(comp) == 0: pb += xs[(comp, agent.name)] == 1 x_fixed_to_1.append((comp, agent.name)) assigned_agent = agent.name for other_agent in agentsdef: if other_agent.name == assigned_agent: continue pb += xs[(comp, other_agent.name)] == 0 x_fixed_to_0.append((comp, other_agent.name)) logger.debug( f"Setting binary varaibles to fixed computation {comp}") # 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): if (c1, a1, c2, a2) in betas: continue count += 2 b = LpVariable("b_{}_{}_{}_{}".format(c1, a1, c2, a2), cat=LpBinary) betas[(c1, a1, c2, a2)] = b # Linearization constraints : # a_ijmn <= x_im # a_ijmn <= x_jn if (c1, a1) in x_fixed_to_0 or (c2, a2) in x_fixed_to_0: pb += b == 0 elif (c1, a1) in x_fixed_to_1: pb += b == xs[(c2, a2)] elif (c2, a2) in x_fixed_to_1: pb += b == xs[(c1, a1)] else: 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) if (c1, a2) in x_fixed_to_0 or (c2, a1) in x_fixed_to_0: pb += b == 0 elif (c1, a2) in x_fixed_to_1: pb += b == xs[(c2, a1)] elif (c2, a1) in x_fixed_to_1: pb += b == xs[(c1, a2)] else: 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 cg.node_names()]) <= capacity(a), "Agent {} capacity".format(a), ) # Constraints: all computations must be hosted. for c in cg.node_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", pulp.value(pb.objective)) mapping = {} for k in agt_names: agt_computations = [ i for i, ka in xs if ka == k and pulp.value(xs[(i, ka)]) == 1 ] # print(k, ' -> ', agt_computations) mapping[k] = agt_computations return mapping
from pulp import LpMinimize, LpProblem, LpStatus, LpVariable, lpSum, value # Problem data teams: List = [0, 1, 2, 3, 4] jobs: List = [0, 1, 2, 3, 4] costs: List = [ [33, 22, 40, 21, 43], [27, 40, 55, 32, 26], [33, 38, 42, 49, 29], [36, 30, 52, 36, 34], [28, 45, 31, 42, 19], ] # Decision variables var = LpVariable.dict("x", (teams, jobs), cat="Binary") # Model model = LpProblem("Designation_problem", LpMinimize) # Goal function model += lpSum(var[x] * costs[x[0]][x[1]] for x in var.keys()) # Constrains constrains_list: List = [] for time in teams: for job in jobs: constrains_list.append(var[(time, job)]) model += lpSum(constrains_list) == 1 constrains_list: List = []
2: 3.4, 3: 2, 4: 3, 5: 1.9, 6: 0.6, 7: 1, 8: 2, 9: 3 } availabilities: Dict = {0: 4000, 1: 5000, 2: 3000, 3: 7000, 4: 2500} total_volume: int = 1000 # Decision variable var = LpVariable.dict("P", product, lowBound=0) # Model model = LpProblem("Manufacturing_problem_mix", LpMaximize) # Goal function model += lpSum(var[x] * profit[x] for x in product) # Constrains constrains_list: List = [] for i in availabilities.keys(): for j in product: if cycle_time[j][i] != 0: constrains_list.append(var[j] * cycle_time[j][i]) else:
from pulp import LpVariable, LpProblem, LpMinimize, LpStatus, lpSum, value # Variaveis do Problema times = [0, 1, 2, 3, 4] obras = [0, 1, 2, 3, 4] custos = [[33, 22, 40, 21, 43], [33, 40, 26, 17, 36], [34, 38, 42, 29, 39], [36, 30, 21, 36, 40], [28, 45, 31, 42, 19]] # Variaveis de Decisao var = LpVariable.dict("x", (times, obras), cat='Binary') # criar problema model = LpProblem('Problema_designacao', LpMinimize) # Criar funcao objetivo lista_fo = [] for x in var.keys(): lista_fo.append(var[x] * custos[x[0]][x[1]]) model += lpSum(lista_fo) print(model) # Restricoes lista_rest = [] for time in times: for obra in obras: lista_rest.append(var[(time, obra)])
def _build_xs_binvar(vars_to_host, agents_names): if not vars_to_host: return {} return LpVariable.dict("x", (vars_to_host, agents_names), cat=LpBinary)
import numpy as np from pulp import LpMaximize, LpProblem, LpStatus, LpVariable, lpSum, value # Problem Data components: Dict = {0: "pure_gas", 1: "octane", 2: "additive"} availabilities = np.array([9600000, 4800000, 2200000]) gas_types: Dict = {0: "green_gas", 1: "blue_gas", 2: "common_gas"} composition: List = [[0.22, 0.50, 0.28], [0.52, 0.34, 0.14], [0.74, 0.20, 0.06]] contribution_margin = np.array([0.30, 0.25, 0.20]) limit_blue_gas: int = 600000 min_common_gas: int = 16 # times more than green gas # Model and variables model = LpProblem("Mix_gas", LpMaximize) var = LpVariable.dict("GAS", gas_types, lowBound=0, cat="Integer") model += lpSum(var[x] * contribution_margin[x] for x in gas_types) # Constrains model += (lpSum(var[0] * composition[0][0] + var[1] * composition[1][0] + var[2] * composition[2][0]) <= availabilities[0]) model += (lpSum(var[0] * composition[0][1] + var[1] * composition[1][1] + var[2] * composition[2][1]) <= availabilities[1]) model += (lpSum(var[0] * composition[0][2] + var[1] * composition[1][2] + var[2] * composition[2][2]) <= availabilities[2]) model += lpSum(min_common_gas * (var[0])) - lpSum(var[2]) <= 0 model += lpSum(var[1]) <= limit_blue_gas print(model)
""" Operational Research for allocation of Nexoos investments """ available_capital = 3000 investment = ['C2', 'C3', 'B6', 'B4'] min_invest = 1000 max_invest = 2000 interest = {'C2': 0.02235, 'C3': 0.02360, 'B6': 0.01808, 'B4': 0.01642} risk = {'C2': 0.04, 'C3': 0.03, 'B6': 0.02, 'B4': 0.017} # Decision variables var = LpVariable.dict('Investment', investment, lowBound=min_invest, upBound=max_invest) #print(var) model = LpProblem("Loan_allocation", LpMaximize) # Objective Function lista_fo = [] for x in var.keys(): lista_fo.append(interest[x] * (1 - risk[x]) * var[x]) model += lpSum(lista_fo) # Constrains lista_rest = []
from pulp import LpVariable, LpProblem, LpMaximize, LpStatus, lpSum, value itens = ['A', 'B', 'C', 'D', 'E', 'F'] capacidade = 20000 peso = {'A': 7000, 'B': 4500, 'C': 8700, 'D': 8000, 'E': 4900, 'F': 7500} valor = {'A': 36, 'B': 64, 'C': 40, 'D': 45, 'E': 60, 'F': 40} # Variaveis de Decisao var = LpVariable.dict("", itens, cat="Binary") # Criar o Problema model = LpProblem("Problema_Mochila01", LpMaximize) # Funcao Objetivo lista_fo = [] for item in itens: lista_fo.append(var[item] * valor[item]) model += lpSum(lista_fo) # Restricoes lista_rest = [] for item in itens: lista_rest.append(var[item] * peso[item]) model += lpSum(lista_rest) <= capacidade print(model)
fixed_costs = np.array([ 300000, 400000, 490000, ]) variable_costs: object = ( [40, 15, 20], [10, 12, 25], [30, 17, 27], [10, 12, 20], ) annual_weeks: int = 52 # Model and variables model = LpProblem("Terminal_location", LpMinimize) var_1 = LpVariable.dict("Cities", cities, lowBound=0, cat="Binary") var_2 = LpVariable.dict("Location", (terminals, cities), lowBound=0, cat="Integer") # Goal function model += lpSum(variable_costs[x][i] * var_2[(x, i)] for x, i in var_2) * annual_weeks + lpSum( var_1[y] * fixed_costs[y] for y in cities) # Constrains for i in terminals: model += lpSum(var_2[(i, x)] for x in cities) == weekly_manufacture[i] for x in cities: model += lpSum(var_2[(i, x)] for i in terminals) <= availabilities[x]
from pulp import LpVariable, LpProblem, LpMinimize, LpStatus, lpSum, value # Dados do problema maquinas = [0, 1, 2] custo_fixo = {0: 25, 1: 45, 2: 60} custo_variavel = {0: 4, 1: 7, 2: 12} capacidade = {0: 30, 1: 60, 2: 78} # Variaveis de decisao var = LpVariable.dict("x", (maquinas), cat="Integer", lowBound=0) var2 = LpVariable.dict("y", (maquinas), cat="Binary") # Criacao do Modelo model = LpProblem("Problema_carga_fixa", LpMinimize) # Criacao da funcao objetivo lista_fo = [] for m in maquinas: lista_fo.append(var[m] * custo_variavel[m] + var2[m] * custo_fixo[m]) model += lpSum(lista_fo) print(model)
def wildcard_suggestion(slim_elements_df, optimization_metric, current_team_value, weight): fpl_problem = LpProblem('FPL', LpMaximize) optimization_df = slim_elements_df[[ 'id', 'second_name', 'team_name', 'team', 'total_points', 'position', 'now_cost', 'ict_index', 'form' ]] optimization_df = optimization_df.join( pd.get_dummies(optimization_df['position'])) players = optimization_df['second_name'] optimization_df['now_cost'] = optimization_df['now_cost'] / 10 x = LpVariable.dict('x_ % s', players, lowBound=0, upBound=1, cat=LpInteger) metric_data = [] point_arr = np.array(optimization_df['total_points']) point_norm = np.linalg.norm(point_arr) point_arr = point_arr / point_norm clean_player_points = dict( zip(optimization_df.second_name, np.array(optimization_df['total_points']))) player_points = dict(zip(optimization_df.second_name, point_arr)) ict_arr = np.array(optimization_df['total_points']) ict_norm = np.linalg.norm(ict_arr) ict_arr = ict_arr / ict_norm clean_player_ict = dict( zip(optimization_df.second_name, np.array(optimization_df['ict_index']))) player_ict = dict(zip(optimization_df.second_name, ict_arr)) form_arr = np.array(optimization_df['form']) form_norm = np.linalg.norm(form_arr) form_arr = form_arr / form_norm clean_player_form = dict( zip(optimization_df.second_name, np.array(optimization_df['form']))) player_form = dict(zip(optimization_df.second_name, ict_arr)) #to get player id clean_player_id = dict( zip(optimization_df.second_name, np.array(optimization_df['id']))) if 'total_points' in optimization_metric: metric_data.append(player_points) if 'ict_index' in optimization_metric: metric_data.append(player_ict) if 'form' in optimization_metric: metric_data.append(player_form) final_data = {} for i in range(len(metric_data)): if i == 0: m = 'total_points' elif i == 1: m = 'ict_index' else: m = 'form' d = metric_data[i] for player in d: if player in final_data: final_data[player] += weight[m] * d[player] else: final_data[player] = weight[m] * d[player] fpl_problem += sum(final_data[i] * x[i] for i in players) position_names = ['Goalkeeper', 'Defender', 'Midfielder', 'Forward'] position_constraints = [2, 5, 5, 3] constraints = dict(zip(position_names, position_constraints)) constraints['total_cost'] = float(current_team_value) constraints['team'] = 3 player_cost = dict( zip(optimization_df.second_name, optimization_df.now_cost)) player_position = dict( zip(optimization_df.second_name, optimization_df.position)) player_gk = dict( zip(optimization_df.second_name, optimization_df.Goalkeeper)) player_def = dict( zip(optimization_df.second_name, optimization_df.Defender)) player_mid = dict( zip(optimization_df.second_name, optimization_df.Midfielder)) player_fwd = dict(zip(optimization_df.second_name, optimization_df.Forward)) fpl_problem += sum([player_cost[i] * x[i] for i in players]) <= float(constraints['total_cost']) fpl_problem += sum([player_gk[i] * x[i] for i in players]) == constraints['Goalkeeper'] fpl_problem += sum([player_def[i] * x[i] for i in players]) == constraints['Defender'] fpl_problem += sum([player_mid[i] * x[i] for i in players]) == constraints['Midfielder'] fpl_problem += sum([player_fwd[i] * x[i] for i in players]) == constraints['Forward'] for t in optimization_df.team.unique(): optimization_df['team_' + str(t).lower()] = np.where( optimization_df.team == t, int(1), int(0)) for t in optimization_df.team: player_team = dict( zip(optimization_df.second_name, optimization_df['team_' + str(t)])) fpl_problem += sum([player_team[i] * x[i] for i in players]) <= constraints['team'] fpl_problem.solve() total_points = 0. total_cost = 0. optimal_squad = [] for p in players: if x[p].value() != 0: total_points += clean_player_points[p] total_cost += player_cost[p] optimal_squad.append({ 'name': p, 'position': player_position[p], 'cost': player_cost[p], 'points': clean_player_points[p], 'ict_index': clean_player_ict[p], 'form': clean_player_form[p], 'id': clean_player_id[p] }) solution_info = {'total_points': total_points, 'total_cost': total_cost} optimal_squad_df = pd.DataFrame(optimal_squad) optimal_squad_df.sort_values('position', inplace=True) return optimal_squad_df, solution_info
from typing import Dict, List from pulp import LpMinimize, LpProblem, LpStatus, LpVariable, lpSum, value # Problem data machines: List = [0, 1, 2] fixed_cost: Dict = {0: 25, 1: 45, 2: 60} variable_cost: Dict = {0: 4, 1: 7, 2: 12} availability: Dict = {0: 30, 1: 60, 2: 78} # Decision variables var_1 = LpVariable.dict("X", machines, cat="Integer", lowBound=0) var_2 = LpVariable.dict("Y", machines, cat="Binary") # Model model = LpProblem("fixed_load", LpMinimize) # Goal function model += lpSum(var_1[i] * variable_cost[i] + var_2[i] * fixed_cost[i] for i in machines) # Constrains for i in machines: model += var_1[i] <= availability[i] * var_2[i] model += lpSum(x for x in var_1.values()) == 75 print(model)
from pulp import LpMaximize, LpProblem, LpStatus, LpVariable, lpSum, value # Problem data # b1 b2 b3 reward: List = [ [30, -10, -30], # Very Hard A [0, -40, 10], # Average A [-50, 60, 0], ] # Light strategy A strategy_A: List = [0, 1, 2] strategy_B: List = [0, 1, 2] # Decision variables var = LpVariable.dict("A", strategy_A, lowBound=0) v = LpVariable("v") # Model model = LpProblem("zero_sum_game", LpMaximize) # Goal function model += v # Constrains constrains_list: List = [] for j in strategy_B: for i in strategy_A: constrains_list.append(var[i] * reward[i][j]) model += v - lpSum(constrains_list) == 0
#格子の数 SIZE = 10 #ばらまくPointの数 N = 3 #2点間の距離を算出する def dist(p1, p2): return (sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) / SIZE) ######変数定義 #どこにPointを置くか x = LpVariable.dict(name="x", indexs=(range(SIZE), range(SIZE)), lowBound=0, upBound=1, cat=LpBinary) #今回のキモ 多目的のための変数(どんなに良くても対角の√2以下) z = LpVariable("z", lowBound=0, upBound=1.5, cat=LpContinuous) #問題定義 p = LpProblem(name="SpreadingPointsProblem", sense=LpMaximize) #zの最大化問題として定義 p += z #N個のPointが配置される tmp_sub = 0 for i, j in product(range(SIZE), range(SIZE)): tmp_sub += x[(i, j)]
1: 'Terminal_2', 2: 'Terminal_3', 3: 'Terminal_4' } manufacture = {0: 800, 1: 1200, 2: 650, 3: 1450} variable_costs = [[40, 15, 20], [10, 12, 25], [30, 17, 27], [10, 12, 20]] locations = {0: 'Niteroi', 1: 'Angra', 2: 'Campos'} fixed_costs = {0: 300000, 1: 400000, 2: 490000} availabilities = {0: 1500, 1: 2600, 2: 3400} weeks = 52 # Objective Function var_1 = LpVariable.dict('Cities', locations, cat='Binary') var_2 = LpVariable.dict("Location", (terminals, locations), lowBound=0, cat='Integer') objective_list = [] for i in var_1.keys(): objective_list.append(var_1[i] * fixed_costs[i]) for x in var_2.keys(): objective_list.append(weeks * (var_2[x] * variable_costs[x[0]][x[1]])) objective_func += lpSum(objective_list) # Constrains
def _build_fs_binvar(facs_to_host, agents_names): if not facs_to_host: return {} return LpVariable.dict("f", (facs_to_host, agents_names), cat=LpBinary)
# Problem Data feed: List = [0, 1, 2, 3, 4, 5] costs: Dict = {0: 0.74, 1: 0.70, 2: 0.83, 3: 0.81, 4: 0.73, 5: 0.75} minimum: Dict = {0: 200, 1: 180, 2: 150} # Carbohydrate # Protein # Vitamin inf_nutri: List = [ [50, 60, 30, 0, 20, 45], [27, 0, 40.5, 20, 30, 50], [50, 80, 60, 30, 20, 40], ] # Model and Decision Variables model = LpProblem("Diet_problem", LpMinimize) var = LpVariable.dict("R", feed, lowBound=0, cat="Integer") # Goal function model += lpSum(var[x] * costs[x] for x in var.keys()) # Constrains list_rest: List = [] for i in minimum.keys(): for j in feed: list_rest.append(var[j] * inf_nutri[i][j]) model += lpSum(list_rest) >= minimum[i] list_rest = [] print(model) # Solving problem
passenger_capacity: Dict = {0: 50, 1: 30, 2: 20} aircraft_availability: Dict = {0: 5, 1: 8, 2: 10} route_demand: Dict = {0: 150, 1: 200, 2: 90, 3: 300} total_travels: List = [[3, 2, 2, 1], [4, 3, 3, 2], [5, 5, 4, 2]] operational_costs = [ [1000, 1100, 1200, 1100], [800, 900, 1000, 1000], [600, 800, 800, 1000], ] # Model and Decision Variables model = LpProblem("Routing_problem", LpMinimize) var = LpVariable.dict("aircraft", (aircraft_type, routes), lowBound=0, cat="Integer") # Goal Function model += lpSum(var[(x, y)] * operational_costs[x][y] for x, y in var.keys()) # Constrains for y in route_demand.keys(): """ Soma as capacidades das aeronaves nas rotas e limita em relacao a demanda """ model += (lpSum(passenger_capacity[x] * var[(x, y)] for x in passenger_capacity) >= route_demand[y]) for i in aircraft_type: """ Soma o numero de viagens/rota e restringe em relacao a disponibilidade de aeronaves """ model += (lpSum(var[(i, y)] * (1 / total_travels[i][y]) for y in routes) <= aircraft_availability[i])
from pulp import LpVariable, LpProblem, LpMaximize, lpSum, LpStatus, value # Dados do Problema retornos = [[30, -10, -30], [0, -40, 10], [-50, 60, 0]] estrategia_a = [0, 1, 2] estrategia_b = [0, 1, 2] # Criacao das variaveis de decisao var = LpVariable.dict("A", (estrategia_a), lowBound=0) v = LpVariable('v') # Criacao do modelo model = LpProblem("Jogo_soma_ZERO", LpMaximize) # Criacao da funcao Objetivo model += v # Criacao das restricoes lista_rest = [] for j in estrategia_b: for i in estrategia_a: lista_rest.append(var[i] * retornos[i][j]) model += v - lpSum(lista_rest) == 0 lista_rest = []