def game_to_milp(g: Game, robust=True, counter_examples=None): # TODO: implement counter_example encoding if not counter_examples: counter_examples = [{}] model = Model() store = keydefaultdict(lambda x: rob_encode.z(x, g)) # Add counter examples to store for i, ce in enumerate(counter_examples): store.update(counter_example_store(g, ce, i)) # Encode each scenario. scenarios = [ create_scenario(g, i) for i, ce in enumerate(counter_examples) ] constraints, objs = zip(*(encode_game(g2, store) for g2 in scenarios)) # Objective is to maximize the minimum robustness of the scenarios. if len(objs) > 1: obj = stl.andf(*objs) constraints = chain( rob_encode.encode(obj, store, 0), fn.cat(constraints)) else: obj = objs[0] constraints = fn.cat(constraints) for i, (constr, kind) in enumerate(constraints): if constr is True: continue add_constr(model, constr, kind, i) # TODO: support alternative objective functions J = store[obj][0] if isinstance(store[obj], tuple) else store[obj] model.objective = Objective(J, direction='max') return model, store
def game_to_milp(g: Game, robust=True, counter_examples=None): # TODO: implement counter_example encoding if not counter_examples: counter_examples = [{}] model = Model() store = keydefaultdict(lambda x: rob_encode.z(x, g)) # Add counter examples to store for i, ce in enumerate(counter_examples): store.update(counter_example_store(g, ce, i)) # Encode each scenario. scenarios = [ create_scenario(g, i) for i, ce in enumerate(counter_examples) ] constraints, objs = zip(*(encode_game(g2, store) for g2 in scenarios)) # Objective is to maximize the minimum robustness of the scenarios. if len(objs) > 1: obj = stl.andf(*objs) constraints = chain(rob_encode.encode(obj, store, 0), fn.cat(constraints)) else: obj = objs[0] constraints = fn.cat(constraints) for i, (constr, kind) in enumerate(constraints): if constr is True: continue add_constr(model, constr, kind, i) # TODO: support alternative objective functions J = store[obj][0] if isinstance(store[obj], tuple) else store[obj] model.objective = Objective(J, direction='max') return model, store
def __init__(self, model=None): Solver.__init__(self) self.problem = Model() self.parameter_mapping = { Parameter.TIME_LIMIT: self.problem.configuration.timeout, Parameter.FEASIBILITY_TOL: self.problem.configuration.tolerances.feasibility, Parameter.OPTIMALITY_TOL: self.problem.configuration.tolerances.optimality, Parameter.INT_FEASIBILITY_TOL: self.problem.configuration.tolerances.integrality, } self.set_parameters(default_parameters) self.set_logging(False) if model: self.build_problem(model)
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 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 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 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)
class OptLangSolver(Solver): """ Implements the gurobi solver interface. """ def __init__(self, model=None): Solver.__init__(self) self.problem = Model() self.parameter_mapping = { Parameter.TIME_LIMIT: self.problem.configuration.timeout, Parameter.FEASIBILITY_TOL: self.problem.configuration.tolerances.feasibility, Parameter.OPTIMALITY_TOL: self.problem.configuration.tolerances.optimality, Parameter.INT_FEASIBILITY_TOL: self.problem.configuration.tolerances.integrality, } self.set_parameters(default_parameters) self.set_logging(False) if model: self.build_problem(model) def add_variable(self, var_id, lb=-inf, ub=inf, vartype=VarType.CONTINUOUS, update=True): """ Add a variable to the current problem. Arguments: var_id (str): variable identifier lb (float): lower bound ub (float): upper bound vartype (VarType): variable type (default: CONTINUOUS) update (bool): update problem immediately (default: True) """ if var_id in self.var_ids: var = self.problem.variables[var_id] var.lb = lb var.ub = ub var.type = vartype.value else: var = Variable(var_id, lb=lb, ub=ub, type=vartype.value) self.problem.add(var) self.var_ids.append(var_id) if update: self.problem.update() 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 remove_variable(self, var_id): """ Remove a variable from the current problem. Arguments: var_id (str): variable identifier """ self.remove_variables([var_id]) def remove_variables(self, var_ids): """ Remove variables from the current problem. Arguments: var_ids (list): variable identifiers """ for var_id in var_ids: if var_id in self.var_ids: self.problem.remove(var_id) self.var_ids.remove(var_id) def remove_constraint(self, constr_id): """ Remove a constraint from the current problem. Arguments: constr_id (str): constraint identifier """ self.remove_constraints([constr_id]) def remove_constraints(self, constr_ids): """ Remove constraints from the current problem. Arguments: constr_ids (list): constraint identifiers """ for constr_id in constr_ids: if constr_id in self.constr_ids: self.problem.remove(constr_id) self.constr_ids.remove(constr_id) def set_objective(self, linear=None, quadratic=None, minimize=True): """ Set a predefined objective for this problem. Args: linear (dict): linear coefficients (optional) quadratic (dict): quadratic coefficients (optional) minimize (bool): solve a minimization problem (default: True) Notes: Setting the objective is optional. It can also be passed directly when calling **solve**. """ if linear is None: linear = {} if quadratic is None: quadratic = {} if linear and not quadratic: objective = {} if isinstance(linear, str): objective = {self.problem.variables[linear]: 1} if linear not in self.var_ids: warn( f"Objective variable not previously declared: {linear}" ) else: for r_id, val in linear.items(): if r_id not in self.var_ids: warn( f"Objective variable not previously declared: {r_id}" ) elif val != 0: objective[self.problem.variables[r_id]] = val self.problem.objective = Objective( Zero, direction=('min' if minimize else 'max'), sloppy=True) self.problem.objective.set_linear_coefficients(objective) else: objective = [] for r_id, val in linear.items(): if r_id not in self.var_ids: warn(f"Objective variable not previously declared: {r_id}") elif val != 0: objective.append(val * self.problem.variables[r_id]) for (r_id1, r_id2), val in quadratic.items(): if r_id1 not in self.var_ids: warn( f"Objective variable not previously declared: {r_id1}") elif r_id2 not in self.var_ids: warn( f"Objective variable not previously declared: {r_id2}") elif val != 0: objective.append(val * self.problem.variables[r_id1] * self.problem.variables[r_id2]) objective_expr = add(objective) self.problem.objective = Objective( objective_expr, direction=('min' if minimize else 'max'), sloppy=True) def solve(self, linear=None, quadratic=None, minimize=None, model=None, constraints=None, get_values=True, shadow_prices=False, reduced_costs=False, pool_size=0, pool_gap=None): """ Solve the optimization problem. Arguments: linear (str or dict): linear coefficients (or a single variable to optimize) quadratic (dict): quadratic objective (optional) minimize (bool): solve a minimization problem (default: True) model (CBModel): model (optional, leave blank to reuse previous model structure) constraints (dict): additional constraints (optional) get_values (bool or list): set to false for speedup if you only care about the objective (default: True) shadow_prices (bool): return shadow prices if available (default: False) reduced_costs (bool): return reduced costs if available (default: False) pool_size (int): calculate solution pool of given size (only for MILP problems) pool_gap (float): maximum relative gap for solutions in pool (optional) Returns: Solution: solution """ if model: self.build_problem(model) problem = self.problem if constraints: old_constraints = {} for r_id, x in constraints.items(): lb, ub = x if isinstance(x, tuple) else (x, x) if r_id in self.var_ids: lpvar = problem.variables[r_id] old_constraints[r_id] = (lpvar.lb, lpvar.ub) lpvar.lb, lpvar.ub = lb, ub else: warn( f"Constrained variable '{r_id}' not previously declared" ) problem.update() self.set_objective(linear, quadratic, minimize) # run the optimization if pool_size > 0: raise RuntimeError( "OptLang interface does not support solution pools.") problem.optimize() status = status_mapping.get(problem.status, Status.UNKNOWN) message = str(problem.status) if status == Status.OPTIMAL: fobj = problem.objective.value values, s_prices, r_costs = None, None, None if get_values: values = dict(problem.primal_values) if isinstance(get_values, Iterable): values = {x: values[x] for x in get_values} if shadow_prices: s_prices = dict(problem.shadow_prices) if reduced_costs: r_costs = dict(problem.reduced_costs) solution = Solution(status, message, fobj, values, s_prices, r_costs) else: solution = Solution(status, message) # restore values of temporary constraints if constraints: for r_id, (lb, ub) in old_constraints.items(): lpvar = problem.variables[r_id] lpvar.lb, lpvar.ub = lb, ub problem.update() return solution def set_parameter(self, parameter, value): """ Set a parameter value for this optimization problem Arguments: parameter (Parameter): parameter type value (float): parameter value """ if parameter in self.parameter_mapping: self.parameter_mapping[parameter] = value else: raise RuntimeError('Parameter unknown (or not yet supported).') def set_logging(self, enabled=False): """ Enable or disable log output: Arguments: enabled (bool): turn logging on (default: False) """ self.problem.configuration.verbosity = 3 if enabled else 0 def write_to_file(self, filename): """ Write problem to file: Arguments: filename (str): file path """ with open(filename, "w") as f: f.write(self.problem.to_lp())
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
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 __init__(self): self.opt_model = Model(name='Farm Decision model')
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)
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
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 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)
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
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) print("----------") for var_name, var in model.variables.iteritems(): print(var_name, "=", var.primal)