def fact(meta, plazo, DD, Gm, F): # All the (symbolic) variables are declared, with a name and optionally a lower and/or upper bound. a = Variable('%ahorro', lb=0, ub=1) g = Variable('%otrosgastos', lb=0, ub=1) f = Variable('%fondoemergencia', lb=0, ub=1) # A constraint is constructed from an expression of variables and a lower and/or upper bound (lb and ub). c1 = Constraint(a + g + f, lb=1, ub=1) c2 = Constraint(g * DD, lb=Gm) #El % de ahorro * dinero disponible * el plazo debe ser estrictamente igual a la meta c3 = Constraint(a * DD * plazo, lb=meta, ub=meta) c4 = Constraint(f * DD, lb=F, ub=F) # An objective can be formulated obj = Objective(a * DD * plazo, direction='max') # Variables, constraints and objective are combined in a Model object, which can subsequently be optimized. model = Model(name='Simple model') model.objective = obj model.add([c1, c2, c3, c4]) status = model.optimize() #print("status:", model.status) #print("objective value:", model.objective.value) #print("----------") resultados = { '%ahorro': 0, '%otrosgastos': 0, '%fondoemergencia': 0, 'status': status, 'months': plazo } for var_name, var in model.variables.iteritems(): resultados[var_name] = round(var.primal * DD) if model.status == 'optimal': print('Opcion 1:') print('Ahorrando mensual', resultados['%ahorro'], ', lograras ahorrar', resultados['%ahorro'] * plazo) print('Para otros gastos tendrías disponible mensual', resultados['%otrosgastos']) print('En', plazo, 'meses') else: print('La meta no es factible con las condiciones dadas:') print('Con', DD, 'disponible, ahorrar', meta, 'en', plazo, 'meses, con', Gm, 'mínimo para otros gastos.') resultados['saving'] = resultados['%ahorro'] resultados['other'] = resultados['%otrosgastos'] resultados['emergency'] = resultados['%fondoemergencia'] resultados['total'] = resultados['%ahorro'] * plazo resultados['msg'] = "Ahorrando mensual $ " + '{:,}'.format(resultados['saving']).replace(",",".") \ + " , lograrás ahorrar $ " + '{:,}'.format(resultados['total']).replace(",",".") \ + ". Para otros gastos tendrías disponible mensual $ " \ + '{:,}'.format(resultados['other']).replace(",",".") + " en "+str(resultados['months']) + " meses." return resultados
def buildModel(constraint_list, obj, model_name): """ Construit le model et l'excute pour le résoudre En décommentant les lignes, il est possible d'afficher les élements constitutifs d'un modèle (debug) Args: constraint_list : listes contraintes existantes obj: fonction objectif model_name: nom du model Return: l'objet modèle """ model = Model(name = model_name) model.objective = obj model.add(constraint_list) model.optimize() #Print du modèle pour débug # for cons in model.constraints.items(): # print(cons[1]) # for var in model.variables.items(): # print(var) return model
def stoichiomatrix_solution(S, flux_bounds, objective_index, objective_direction): #We make a variable 'v-(index)' for each reaction (column) in the matrix: variables = make_variables(S, flux_bounds) constraints = make_constraints(S, variables) obj = make_objective(objective_index, objective_direction, variables) model = Model(name='Stoichiomatrix') model.objective = obj model.add(constraints) status = model.optimize() return [status, model]
def tiempo(meta, DD, Gm, F): plazo = 0 while plazo <= 60: a = Variable('%ahorro', lb=0, ub=1) g = Variable('%otrosgastos', lb=0, ub=1) f = Variable('%fondoemergencia', lb=0, ub=1) # A constraint is constructed from an expression of variables and a lower and/or upper bound (lb and ub). c1 = Constraint(a + g + f, lb=1, ub=1) c2 = Constraint(g * DD, lb=Gm) #El % de ahorro * dinero disponible * el plazo debe ser estrictamente igual a la meta c3 = Constraint(a * DD * plazo, lb=meta, ub=meta) c4 = Constraint(f * DD, lb=F, ub=F) # An objective can be formulated obj = Objective(a * DD * plazo, direction='max') # Variables, constraints and objective are combined in a Model object, which can subsequently be optimized. model = Model(name='Simple model') model.objective = obj model.add([c1, c2, c3, c4]) resultados = dict() status = model.optimize() for var_name, var in model.variables.iteritems(): #print(var_name, "=", round(var.primal * DD)) resultados[var_name] = round(var.primal * DD) if model.status == 'optimal': print('Opción 2:') print('Ahorrando mensual', resultados['%ahorro'], ', lograras ahorrar', resultados['%ahorro'] * plazo) print('Para otros gastos tendrías disponible mensual', resultados['%otrosgastos']) print('En', plazo, 'meses') break plazo += 1 if plazo > 60: status = 'overtime' resultados.update({'status': status, 'months': plazo}) resultados['months'] = plazo resultados['saving'] = resultados['%ahorro'] resultados['other'] = resultados['%otrosgastos'] resultados['emergency'] = resultados['%fondoemergencia'] resultados['total'] = resultados['%ahorro'] * plazo resultados['msg'] = "Ahorrando mensual $ " + '{:,}'.format(resultados['saving']).replace(",",".") \ + " , lograrás ahorrar $ " + '{:,}'.format(resultados['total']).replace(",",".") \ + ". Para otros gastos tendrías disponible mensual $ " \ + '{:,}'.format(resultados['other']).replace(",",".") + " en "+str(resultados['months']) + " meses." return resultados
def solveBIP(affinity): m = len(affinity) n = len(affinity[0]) variables = {} for i in range(0, m): variables[i] = {} for j in range(0, n): var = Variable(name="{}_{}".format(i, j), lb=0, ub=1, type="integer") variables[i][j] = var constraints = [] for i in range(0, m): const = Constraint(sum(variables[i].values()), ub=1) constraints.append(const) for j in range(0, n): const = Constraint(sum(row[j] for row in variables.values()), ub=1) constraints.append(const) obj = Objective( sum(affinity[i][j] * variables[i][j] for i in range(0, m) for j in range(0, n))) model = Model(name="BIP Solved") model.add(constraints) model.objective = obj status = model.optimize() # for var in model.variables: # print var.name, " : ", var.primal mat = np.zeros((m, n)) #print mat for ind in model.variables: i, j = ind.name.split("_") i = int(i) j = int(j) mat[i, j] = ind.primal return mat
constraints.append(const) for destination in demand: const = Constraint(sum(row[destination] for row in variables.values()), lb=demand[destination], name="{}_demand".format(destination)) constraints.append(const) # Define the objective obj = Objective(sum(freight_cost * distances[ori][dest] * variables[ori][dest] for ori in supply for dest in demand), direction="min") # We can print the objective and constraints print(obj) print("") for const in constraints: print(const) print("") # Put everything together in a Model model = Model() model.add(constraints) # Variables are added implicitly model.objective = obj # Optimize and print the solution status = model.optimize() print("Status:", status) print("Objective value:", model.objective.value) print("") for var in model.variables: print(var.name, ":", var.primal)
def result(): if request.method == 'POST': fields = [k for k in request.form] values = [request.form[k] for k in request.form] data = dict(zip(fields, values)) animal_name = data['animal'] animal_type = data['animal_type'] weight = data['weight'] ingredients = { k: v for k, v in data.items() if k != 'animal' and k != 'animal_type' and k != 'weight' } selected_ingredients = [*ingredients] print(selected_ingredients) ################################################ variable_objects = [] # stores all the contraints for the formulation """The feed size is the amount in kilogram (kg) the buyer wants to get from the feed formulator, this should be collected from the client side""" feed_size = weight animal_selected = animal_name ################################# selected_animal_stage = animal_type variable_objects = [] # stores all the contraints for the formulation variable_sum = None for i in range(1, len(selected_ingredients) + 1): ing = Variable('x{0}'.format(i), lb=0) if i == 1: variable_sum = ing elif i > 1: variable_sum += ing variable_objects.append(ing) print("THE VARIABLE SUM FOR THE CONSTRAINT =>>>>>", variable_sum) #the next step is to build the constraints for the formulation #we will build the contraints using the value of the ingredients respective nutrients compositions for the the particular animal maximum and minimum nutrient value #let's build the first contraint for the formulation #but before then, the demand reqirement will be the variable_sum, so all we need to do is to assign the variable_sum to the first contraint # contraint_sum = None #this should be constants to solve the formulation #do not change c1 = Constraint(variable_sum, lb=feed_size) # c2 = Constraint(variable_sum,ub = feed_size ) contraints_list = [] #append the fisrt two constraints into the contraints_list. contraints_list.append(c1) # contraints_list.append(c2) # the temp sum to hold the temporary sum of all the varible for the formulation temp_var_sum = None # print(animal_db[animal_selected][selected_animal_stage]) # if the user selects finisher broiler #This will return the keys in the finisher's feed contraints # This will return the keys in the finisher's feed contraints for nutrient in animal_db[animal_selected][selected_animal_stage]: """now we will iterate through the returned nutrient compositions for the finisher broiler""" for bound in animal_db[animal_selected][selected_animal_stage][ nutrient]: count = 0 # print("BOUND=>",bound) for ing_name in selected_ingredients: # print("\nIngredient ====>",ing_name,"\n") if count == 0: # print("\n\n--------------Another contraints goes from here-----------------------------") if nutrient != "Energy": temp_var_sum = ( ingredient_db[ing_name]["ing"][nutrient] / 100) * variable_objects[count] # print(temp_var_sum,end=" ") count = count + 1 else: temp_var_sum = ingredient_db[ing_name]["ing"][ nutrient] * variable_objects[count] # print(temp_var_sum,end=" ") count = count + 1 # print(count) elif count > 0: # print("\n\n--------------Another contraints goes from here-----------------------------") if nutrient != "Energy": temp_var_sum += ( ingredient_db[ing_name]["ing"][nutrient] / 100) * variable_objects[count] # print(temp_var_sum,end=" ") count = count + 1 else: temp_var_sum += ingredient_db[ing_name]["ing"][ nutrient] * variable_objects[count] # print(temp_var_sum,end=" ") count = count + 1 ############################Then we build the contraints from here after the sum of the constraints has been generated############################## # print("\n\n--------------Another contraints goes from here-----------------------------") # print("NUTRIENT ===> ",nutrient) # print(temp_var_sum, end=" ") # print("BOUND=>",bound, end=" ") # print("=",animal_db[animal_selected][selected_animal_stage][nutrient][bound]) if bound == "Min": contraints_list.append( Constraint(temp_var_sum, lb=animal_db[animal_selected] [selected_animal_stage][nutrient][bound])) print( temp_var_sum, ">=", animal_db[animal_selected] [selected_animal_stage][nutrient][bound]) elif bound == "Max": contraints_list.append( Constraint(temp_var_sum, ub=animal_db[animal_selected] [selected_animal_stage][nutrient][bound])) print( temp_var_sum, "<=", animal_db[animal_selected] [selected_animal_stage][nutrient][bound]) elif bound == "Equal": contraints_list.append( Constraint(temp_var_sum, lb=animal_db[animal_selected] [selected_animal_stage][nutrient][bound])) contraints_list.append( Constraint(temp_var_sum, ub=animal_db[animal_selected] [selected_animal_stage][nutrient][bound])) print( temp_var_sum, ">=", animal_db[animal_selected] [selected_animal_stage][nutrient][bound]) print( temp_var_sum, "<=", animal_db[animal_selected] [selected_animal_stage][nutrient][bound]) # all_const+=temp_var_sum #################################################################################################################################################### print("\nCONTRAINTS===>", contraints_list, end="\n\n\n") #constructing the object function from here objective_sum = None for i in range(0, len(selected_ingredients)): if i == 0: objective_sum = ingredient_db[ selected_ingredients[i]]["Price"] * variable_objects[i] elif i > 0: objective_sum += ingredient_db[ selected_ingredients[i]]["Price"] * variable_objects[i] print(objective_sum) print("OBJECTIVE FUNCTION ====> ", objective_sum, end="\n\n\n\n") obj = Objective(objective_sum, direction='min') # Variables, constraints and objectives are combined in a Model object, which can subsequently be optimized. model = Model(name='Simple model') model.objective = obj model.add(contraints_list) status = model.optimize() print("status:", status) print("objective value:", model.objective.value) print( "---------------------------------------------------------------------" ) variable_quantity = model.variables objValue = round(model.objective.value, 2) variables = [] for a, n in variable_quantity.items(): value = a, round(n.primal, 2) variables.append(value) price = [] for i in selected_ingredients: value = i, ingredient_db[i]["Price"] price.append(value) collection = dict(zip(variables, price)) return render_template("result.html", collection=collection, animal_type=animal_type, objValue=objValue)
def result(): if request.method == 'POST': result = request.form fields = [k for k in request.form] values = [request.form[k] for k in request.form] data = dict(zip(fields, values)) animal_name = data['animal'] animal_type = data['animal_type'] weight = data['weight'] selected_ingredients = {k: v for k, v in data.items() if k != 'animal' and k != 'animal_type' and k != 'weight'} ingredient_names = [*selected_ingredients] # for k in ingredient_names: # ration = INGREDIENT_DB[k] # print(ration) # Computation starts here--- # animal ration(nutrient requirement) animal_ration = ANIMAL_FEED_REQUIREMENT_DB[animal_type] # Define variables # variables = {} # variable_object = {} # for i in range(1, len(ingredient_names)+1): # variable_object[ingredient_names[i-1]] = 'x'+str(i) # for ration in animal_ration: # variables[ration] = {} # for k, v in variable_object.items(): # for name in ingredient_names: # var = Variable(v, lb=0) # variables[ration][name] = var variables = {} for ration in animal_ration: variables[ration] = {} for name in ingredient_names: var = Variable("{}".format(name), lb=0) variables[ration][name] = var print(variables) print(len(variables)) # Get nutrient level of feed ingredients # for name in ingredient_names: # for ration in animal_ration: # # if (INGREDIENT_DB[name] != ration): # # a.append(animal_ration[ration]) # # else: # try: # a.append(INGREDIENT_DB[name][ration]) # except Exception as e: # print(e) # print(a) # Define constraints constraints = [] for ration in animal_ration: try: const = Constraint( sum((INGREDIENT_DB[name][ration]/100) * variables[name][ration] if ration in INGREDIENT_DB[name] else animal_ration[ration] * variables[name][ration] for name in ingredient_names ), lb=animal_ration[ration] ) # print(const) constraints.append(const) except Exception as e: print(e) # print(len(constraints)) {{ ingredient_db[selected_ingredients[i]]["Price"] }} {% for i in range( 0, lengthOfIngredients): %} # for name in ingredient_names: # print(name) # print("-" * 10) # for k, v in variable_object.items(): # print(v) # Objective function for ration in animal_ration: obj = Objective( sum(INGREDIENT_PRICE[name] * variables[name][ration] for name in ingredient_names), direction='min' ) # Objective( 58*x1+150*x2+60*x3+15*x4+50*x5+90*x6+700*x7+1300*x8+550*x9) # print(obj) # Solve model = Model() model.objective = obj model.add(constraints) status = model.optimize() print("status:", status) print("objective value:", model.objective.value) print("-------------") for var_name , var in model.variables.items(): print(var_name, "=", var.primal) # result = model.objective.value return render_template("result.html", animal_type = animal_type)
import numpy as np from optlang import Model, Variable, Constraint, Objective # All the (symbolic) variables are declared, with a name and optionally a lower # and/or upper bound. x = np.array([Variable('x{}'.format(i), lb=0) for i in range(1, 4)]) bounds = [100, 600, 300] A = np.array([[1, 1, 1], [10, 4, 5], [2, 2, 6]]) w = np.array([10, 6, 4]) obj = Objective(w.dot(x), direction='max') c = np.array([Constraint(row, ub=bound) for row, bound in zip(A.dot(x), bounds)]) model = Model(name='Numpy model') model.objective = obj model.add(c) status = model.optimize() print("status:", model.status) print("objective value:", model.objective.value) print("----------") for var_name, var in model.variables.iteritems(): print(var_name, "=", var.primal)