def createConstraint(list_of_parameter, constraint_num, score=None, variable_list_y=None): """ Constructeur de contraintes Args: list_of_parameter : listes des paramètres (0.4 * x1, 0.6 * x2 ect...) constraint_num: numéro de la contrainte score: forme de la contrainte (avec ou sans score) variable_list_y: liste des variables de score (y1 = fa) Return: la contrainte """ list_expr = [] for t in list_of_parameter: expr = t[0]* t[1] list_expr.append(expr) expr = list_expr[0] for exp in list_expr[1:]: expr += exp #Construit la contrainte en fonction du mode avec ou sans score if score != None: constraint = Constraint(expr, name=f'c{constraint_num+1}', lb = score, ub = score) else: constraint = Constraint(expr-variable_list_y, name=f'c{constraint_num+1}', lb = 0, ub = 0) return constraint
def add_constraint(self, constr_id, lhs, sense='=', rhs=0, update=True): """ Add a constraint to the current problem. Arguments: constr_id (str): constraint identifier lhs (dict): variables and respective coefficients sense (str): constraint sense (any of: '<', '=', '>'; default '=') rhs (float): right-hand side of equation (default: 0) update (bool): update problem immediately (default: True) """ if constr_id in self.constr_ids: self.problem.remove(constr_id) if sense == '=': constr = Constraint(Zero, lb=rhs, ub=rhs, name=constr_id) elif sense == '>': constr = Constraint(Zero, lb=rhs, name=constr_id) elif sense == '<': constr = Constraint(Zero, ub=rhs, name=constr_id) else: raise RuntimeError(f"Invalid constraint direction: {sense}") self.problem.add(constr) self.constr_ids.append(constr_id) expr = { self.problem.variables[r_id]: coeff for r_id, coeff in lhs.items() if coeff } self.problem.constraints[constr_id].set_linear_coefficients(expr) if update: self.problem.update()
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 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 _encode_dynamics(A, B, C, var_lists, store, t): rhses = [ row_to_smt(zip([a, b, c], var_lists), store, t) for a, b, c in zip(A, B, C) ] lhses = [store[v, t + 1][0] for v in var_lists[0]] yield from ((Constraint(lhs - rhs, lb=0, ub=0), (lhs, rhs)) for lhs, rhs in zip(lhses, rhses))
def encode_lineq(psi, s, t, within_or=False): x = sum(float(term.coeff) * s[(term.id, t)][0] for term in psi.terms) if not within_or: if psi.op == "=": lb = ub = psi.const elif psi.op in ("<", "<="): lb, ub = None, psi.const elif psi.op in (">", ">="): lb, ub = psi.const, None yield Constraint(x, lb=lb, ub=ub), psi else: z_phi = z((psi, t)) s[psi, t, 'or'] = z_phi x = x - psi.const if psi.op in (">", ">=") else psi.const - x yield Constraint(x - M * z_phi + eps, ub=0), psi yield Constraint(-x - M * (1 - z_phi) + eps, ub=0), psi
def encode_op(phi: "SL", s, t, *, k: Kind, isor: bool): for psi in phi.args: yield from encode(psi, s, t) r_var, bool_vars = s[phi] bool_vars = dict(bool_vars) # At most one of the bool vars is active (chosen var) constr = Constraint(sum(bool_vars.values()), ub=1, lb=1) yield constr, k[1] # For each variable comput r and assert rel to psi r elems = [s[psi][0] for psi in phi.args] for psi, e in zip(phi.args, elems): if isor: yield Constraint(e - r_var, ub=0), k[0] else: yield Constraint(r_var - e, ub=0), k[0] yield Constraint(e - (1 - bool_vars[psi]) * M - r_var, ub=0), phi yield Constraint(e + M * (1 - bool_vars[psi]) - r_var, lb=0), phi
def createScoreConstraint(df_score, variable_list_y, constraint_num): """ Constructeur de contraintes de score (égalité et inégalité entre les différents score de produits) Args: df_score : la colonne des score variable_list_y: liste de variables correspondant au score (y1 = fa) constraint_num: Numéro de la contrainte variable_list_y: liste des variables de score Return: la liste des contraintes portant sur les scores """ scoreContraints = [] for i in range(len(df_score)-1): if df_score.iloc[i] != df_score.iloc[i+1]: scoreContraints.append(Constraint(variable_list_y[i] - variable_list_y[i+1], name=f'c{constraint_num+i+1}', lb = 0.1)) else: scoreContraints.append(Constraint(variable_list_y[i] - variable_list_y[i+1], name=f'c{constraint_num+i+1}', lb = 0, ub = 0)) return scoreContraints
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
def make_constraints(S, variables): #Creating the constraints, one per compound: constraints = [] for row in S: constraint_sum = 0 for i in range(len(row)): constraint_sum += row[i] * variables[i] c = Constraint(constraint_sum, lb=0, ub=0) constraints.append(c) return constraints
def encode_lineq(psi, s, t): x = sum(float(term.coeff) * s[(term.id, t)][0] for term in psi.terms) y = s[psi >> t][0] if psi.op in (">", ">="): expr = x - y elif psi.op in ("<", "<="): expr = x + y else: raise NotImplementedError constr = Constraint(expr, ub=psi.const, lb=psi.const) yield constr, psi
def encode_or(phi, s, t, within_or=False): if within_or: raise NotImplementedError # Shallow encoding of or constraint # For at least one of childs to be satisified for psi in phi.args: yield from encode(psi, s, t, within_or=True) elems = [s[psi, t, 'or'] for psi in phi.args] yield Constraint(sum(elems), lb=0.5), K.OR_TOTAL
def constrained_optimzation(objective_function, *variables, **constraints): # Objective function obj = Objective(objective_function, direction='max') # Symbolic variables variables = [] for i in range(len(variables)): print('Variable {num}: '.format(i) + str(variables[i])) variable[i] = Variable(variables[i], lb=0) for key, value in constraints.items(): print(key, value) # Constraints constraints = [] for i in range(len(constraints)): print('Constraint {num}: '.format(i) + str(constraints[i])) constraint[i] = Constraint(constraints[i], lb=0)
def optimize_irrigated_area(self, zone) -> Dict: """Apply Linear Programming to naively optimize irrigated area. Occurs at start of season. Parameters ---------- * zone : FarmZone object, representing a farm or a farming zone. """ calc = [] areas = [] constraints = [] zone_ws = zone.water_sources total_avail_water = zone.avail_allocation field_areas = {} for f in zone.fields: area_to_consider = f.total_area_ha did = f"{f.name}__".replace(" ", "_") naive_crop_income = f.crop.estimate_income_per_ha() naive_req_water = f.crop.water_use_ML_per_ha app_cost_per_ML = self.ML_water_application_cost(zone, f, naive_req_water) pos_field_area = [w.allocation / naive_req_water for ws_name, w in zone_ws.items() ] pos_field_area = min(sum(pos_field_area), area_to_consider) field_areas[f.name] = { ws_name: Variable(f"{did}{ws_name}", lb=0, ub=min(w.allocation / naive_req_water, area_to_consider)) for ws_name, w in zone_ws.items() } # total_pump_cost = sum([ws.pump.maintenance_cost(year_step) for ws in zone_ws]) profits = [field_areas[f.name][ws_name] * (naive_crop_income - app_cost_per_ML[ws_name]) for ws_name in zone_ws ] calc += profits curr_field_areas = list(field_areas[f.name].values()) areas += curr_field_areas # Total irrigated area cannot be greater than field area # or area possible with available water constraints += [ Constraint(sum(curr_field_areas), lb=0.0, ub=pos_field_area) ] # End for # for ws_name in zone_ws: # total_f_ws = 0 # for f in zone.fields: # total_f_ws += field_areas[f.name][ws_name] # # End for # # End for # constraints += [Constraint(total_f_ws, # lb=0.0, # ub=zone.total_area_ha)] constraints += [Constraint(sum(areas), lb=0.0, ub=zone.total_area_ha)] # Generate appropriate OptLang model model = Model.clone(self.opt_model) model.objective = Objective(sum(calc), direction='max') model.add(constraints) model.optimize() if model.status != 'optimal': raise RuntimeError("Could not optimize!") return model.primal_values
def encode_neg(phi, s, t): yield Constraint(s[phi][0] + s[phi.arg][0], lb=0, ub=0), K.NEG yield from encode(phi.arg, s, t)
# Define variables variables = {} for origin in supply: variables[origin] = {} for destination in demand: # Construct a variable with a name, bounds and type var = Variable(name="{}_to_{}".format(origin, destination), lb=0, type="integer") variables[origin][destination] = var # Define constraints constraints = [] for origin in supply: const = Constraint(sum(variables[origin].values()), ub=supply[origin], name="{}_supply".format(origin)) 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("")
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)
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 optimization_problem(self): """This method is to build the mathematical optimization problem for the generator""" print('Building the problem - Please wait') print('Variables') # Parameters abbreviation N = self.Horizon efficiency = self.Efficiency power = self.Power energy = self.Energy mode = self.N_mode alpha = self.Startup_cold_time beta = self.Minimum_downtime price_elec = self.Commodity_Price.electricity_price price_carbon = self.Commodity_Price.carbon_price price_fuel = self.Commodity_Price.fuel_price price_fossil = self.Commodity_Price.fossil_price # Variable Registration # ----------------------------------------------------------------------------------- model = Model(name=self.Name) X = [[]]*mode # list of lists, representing state variables for each mode of operation S = [Variable(name='start_' + str(t), type='binary') for t in range(N)] F = [Variable(name='shutdown_' + str(t), type='binary') for t in range(N)] for m in range(mode): X[m] = [Variable(name='state_mode_' + str(m) + '_' + str(t), type='binary') for t in range(N)] for t in range(alpha): X[m][t].set_bounds(0, 0) print('Constraints') # Constraints Registration # ----------------------------------------------------------------------------------- # ctr_initial_states = [[]]*mode ctr_unique_mode = [[]]*N ctr_start_shut = [[]]*N ctr_init_state = [[]]*mode ctr_start_01 = [[]]*(N-alpha-1) ctr_start_02 = [[]]*(N-alpha) # Initial States Constraints for m in range(mode): ctr_init_state[m] = [[]]*(alpha+1) for t in range(alpha+1): ctr_init_state[m][t] = Constraint(X[m][t], lb=0, ub=0, name='ctr_initial_states_m_' + str(m) + str(t)) # Listed constraints for t in range(N): # 1.1 Unique mode constraint: ctr_unique_mode[t] = Constraint(sum(X[m][t] for m in range(mode)), ub=1, name='ctr_unique_mode_' + str(t)) # 1.2 Startup - shutdown constraint: ctr_start_shut[t] = Constraint(S[t] + F[t], ub=1, name='ctr_start_shut_' + str(t)) for i, t in enumerate(range(alpha, N-1)): # 2, 21 # 1.3 Startup - shutdown constraint 2 : ctr_start_01[i] = Constraint(S[t - alpha] - F[t] - sum(X[m][t+1] - X[m][t] for m in range(mode)), lb=0, ub=0, name='ctr_start_01_' + str(t)) # 1.4 Minimum startup time : ctr_start_02[i] = Constraint(sum(sum(X[m][t - k] for k in range(1, alpha)) for m in range(mode)) + alpha*S[t-alpha], ub=alpha, name='ctr_start_02_' + str(t)) ctr_start_02[N-alpha-1] = Constraint(sum(sum(X[m][N - 1 - k] for k in range(1, alpha)) for m in range(mode)) + alpha*S[N - 1 - alpha], ub=alpha, name='ctr_start_02_' + str(N - 1)) # 1.5 Capacity Factor constraint : will be done below # 1.6 Minimum shutdown time : will be done below # Objective function : # ----------------------------------------------------------------------------------- print('Objective') obj_list = [[]]*(mode+1) obj_func = Objective(0, direction='max') obj_coeff_dict = {} obj_coeff_start = dict(zip(S, [-self.Power[0]*(self.Startup_dep_cost + self.Startup_fuel*price_fossil[t]) for t in range(N)])) obj_coeff_dict.update(obj_coeff_start) for m in range(mode): # obj_list[m] = Objective(energy[m]*sum(price_elec[t]*X[m][t] - price_fuel[m].values[t]*X[m][t] - price_carbon[t]*self.Emission_Intensity[m]*X[m][t] # - X[m][t]*self.Cost_var_OM for t in range(N)), direction='max') obj_coeff_rev = dict(zip(X[m], [energy[m]*(price_elec[t] - price_fuel[m].values[t] - price_carbon[t]*self.Emission_Intensity[m] - self.Cost_var_OM) for t in range(N)])) obj_coeff_dict.update(obj_coeff_rev) # for elem in obj_list: # # obj_func += elem.expression # Add variables and constraints to the model : var_list = [] cons_list = [] for m in range(mode): var_list.extend(X[m]) cons_list.extend(ctr_init_state[m]) var_list.extend(S) var_list.extend(F) cons_list.extend(ctr_unique_mode) cons_list.extend(ctr_start_shut) cons_list.extend(ctr_start_01) cons_list.extend(ctr_start_02) # 1.6 Minimum shutdown time : if self.Minimum_downtime is not None: ctr_min_time = [[]] * (N - beta) for i, t in enumerate(range(N - beta)): ctr_min_time[i] = Constraint( sum(sum(X[m][t + k] for k in range(1, beta + 1)) for m in range(mode)) + beta * F[t], lb=0, ub=beta, name='ctr_min_time_' + str(t)) cons_list.extend(ctr_min_time) self._cons['ctr_min_time'] = ctr_min_time model.add(var_list) # 1.5 Capacity Factor Constraint : # ------------------------------------------------------------------------------------------------ index = self.input_price.index time_interval = (index[-1] - index[0]).days if time_interval >= self.CF * 365: coeff_capacity_factor_dict = {} print('Capacity Factor Constraint Activated ') for m in range(mode): dict_tempo = dict(zip(X[m], [1]*N)) coeff_capacity_factor_dict.update(dict_tempo) ctr_capacity_factor = Constraint(0, name='ctr_capacity_factor') model.add(ctr_capacity_factor) model.constraints['ctr_capacity_factor'].ub = self.CF*365*24 ctr_capacity_factor.set_linear_coefficients(coeff_capacity_factor_dict) self._cons['ctr_capacity_factor'] = ctr_capacity_factor # 1.6 Minimum shutdown time : # for i, t in enumerate(range(N-beta)): # ctr_min_time[i] = Constraint(sum(sum(X[m][t + k] for k in range(1, beta + 1)) for m in range(mode)) + beta * F[t], # lb=0, ub=beta, name='ctr_min_time_' + str(t)) # ctr_min_time[i] = Constraint(0, lb=0, name='ctr_min_time_' + str(t)) # model.add(ctr_min_time[i]) # model.constraints['ctr_min_time_' + str(t)].ub = beta # dict_tempo = {F[t]: beta} # # for m in range(mode): # # dict_tempo_1 = dict(zip(X[m][t:(t+beta+1)], [1]*beta)) # dict_tempo.update(dict_tempo_1) # # ctr_min_time[i].set_linear_coefficients(dict_tempo) # Add other constraints and objective function # ------------------------------------------------------------------------------------------------ model.add(cons_list) model.objective = obj_func obj_func.set_linear_coefficients(obj_coeff_dict) self.optim_model = model for m in range(mode): self._var['state_mode_' + str(m)] = X[m] self._var['Start'] = S self._var['Shut'] = F self._cons.update({'ctr_init_state': ctr_init_state, 'ctr_unique_mode': ctr_unique_mode, 'ctr_start_shut': ctr_start_shut, 'ctr_start_01': ctr_start_01, 'ctr_start_02': ctr_start_02}) print('Object Creation Finished')
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import six from optlang import Model, Variable, Constraint, Objective x1 = Variable('x1', lb=0) x2 = Variable('x2', lb=0) x3 = Variable('x3', lb=0) c1 = Constraint(x1 + x2 + x3, ub=100) c2 = Constraint(10 * x1 + 4 * x2 + 5 * x3, ub=600) c3 = Constraint(2 * x1 + 2 * x2 + 6 * x3, ub=300) obj = Objective(10 * x1 + 6 * x2 + 4 * x3, direction='max') model = Model(name='Simple model') model.objective = obj model.add([c1, c2, c3]) status = model.optimize() print("status:", model.status) print("objective value:", model.objective.value) for var_name, var in six.iteritems(model.variables): print(var_name, "=", var.primal)
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)
def optimize_irrigation(self, zone, dt: object) -> tuple: """Apply Linear Programming to optimize irrigation water use. Results can be used to represent percentage mix e.g. if the field area is 100 ha, and the optimal area to be irrigated by a water source is `SW: 70 ha GW: 30 ha` and the required amount is 20mm `SW: 70 / 100 = 0.7 (irrigated area / total area, 70%) GW: 30 / 100 = 0.3 (30%)` Then the per hectare amount to be applied from each water source is calculated as: `SW = 20mm * 0.7 = 14mm GW = 20mm * 0.3 = 6mm` Parameters ---------- * zone : FarmZone * dt : datetime object, current datetime Returns --------- * Tuple : OrderedDict[str, float] : keys based on field and water source names values are hectare area Float : $/ML cost of applying water """ model = self.opt_model areas = [] profit = [] app_cost = OrderedDict() constraints = [] zone_ws = zone.water_sources total_irrigated_area = sum(map(lambda f: f.irrigated_area if f.irrigated_area is not None else 0.0, zone.fields)) field_area = {} possible_area = {} for f in zone.fields: f_name = f.name did = f"{f_name}__".replace(" ", "_") if f.irrigation.name == 'dryland': areas += [Variable(f"{did}{ws_name}", lb=0, ub=0) for ws_name in zone_ws] continue # End if # Disable this for now - estimated income includes variable costs # Will always incur maintenance costs and crop costs # total_pump_cost = sum([ws.pump.maintenance_cost(dt.year) for ws in zone_ws]) # total_irrig_cost = f.irrigation.maintenance_cost(dt.year) # maintenance_cost = (total_pump_cost + total_irrig_cost) # estimated gross income - variable costs per ha crop_income_per_ha = f.crop.estimate_income_per_ha() req_water_ML_ha = f.calc_required_water(dt) / ML_to_mm if req_water_ML_ha == 0.0: field_area[f_name] = { ws_name: Variable(f"{did}{ws_name}", lb=0.0, ub=0.0) for ws_name in zone_ws } else: max_ws_area = zone.possible_area_by_allocation(f) field_area[f_name] = { ws_name: Variable(f"{did}{ws_name}", lb=0, ub=max_ws_area[ws_name]) for ws_name in zone_ws } # End if # Costs to pump needed water volume from each water source app_cost_per_ML = self.ML_water_application_cost(zone, f, req_water_ML_ha) app_cost.update({ f"{did}{k}": v for k, v in app_cost_per_ML.items() }) profit += [ (crop_income_per_ha - (app_cost_per_ML[ws_name] * req_water_ML_ha) ) * field_area[f_name][ws_name] for ws_name in zone_ws ] # End for # Total irrigation area cannot be more than available area constraints += [Constraint(sum(areas), lb=0.0, ub=min(total_irrigated_area, zone.total_area_ha)) ] # 0 <= field1*sw + field2*sw + field_n*sw <= possible area to be irrigated by sw for ws_name, w in zone_ws.items(): alloc = w.allocation pos_area = zone.possible_irrigation_area(alloc) f_ws_var = [] for f in zone.fields: f_ws_var += [field_area[f.name][ws_name]] # End for constraints += [Constraint(sum(f_ws_var), lb=0.0, ub=pos_area)] # End for # Generate appropriate OptLang model model = Model.clone(self.opt_model) model.objective = Objective(sum(profit), direction='max') model.add(constraints) model.optimize() return model.primal_values, app_cost
from optlang import Model, Variable, Constraint, Objective model = Model(name='optlang model') ### Decision variables, positive (lb is lower bound) # x is real, y is interger x = Variable('x',lb=0,type='continuous') y = Variable('y',lb=0,type='integer') ### Constraints, x+2*y<=4, 5*x-y>=8 model.add([ Constraint(x+2*y, ub=4), Constraint(5*x-y, lb=8) ]) ### Objetive function to be maximixed model.objective = Objective(x+2*y-2, direction='max') ### Solve status = model.optimize() ### status can be "optimal", "infeasible", "unbounded" # or "undefined", if the solver decides there is no # optimal value, but cannot decide why print("status:", model.status) ### optimal value # (only acceptable if status is "optimal") print("objective value:", model.objective.value) ### print the value of each decision variable # for the optimal solution
# Constraints constraints = [] for i in range(len(constraints)): print('Constraint {num}: '.format(i) + str(constraints[i])) constraint[i] = Constraint(constraints[i], lb=0) constrained_optimzation(P**2, P, constraint=2) # All the (symbolic) variables are declared, with a name and optionally a lower and/or upper bound. x1 = Variable('x1', lb=0) x2 = Variable('x2', lb=0) # A constraint is constructed from an expression of variables and a lower and/or upper bound (lb and ub). c1 = Constraint(P=1 - Q) c2 = Constraint(10 * x1 + 4 * x2 + 5 * x3, ub=600) c3 = Constraint(2 * x1 + 2 * x2 + 6 * x3, ub=300) # An objective can be formulated obj = Objective(10 * x1 + 6 * x2 + 4 * x3, 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]) status = model.optimize() print("status:", model.status) print("objective value:", model.objective.value)