def solve(self): print("Solving") solver_start = timer() opt = pyo.SolverFactory('cbc') # Select solver solver_manager = pyo.SolverManagerFactory('neos') results = solver_manager.solve(self.model, opt=opt) solver_end = timer() if (results.solver.status == SolverStatus.ok) and (results.solver.termination_condition == TerminationCondition.optimal): print("This is feasible and optimal") print(solver_end - solver_start) elif results.solver.termination_condition == TerminationCondition.infeasible: print ("Do something about it? or exit?") else: # something else is wrong #print (str(results.solver)) print("store " + str(self.id) + " solved") #print(self.bur_promo) #results.write(num=1) #self.gen_results_list #pprint.pprint(var_values) #pprint.pprint(var_coefs) return results
def solve(self, solver_name, options=None, solver_path=None, local=True): if solver_path is not None: solver = pe.SolverFactory(solver_name, executable=solver_path) else: solver = pe.SolverFactory(solver_name) # TODO remove - too similar to alstom if options is not None: for key, value in options.items(): solver.options[key] = value if local: solver_results = solver.solve(self.model, tee=True) else: solver_manager = pe.SolverManagerFactory("neos") solver_results = solver_manager.solve(self.model, opt=solver) results = [{ "Case": case, "Session": session, "Session Date": self.model.SESSION_DATES[session], "Case Deadline": self.model.CASE_DEADLINES[case], "Days before deadline": self.model.CASE_DEADLINES[case] - self.model.SESSION_DATES[session], "Start": self.model.CASE_START_TIME[case, session](), "Assignment": self.model.SESSION_ASSIGNED[case, session]() } for (case, session) in self.model.TASKS]
def solve(self, model, **options): assert (isinstance(model, pe.Model) or isinstance(model, pe.SimpleBlock) ), "The Pyomo solver '%s' cannot solve a model of type %s" % ( self.name, str(type(model))) if self.config['email'] is not None: os.environ['NEOS_EMAIL'] = self.config['email'] assert ( 'NEOS_EMAIL' in os.environ ), "The NEOS solver requires an email. Please specify the NEOS_EMAIL environment variable." solver_manager = pe.SolverManagerFactory('neos') try: tmp_config = self.config() tmp_options = copy.copy(self.solver_options) tmp_options.update( self._update_config(options, config=tmp_config, validate_options=False)) results = solver_manager.solve(model, opt=self.name, tee=tmp_config.tee, options=tmp_options) return results except pyomo.opt.parallel.manager.ActionManagerError as err: raise RuntimeError(str(err)) from None
def globalopt(self, model): ''' Perform global optimization ''' if self.solver == 'gams': # for gams solver_manager = pe.SolverFactory('gams') options = ['option minlp = baron, optcr = 0.0001;'] results = solver_manager.solve(model, keepfiles=True, add_options=options, tmpdir='.', symbolic_solver_labels=True, warmstart=True) else: solver_manager = pe.SolverManagerFactory( 'neos') # Solve in neos server if self.prob.binvar: options = ['couenne'] # for minlp opt else: options = ['lgo'] # for nlp opt results = solver_manager.solve(model, opt=options[0]) solution = self.getsolution(model, results) return solution
def solve(self): assert self.instance is not None, 'Instance is not yet generated. You must call generate_instance(...) before you can call solve().' # Solve the instance using NEOS and CPLEX results = pyo.SolverManagerFactory('neos').solve(self.instance, opt='cplex') # Print the results results.write(num=1) # Print the optimal solution solution = pd.DataFrame() for i in self.instance.x: if self.instance.x[i].value == 1: d = { 'origin': i[0], 'destination': i[1], 'outbound_date': i[2], 'quote': self.instance.c[i] } solution = solution.append(d, ignore_index=True) solution = solution[[ 'origin', 'destination', 'outbound_date', 'quote' ]] solution.sort_values(by=['outbound_date'], inplace=True, ignore_index=True) print(solution)
def test_kestrel_plugin(self): m = pyo.ConcreteModel() m.x = pyo.Var(bounds=(0, 1), initialize=0) m.c = pyo.Constraint(expr=m.x <= 0.5) m.obj = pyo.Objective(expr=2 * m.x, sense=pyo.maximize) solver_manager = pyo.SolverManagerFactory('neos') results = solver_manager.solve(m, opt='cbc') self.assertEqual(results.solver[0].status, pyo.SolverStatus.ok) self.assertAlmostEqual(pyo.value(m.x), 0.5)
def principal( argv ): ## TP[t][m]: tiempo de procesamiento del trabajo t en la máquina m. TP = [ [1, 13, 6, 2], [10, 12, 18, 18], [17, 9, 13, 4], [12, 17, 2, 6], [11, 3, 5, 16] ] TP = [ [27, 79, 22, 93, 38], [92, 23, 93, 22, 84], [75, 66, 62, 64, 62], [94, 5, 53, 81, 10], [18, 15, 30, 94, 11], [41, 51, 34, 97, 93], [37, 2, 27, 54, 57], [58, 81, 30, 82, 81], [56, 12, 54, 11, 10], [20, 40, 77, 91, 40], [2, 59, 24, 23, 62], [39, 32, 47, 32, 49], [91, 16, 39, 26, 90], [81, 87, 66, 22, 34], [33, 78, 41, 12, 11], [14, 41, 46, 23, 81], [88, 43, 24, 34, 51], [22, 94, 23, 87, 21], [36, 1, 68, 59, 39], [65, 93, 50, 2, 27] ] ## DECLARE SOLVER, CREATE A PYOMO ABSTRACT MODEL, DECLARE LINEAR MODEL #opt = SolverFactory('cplex', executable="C:\\Program Files\\IBM\\ILOG\\CPLEX_Studio1210\\cplex\\bin\\x64_win64\\cplex") #opt = SolverFactory('glpk', executable="C:\\Users\\USUARIO1\\Desktop\\Programas\\Gusek\\GUSEK PRINCIPAL\\glpsol") # opt = SolverFactory("gurobi", solver_io="python") opt = pyo.SolverManagerFactory('neos') model = pyo.AbstractModel() create_lineal_model_tardiness( model, TP ) ## Crear una instancia del modelo y ejecutarla instance = model.create_instance() # opt.solve(instance, tee = False) opt.solve(instance, opt='cplex', tee = False) #instance.display() print_results_console( instance )
def solve_pyomo_environ(self, neos=True, solver='cplex'): """ Solve the problem using the standard environ Pyomo package Parameters ---------- neos (boolean, default:True): if True the problem is solved in neos server. Otherwise, it uses local solvers solver (str, default:'cplex'): defines the solver used to solve the optimization problem Returns ------- obj_fun (real): objective function sol (list): optimal solution of variables """ # Model m = pe.ConcreteModel() # Sets m.i = pe.Set(initialize=range(self.nvar), ordered=True) m.j = pe.Set(initialize=range(self.ncon), ordered=True) # Variables m.z = pe.Var() m.x = pe.Var(m.i, within=pe.NonNegativeReals) # Objective function def obj_rule(m): return sum(self.c[i] * m.x[i] for i in m.i) m.obj = pe.Objective(rule=obj_rule) # Constraints def con_rule(m, j): return sum(self.A[j][i] * m.x[i] for i in m.i) <= self.b[j] m.con = pe.Constraint(m.j, rule=con_rule) # Print problem m.pprint() # Solve problem if neos: res = pe.SolverManagerFactory('neos').solve( m, opt=pe.SolverFactory(solver)) else: res = pe.SolverFactory(solver).solve(m, symbolic_solver_labels=True, tee=True) print(res['Solver'][0]) # Output return round(m.obj(), 2), [round(m.x[i].value, 2) for i in m.i]
def solve_mip(self, M=10**6, lpsolver='cplex', mipsolver='ipopt'): start = time.time() self.gen_model_mip() self.m.M = M if mipsolver[0:4] == 'neos': opt = pe.SolverFactory(mipsolver[5:]) opt.options['mipgap'] = 1e-8 res = pe.SolverManagerFactory('neos').solve( self.m, opt=opt, symbolic_solver_labels=True, tee=True) else: opt = pe.SolverFactory(mipsolver) opt.options['mipgap'] = 1e-8 res = opt.solve(self.m, symbolic_solver_labels=True, tee=True) of = self.solve_ll(vector_x=[self.m.x[i].value for i in self.m.i], lpsolver=lpsolver) return of, time.time() - start
def run_solver(instance, conf, solver, neos_flag): """Method to solve a pyomo instance Parameters: instance: Pyomo unsolved instance solver(str): solver to use. Select between (glpk, cplex, gurobi, cbc et.c) solver_manager (str): serial or pyro tee(bool): if True a detailed solver output will be printed on screen options_string: options to pass to solver Returns: """ # initialize the solver / solver manager. solver_name = solver if neos_flag: solver = pe.SolverManagerFactory("neos") else: solver = pe.SolverFactory(solver_name) if solver is None: raise Exception("Solver %s is not available on this machine." % solver) if neos_flag: results = solver.solve( instance, tee=conf['tee'], symbolic_solver_labels=conf['symbolic_solver_labels'], load_solutions=False, opt=solver_name) else: results = solver.solve( instance, tee=conf['tee'], symbolic_solver_labels=conf['symbolic_solver_labels'], load_solutions=False) if results.solver.termination_condition not in ( TerminationCondition.optimal, TerminationCondition.maxTimeLimit): # something went wrong logging.warn("Solver: %s" % results.solver.termination_condition) logging.debug(results.solver) else: #logging.info("Model solved. Solver: %s, Time: %.2f, Gap: %s" % # (results.solver.termination_condition, results.solver.time, results.solution(0).gap)) instance.solutions.load_from(results) instance.obj_model1.expr() return instance, results.solver, results.solution
def _run(self, opt, constrained=True): m = _model(self.sense) with pyo.SolverManagerFactory('neos') as solver_manager: results = solver_manager.solve(m, opt=opt) expected_y = { (pyo.minimize, True): -1, (pyo.maximize, True): 1, (pyo.minimize, False): -10, (pyo.maximize, False): 10, }[self.sense, constrained] self.assertEqual(results.solver[0].status, pyo.SolverStatus.ok) if constrained: # If the solver ignores constraints, x is degenerate self.assertAlmostEqual(pyo.value(m.x), 1, delta=1e-5) self.assertAlmostEqual(pyo.value(m.obj), expected_y, delta=1e-5) self.assertAlmostEqual(pyo.value(m.y), expected_y, delta=1e-5)
def solve_reg(self, vector_ep=[10**6, 10**4, 10**2, 1, 0.1, 0.01, 0], lpsolver='cplex', nlpsolver='ipopt'): start = time.time() self.gen_model_reg() for ep in vector_ep: self.m.ep = ep if nlpsolver[0:4] == 'neos': res = pe.SolverManagerFactory('neos').solve( self.m, opt=pe.SolverFactory(nlpsolver[5:]), symbolic_solver_labels=True, tee=True) else: res = pe.SolverFactory(nlpsolver).solve( self.m, symbolic_solver_labels=True, tee=True) of = self.solve_ll(vector_x=[self.m.x[i].value for i in self.m.i], lpsolver=lpsolver) return of, time.time() - start
def principal(argv): ## TP[t][m]: tiempo de procesamiento del trabajo t en la máquina m. TP = [[1, 13, 6, 2], [10, 12, 18, 18], [17, 9, 13, 4], [12, 17, 2, 6], [11, 3, 5, 16]] dd = [20, 75, 45, 34, 41] ## DECLARE SOLVER, CREATE A PYOMO ABSTRACT MODEL, DECLARE LINEAR MODEL #opt = SolverFactory('cplex', executable="C:\\Program Files\\IBM\\ILOG\\CPLEX_Studio1210\\cplex\\bin\\x64_win64\\cplex") # opt = SolverFactory('glpk', executable="C:\\Users\\USUARIO1\\Desktop\\Programas\\Gusek\\GUSEK PRINCIPAL\\glpsol") opt = pyo.SolverManagerFactory('neos') model = pyo.AbstractModel() create_lineal_model_tardiness(model, TP, dd) ## Crear una instancia del modelo y ejecutarla instance = model.create_instance() opt.solve(instance, opt='cplex', tee=False) # opt.solve(instance, tee = False) #instance.display() print_results_console(instance)
def modelo_tardanza(TP, dd): ## DECLARE SOLVER, CREATE A PYOMO ABSTRACT MODEL, DECLARE LINEAR MODEL # opt = SolverFactory('cplex', executable="C:\\Program Files\\IBM\\ILOG\\CPLEX_Studio1210\\cplex\\bin\\x64_win64\\cplex") # opt = SolverFactory("gurobi", solver_io="python") # opt = SolverFactory('glpk', executable="C:\\Users\\USUARIO1\\Desktop\\Programas\\Gusek\\GUSEK PRINCIPAL\\glpsol") opt = pyo.SolverManagerFactory('neos') model = pyo.AbstractModel() model = create_lineal_model_tardiness(model, TP, dd) ## Crear una instancia del modelo y ejecutarla instance = model.create_instance() results = opt.solve(instance, opt='bonmin', tee=False) #instance.display() secuencia, tardanza, makespan = obtener_resultados(instance) return (secuencia, tardanza, makespan) #fed
def multistartlocalopt(self, model, xloc): ''' perform local optimization''' if self.solver == 'gams': # for gams solver_manager = pe.SolverFactory('gams') if self.prob.binvar: options = ['option minlp = dicopt;'] else: options = ['option nlp = conopt;'] else: solver_manager = pe.SolverManagerFactory('neos') # for neos if self.prob.binvar: options = ['bonmin'] # for minlp else: options = ['ipopt'] # for nlp #multistart optimization solution = [] for i in range(xloc.shape[0]): #xloc.shape[0]): for j in range(xloc.shape[1]): model.x[j].value = xloc[i, j] # provide initial points if self.solver == 'gams': # for gams results = solver_manager.solve( model, keepfiles=True, add_options=options, tmpdir='.', symbolic_solver_labels=True, warmstart=True ) #keepfiles=True, add_options = options, tmpdir = '.', symbolic_solver_labels= True) #, opt='bonmin') else: # for neos results = solver_manager.solve(model, opt=options[0], warmstart=True) allsol = self.getsolution(model, results) solution.append(allsol) return solution
def solve_ll(self, vector_x, lpsolver='cplex'): m = pe.ConcreteModel() # Sets m.i = pe.Set(initialize=range(self.nvar), ordered=True) m.j = pe.Set(initialize=range(self.ncon), ordered=True) # Variables m.y = pe.Var(m.i, within=pe.NonNegativeReals) # Objective function def obj_rule(m): return sum(self.e[i] * m.y[i] for i in m.i) m.obj = pe.Objective(rule=obj_rule) # Constraints def con1_rule(m, j): return sum(self.F[j][i] * m.y[i] for i in m.i) <= self.g[j] m.con1 = pe.Constraint(m.j, rule=con1_rule) def con2_rule(m, j): return sum(self.H[j][i] * vector_x[i] for i in m.i) + sum(self.I[j][i] * m.y[i] for i in m.i) <= self.j[j] m.con2 = pe.Constraint(m.j, rule=con2_rule) if lpsolver[0:4] == 'neos': res = pe.SolverManagerFactory('neos').solve( m, opt=pe.SolverFactory(lpsolver[5:]), symbolic_solver_labels=True, tee=True) else: res = pe.SolverFactory(lpsolver).solve(m, symbolic_solver_labels=True, tee=True) return sum(self.a[i] * vector_x[i] + self.b[i] * m.y[i].value for i in m.i)
def solve(self, solver='cbc', network=True, commit=True, outdir='results'): #Define the Model m = pe.ConcreteModel() #Define the Sets m.g = pe.Set(initialize=list(range(self.ng)), ordered=True) m.l = pe.Set(initialize=list(range(self.nl)), ordered=True) m.b = pe.Set(initialize=list(range(self.nb)), ordered=True) m.t = pe.Set(initialize=list(range(self.nt)), ordered=True) #Define Variables #Objective Function m.z = pe.Var() #Active and Reactive Power Generations m.pgg = pe.Var(m.g, m.t, within=pe.NonNegativeReals) m.qgg = pe.Var(m.g, m.t, within=pe.Reals) #Demand and Renewable Shedding m.pds = pe.Var(m.b, m.t, within=pe.Binary) m.prs = pe.Var(m.b, m.t, within=pe.NonNegativeReals) #Voltage Magnitude m.vol = pe.Var(m.b, m.t, within=pe.Reals, bounds=(self.vmin, self.vmax)) #Active and Reactive Line Flows m.pll = pe.Var(m.l, m.t, within=pe.Reals) #Active Power m.qll = pe.Var(m.l, m.t, within=pe.Reals) #Reactive Power if commit: m.u = pe.Var(m.g, m.t, within=pe.Binary) else: m.u = pe.Var(m.g, m.t, within=pe.NonNegativeReals, bounds=(0, 1)) #Objective Function def obj_rule(m): return m.z m.obj = pe.Objective(rule=obj_rule) #Definition Cost def cost_def_rule(m): if commit: return m.z == sum( self.gen['start'][g] * m.u[g, t] for g in m.g for t in m.t) - sum( self.gen['start'][g] * m.u[g, t - 1] for g in m.g for t in m.t if t > 1) + self.sb * ( sum(self.gen['cost'][g] * m.pgg[g, t] for g in m.g for t in m.t) + sum(self.cds * self.pde.iloc[t, b] * m.pds[b, t] for b in m.b for t in m.t) + sum(self.crs * m.prs[b, t] for b in m.b for t in m.t)) else: return m.z == self.sb * ( sum(self.gen['cost'][g] * m.pgg[g, t] for g in m.g for t in m.t) + sum(self.cds * self.pde.iloc[t, b] * m.pds[b, t] for b in m.b for t in m.t) + sum(self.crs * m.prs[b, t] for b in m.b for t in m.t)) m.cost_def = pe.Constraint(rule=cost_def_rule) #Active Energy Balance def act_bal_rule(m, b, t): return sum(m.pgg[g, t] for g in m.g if self.gen['bus'][g] == b) + self.pre.iloc[t, b] + sum( m.pll[l, t] for l in m.l if self.lin['to'][l] == b) == self.pde.iloc[ t, b] * (1 - m.pds[b, t]) + m.prs[b, t] + sum( m.pll[l, t] for l in m.l if self.lin['from'][l] == b) m.act_bal = pe.Constraint(m.b, m.t, rule=act_bal_rule) #Reactive Energy Balance def rea_bal_rule(m, b, t): return sum(m.qgg[g, t] for g in m.g if self.gen['bus'][g] == b) + sum( m.qll[l, t] for l in m.l if self.lin['to'][l] == b) == self.qde.iloc[t, b] * (1 - m.pds[b, t]) + sum( m.qll[l, t] for l in m.l if self.lin['from'][l] == b) m.rea_bal = pe.Constraint(m.b, m.t, rule=rea_bal_rule) #Minimum Active Generation def min_act_gen_rule(m, g, t): return m.pgg[g, t] >= m.u[g, t] * self.gen['pmin'][g] m.min_act_gen = pe.Constraint(m.g, m.t, rule=min_act_gen_rule) #Maximum Active Generation def max_act_gen_rule(m, g, t): return m.pgg[g, t] <= m.u[g, t] * self.gen['pmax'][g] m.max_act_gen = pe.Constraint(m.g, m.t, rule=max_act_gen_rule) #Minimum Reactive Generation def min_rea_gen_rule(m, g, t): return m.qgg[g, t] >= m.u[g, t] * self.gen['qmin'][g] m.min_rea_gen = pe.Constraint(m.g, m.t, rule=min_rea_gen_rule) #Maximum Reactive Generation def max_rea_gen_rule(m, g, t): return m.qgg[g, t] <= m.u[g, t] * self.gen['qmax'][g] m.max_rea_gen = pe.Constraint(m.g, m.t, rule=max_rea_gen_rule) #Maximum Renewable Shedding def max_shed_rule(m, b, t): return m.prs[b, t] <= self.pre.iloc[t, b] m.max_shed = pe.Constraint(m.b, m.t, rule=max_shed_rule) #Line flow Definition def flow_rule(m, l, t): if network: return ( m.vol[self.lin['from'][l], t] - m.vol[self.lin['to'][l], t]) == self.lin['res'][l] * m.pll[ l, t] + self.lin['rea'][l] * m.qll[l, t] else: return pe.Constraint.Skip m.flow = pe.Constraint(m.l, m.t, rule=flow_rule) #Max Active Line Flow def max_act_flow_rule(m, l, t): if network: return m.pll[l, t] <= self.lin['pmax'][l] else: return pe.Constraint.Skip m.max_act_flow = pe.Constraint(m.l, m.t, rule=max_act_flow_rule) #Min Active Line Flow def min_act_flow_rule(m, l, t): if network: return m.pll[l, t] >= -self.lin['pmax'][l] else: return pe.Constraint.Skip m.min_act_flow = pe.Constraint(m.l, m.t, rule=min_act_flow_rule) #Max Reactive Line Flow def max_rea_flow_rule(m, l, t): if network: return m.qll[l, t] <= self.lin['qmax'][l] else: return pe.Constraint.Skip m.max_rea_flow = pe.Constraint(m.l, m.t, rule=max_rea_flow_rule) #Min Reactive Line Flow def min_rea_flow_rule(m, l, t): if network: return m.qll[l, t] >= -self.lin['qmax'][l] else: return pe.Constraint.Skip m.min_rea_flow = pe.Constraint(m.l, m.t, rule=min_rea_flow_rule) #Voltage Magnitude at Reference Bus def vol_ref_rule(m, t): if network: return sum(m.vol[b, t] for b in m.b if b == 0) == 1 else: return pe.Constraint.Skip m.vol_ref = pe.Constraint(m.t, rule=vol_ref_rule) #Solve the optimization problem solver_manager = pe.SolverManagerFactory('neos') opt = pe.SolverFactory(solver) opt.options['threads'] = 1 opt.options['mipgap'] = 1e-9 result = solver_manager.solve(m, opt=opt, symbolic_solver_labels=True, tee=True) print(result['Solver'][0]) print(m.display()) #Save the results self.output = m self.u_output = pyomo2df(m.u, m.g, m.t).T self.pgg_output = pyomo2df(m.pgg, m.g, m.t).T self.qgg_output = pyomo2df(m.qgg, m.g, m.t).T self.pds_output = pyomo2df(m.pds, m.b, m.t).T self.prs_output = pyomo2df(m.prs, m.b, m.t).T self.vol_output = pyomo2df(m.vol, m.b, m.t).T self.pll_output = pyomo2df(m.pll, m.l, m.t).T self.qll_output = pyomo2df(m.qll, m.l, m.t).T # Check if output folder exists if not os.path.exists(outdir): os.makedirs(outdir) self.u_output.to_csv(outdir + os.sep + 'u.csv', index=False) self.pgg_output.to_csv(outdir + os.sep + 'pg.csv', index=False) self.qgg_output.to_csv(outdir + os.sep + 'qg.csv', index=False) self.pds_output.to_csv(outdir + os.sep + 'pds.csv', index=False) self.prs_output.to_csv(outdir + os.sep + 'prs.csv', index=False) self.vol_output.to_csv(outdir + os.sep + 'vol.csv', index=False) self.pll_output.to_csv(outdir + os.sep + 'pl.csv', index=False) self.qll_output.to_csv(outdir + os.sep + 'ql.csv', index=False)
def diet_model(): model = AbstractModel( ) # an abstract model is initialized. An instance is created later with the '.dat' file ''' Sets initialization ''' # Foods model.F = Set() # Nutrients model.N = Set() # Cereals & grains model.G1 = Set() # Pulses & Vegetables model.G2 = Set() # Oil & Fats model.G3 = Set() # Mixed & Blended Foods model.G4 = Set() # Meat & Fish & Dairy model.G5 = Set() # Mix of foods for extra constraints model.G0 = Set() ''' Parameters initialization ''' # Cost of each food model.c = Param(model.F, within=PositiveReals) # Amount of nutrient in each food model.a = Param(model.F, model.N, within=NonNegativeReals) # Lower bound on each nutrient model.Nmin = Param(model.N, within=NonNegativeReals, default=0.0) # Upper and lower bounds on each group model.maxG1 = Param(within=NonNegativeReals) model.minG1 = Param(within=NonNegativeReals) model.maxG2 = Param(within=NonNegativeReals) model.minG2 = Param(within=NonNegativeReals) model.maxG3 = Param(within=NonNegativeReals) model.minG3 = Param(within=NonNegativeReals) model.maxG4 = Param(within=NonNegativeReals) model.minG4 = Param(within=NonNegativeReals) model.maxG5 = Param(within=NonNegativeReals) model.minG5 = Param(within=NonNegativeReals) # Volume per serving of food model.V = Param(model.F, within=PositiveReals) ''' Variables initialization ''' # Decision variable model.x = Var(model.F, within=NonNegativeReals) # Slack variables model.Sg1 = Var(within=Reals) model.Sg2 = Var(within=Reals) model.Sg3 = Var(within=Reals) model.Sg4 = Var(within=Reals) model.Sg5 = Var(within=Reals) model.Sl = Var(model.N, within=NonNegativeReals) ''' OBJECTIVE FUNCTION: Minimize the value of the Sl[j]s ''' def cost_rule(model): return sum(model.Sl[i] for i in model.N) ''' CONSTRAINTS ''' # Limit nutrient consumption for each nutrient def nutrient_rule(model, j): value = sum(model.a[i, j] * model.x[i] for i in model.F) return value >= model.Nmin[j] * (1 - model.Sl[j]) # Limit the Slack variable value to be less than 1 def slackNut_rule(model, i): return model.Sl[i] <= 1 ''' To limit the amount of Food for each group ''' def G1_rule(model): valueG1 = sum(model.x[i] * 100 for i in model.G1) return environ.inequality(model.minG1, valueG1, model.maxG1) def G2_rule(model): valueG2 = sum(model.x[i] * 100 for i in model.G2) return environ.inequality(model.minG2, valueG2, model.maxG2) def G3_rule(model): valueG3 = sum(model.x[i] * 100 for i in model.G3) return environ.inequality(model.minG3, valueG3, model.maxG3) def G4_rule(model): valueG4 = sum(model.x[i] * 100 for i in model.G4) return environ.inequality(model.minG4, valueG4, model.maxG4) def G5_rule(model): valueG5 = sum(model.x[i] * 100 for i in model.G5) return environ.inequality(model.minG5, valueG5, model.maxG5) ''' Impose the sum of foods per group minus the Sgi (auxiliary var) to equal the mid point of each group range the mid point is considered the optimal point ''' def slack1_rule(model): return sum( model.x[i] * 100 for i in model.G1) - model.Sg1 == (model.minG1 + model.maxG1) / 2 def slack2_rule(model): return sum( model.x[i] * 100 for i in model.G2) - model.Sg2 == (model.minG2 + model.maxG2) / 2 def slack3_rule(model): return sum( model.x[i] * 100 for i in model.G3) - model.Sg3 == (model.minG3 + model.maxG3) / 2 def slack4_rule(model): return sum( model.x[i] * 100 for i in model.G4) - model.Sg4 == (model.minG4 + model.maxG4) / 2 def slack5_rule(model): return sum( model.x[i] * 100 for i in model.G5) - model.Sg5 == (model.minG5 + model.maxG5) / 2 def palatability_rule(model): global counter weighted_palatability = environ.sqrt(model.Sg1**2 + (2.5 * model.Sg2)**2 + (10 * model.Sg3)**2 + (4.2 * model.Sg4)**2 + (6.25 * model.Sg5)**2) return 279.96 - weighted_palatability >= counter * 28 # To limit the amount of salt and sugar (I made it up) def salt_rule(model): return environ.inequality(0.05, model.x['Salt'], 1) def sugar_rule(model): return environ.inequality(0.00, model.x['Sugar'], 0.05) ''' Call to constraints and O.F. ''' model.cost = Objective(rule=cost_rule) model.nutrient_limit = Constraint(model.N, rule=nutrient_rule) model.slackNut_limit = Constraint(model.N, rule=slackNut_rule) model.G1_limit = Constraint(rule=G1_rule) model.G2_limit = Constraint(rule=G2_rule) model.G3_limit = Constraint(rule=G3_rule) model.G4_limit = Constraint(rule=G4_rule) model.G5_limit = Constraint(rule=G5_rule) model.salt_limit = Constraint(rule=salt_rule) model.sugar_limit = Constraint(rule=sugar_rule) model.slack_const1 = Constraint(rule=slack1_rule) model.slack_const2 = Constraint(rule=slack2_rule) model.slack_const3 = Constraint(rule=slack3_rule) model.slack_const4 = Constraint(rule=slack4_rule) model.slack_const5 = Constraint(rule=slack5_rule) # model.palatability_limit = Constraint(rule=palatability_rule) ''' Instantiate the model using the .dat file The GNU Linear Programming Kit is a software package intended for solving large-scale linear programming, mixed integer programming, and other related problems. ''' instance = model.create_instance('WFPdietOriginal.dat') solver_manager = environ.SolverManagerFactory('neos') results = solver_manager.solve( instance, opt='knitro') # for the non linear palatability constraint if (results.Solver._list[0]['Termination condition'].key == 'infeasible'): return 0 # instance.pprint() # to display the initial model structure before the optimization # instance.display() # to display the solution with constraints and OF if instance.Sg5.value is None: print('var Sg5 null') return 1 ''' Deterministic palatability function, weighted and non-weighted ''' palatability = np.round( math.sqrt(instance.Sg1.value**2 + instance.Sg2.value**2 + instance.Sg3.value**2 + instance.Sg4.value**2 + instance.Sg5.value**2), 2) weighted_palatability = np.round( math.sqrt(instance.Sg1.value**2 + (2.5 * instance.Sg2.value)**2 + (10 * instance.Sg3.value)**2 + (4.2 * instance.Sg4.value)**2 + (6.25 * instance.Sg5.value)**2), 2) ''' Saving of the optimal solution ''' solution = [] print('SOLUTION: ') for i in instance.F: f = open("solutions.csv", "a") row = "" solution.append(instance.x[i].value) row += str(instance.x[i].value) + '\n' # row += i + '\n' f.write(row) f.close() # print(i, np.round(instance.x[i].value, 2)) # if(instance.x[i].value > 0.00001): # print(i, instance.x[i].value) # To print variables values and obj function for v in instance.component_objects(Var, active=True): varobject = getattr(instance, str(v)) cost = 0 if (varobject.name == 'Sl'): for index in varobject: cost += varobject[index].value # print(" ", index, varobject[index].value) print(cost) f = open("solutions.csv", "a") f.write('\n') f.close() print('PALATABILITY', 279.96 - weighted_palatability) print('THE RESULT IS:', results.Solver._list[0]['Termination condition']) return 0
def diet_model(): model = AbstractModel() # An instance is created later with the '.dat' file ''' Sets initialization ''' # Foods model.F = Set() # Nutrients model.N = Set() # Cereals & grains model.G1 = Set() # Pulses & Vegetables model.G2 = Set() # Oil & Fats model.G3 = Set() # Mixed & Blended Foods model.G4 = Set() # Meat & Fish & Dairy model.G5 = Set() # Mix of foods for extra constraints model.G0 = Set() ''' Parameters initialization ''' # Cost of each food model.c = Param(model.F, within=PositiveReals) # Amount of nutrient in each food model.a = Param(model.F, model.N, within=NonNegativeReals) # Lower bound on each nutrient model.Nmin = Param(model.N, within=NonNegativeReals, default=0.0) # Volume per serving of food model.V = Param(model.F, within=PositiveReals) # Upper and lower bounds on each group model.maxG1 = Param(within=NonNegativeReals) model.minG1 = Param(within=NonNegativeReals) model.maxG2 = Param(within=NonNegativeReals) model.minG2 = Param(within=NonNegativeReals) model.maxG3 = Param(within=NonNegativeReals) model.minG3 = Param(within=NonNegativeReals) model.maxG4 = Param(within=NonNegativeReals) model.minG4 = Param(within=NonNegativeReals) model.maxG5 = Param(within=NonNegativeReals) model.minG5 = Param(within=NonNegativeReals) ''' Variables initialization ''' # Decision variable model.x = Var(model.F, within=NonNegativeReals) # Slack variables model.Sl = Var(model.N, within=NonNegativeReals) ''' OBJECTIVE FUNCTION: Minimize the value of the Sl[j]s ''' # Minimize the cost of food that is consumed # def cost_rule1(model): # return sum(model.c[i] * model.x[i] / 10000 for i in model.F) # Minimize the value of the Sl[j]s def cost_rule(model): return sum(model.Sl[i] for i in model.N) def cost_rule2(model): return sum(model.c[i] * model.x[i] / 10000 for i in model.F) ''' CONSTRAINTS ''' # Limit nutrient consumption for each nutrient def nutrient_rule(model, j): value = sum(model.a[i, j] * model.x[i] for i in model.F) return value >= model.Nmin[j] * (1 - model.Sl[j]) # Limit the Slack variable value to be less than 1 def slackNut_rule(model, i): return model.Sl[i] <= 1 ''' To limit the amount of Food for each group ''' def G1_rule(model): valueG1 = sum(model.x[i] * 100 for i in model.G1) return environ.inequality(model.minG1, valueG1, model.maxG1) # return environ.inequality(375, valueG1, model.maxG1) def G2_rule(model): valueG2 = sum(model.x[i] * 100 for i in model.G2) return environ.inequality(model.minG2, valueG2, model.maxG2) # return environ.inequality(80, valueG2, model.maxG2) def G3_rule(model): valueG3 = sum(model.x[i] * 100 for i in model.G3) return environ.inequality(model.minG3, valueG3, model.maxG3) # return environ.inequality(27.5, valueG3, model.maxG3) def G4_rule(model): valueG4 = sum(model.x[i] * 100 for i in model.G4) return environ.inequality(model.minG4, valueG4, model.maxG4) # return environ.inequality(30, valueG4, model.maxG4) def G5_rule(model): valueG5 = sum(model.x[i] * 100 for i in model.G5) return environ.inequality(model.minG5, valueG5, model.maxG5) # return environ.inequality(20, valueG5, model.maxG5) def salt_rule(model): return environ.inequality(0.05, model.x['Salt'], 0.15) def sugar_rule(model): return environ.inequality(0.00, model.x['Sugar'], 0.05) ''' Palatability constraint. Linear model: LINEAR REGRESSION ''' def linear_palatability_rule(model): global palatability_limit palatability_score = sum(model.x[i]*weights[i][0] for i in model.F) + intercept[0] return palatability_score >= palatability_limit ''' Palatability constraint. Non-linear model: NEURAL NETWORK with 2 hidden layers composed by 5 and 2 nodes from left to right. Activation functions: tanh and sigmoid for the last layer ''' def nonlinear_palatability_rule(model): global palatability_limit palatability_score = 1/(1+environ.exp(- (pyomo.core.expr.tanh( pyomo.core.expr.tanh(sum(model.x[i] * weights_ANN.iloc[:, 0][i] for i in model.F) + ANN.get_weights()[1][0])*ANN.get_weights()[2][:,0][0] + pyomo.core.expr.tanh(sum(model.x[i] * weights_ANN.iloc[:, 1][i] for i in model.F) + ANN.get_weights()[1][1])*ANN.get_weights()[2][:,0][1] + pyomo.core.expr.tanh(sum(model.x[i] * weights_ANN.iloc[:, 2][i] for i in model.F) + ANN.get_weights()[1][2])*ANN.get_weights()[2][:,0][2] + pyomo.core.expr.tanh(sum(model.x[i] * weights_ANN.iloc[:, 3][i] for i in model.F) + ANN.get_weights()[1][3])*ANN.get_weights()[2][:,0][3] + pyomo.core.expr.tanh(sum(model.x[i] * weights_ANN.iloc[:, 4][i] for i in model.F) + ANN.get_weights()[1][4])*ANN.get_weights()[2][:,0][4] + ANN.get_weights()[3][0])*ANN.get_weights()[4][0][0] + (pyomo.core.expr.tanh( pyomo.core.expr.tanh(sum(model.x[i] * weights_ANN.iloc[:, 0][i] for i in model.F) + ANN.get_weights()[1][0])*ANN.get_weights()[2][:,1][0] + pyomo.core.expr.tanh(sum(model.x[i] * weights_ANN.iloc[:, 1][i] for i in model.F) + ANN.get_weights()[1][1])*ANN.get_weights()[2][:,1][1] + pyomo.core.expr.tanh(sum(model.x[i] * weights_ANN.iloc[:, 2][i] for i in model.F) + ANN.get_weights()[1][2])*ANN.get_weights()[2][:,1][2] + pyomo.core.expr.tanh(sum(model.x[i] * weights_ANN.iloc[:, 3][i] for i in model.F) + ANN.get_weights()[1][3])*ANN.get_weights()[2][:,1][3] + pyomo.core.expr.tanh(sum(model.x[i] * weights_ANN.iloc[:, 4][i] for i in model.F) + ANN.get_weights()[1][4])*ANN.get_weights()[2][:,1][4] + ANN.get_weights()[3][1])*ANN.get_weights()[4][1][0]) + ANN.get_weights()[5][0]) )) return palatability_score*10 >= palatability_limit # Simple ANN # def nonlinear_palatability_rule(model): # palatability_score = 1/(1+environ.exp(- # (pyomo.core.expr.tanh( # pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * weights_ANN.iloc[:, 0][0] + sum(model.x[i] for i in model.G2) * weights_ANN.iloc[:, 0][1] + sum(model.x[i] for i in model.G3) * weights_ANN.iloc[:, 0][2] + sum(model.x[i] for i in model.G4) * weights_ANN.iloc[:, 0][3] + sum(model.x[i] for i in model.G5) * weights_ANN.iloc[:, 0][4]) + ANN.get_weights()[1][0])*ANN.get_weights()[2][:,0][0] # + pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * weights_ANN.iloc[:, 1][0] + sum(model.x[i] for i in model.G2) * weights_ANN.iloc[:, 1][1] + sum(model.x[i] for i in model.G3) * weights_ANN.iloc[:, 1][2] + sum(model.x[i] for i in model.G4) * weights_ANN.iloc[:, 1][3] + sum(model.x[i] for i in model.G5) * weights_ANN.iloc[:, 1][4]) + ANN.get_weights()[1][1])*ANN.get_weights()[2][:,0][1] # + pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * weights_ANN.iloc[:, 2][0] + sum(model.x[i] for i in model.G2) * weights_ANN.iloc[:, 2][1] + sum(model.x[i] for i in model.G3) * weights_ANN.iloc[:, 2][2] + sum(model.x[i] for i in model.G4) * weights_ANN.iloc[:, 2][3] + sum(model.x[i] for i in model.G5) * weights_ANN.iloc[:, 2][4]) + ANN.get_weights()[1][2])*ANN.get_weights()[2][:,0][2] # + pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * weights_ANN.iloc[:, 3][0] + sum(model.x[i] for i in model.G2) * weights_ANN.iloc[:, 3][1] + sum(model.x[i] for i in model.G3) * weights_ANN.iloc[:, 3][2] + sum(model.x[i] for i in model.G4) * weights_ANN.iloc[:, 3][3] + sum(model.x[i] for i in model.G5) * weights_ANN.iloc[:, 3][4]) + ANN.get_weights()[1][3])*ANN.get_weights()[2][:,0][3] # + pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * weights_ANN.iloc[:, 4][0] + sum(model.x[i] for i in model.G2) * weights_ANN.iloc[:, 4][1] + sum(model.x[i] for i in model.G3) * weights_ANN.iloc[:, 4][2] + sum(model.x[i] for i in model.G4) * weights_ANN.iloc[:, 4][3] + sum(model.x[i] for i in model.G5) * weights_ANN.iloc[:, 4][4]) + ANN.get_weights()[1][4])*ANN.get_weights()[2][:,0][4] # + ANN.get_weights()[3][0])*ANN.get_weights()[4][0][0] # + (pyomo.core.expr.tanh( # pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * weights_ANN.iloc[:, 0][0] + sum(model.x[i] for i in model.G2) * weights_ANN.iloc[:, 0][1] + sum(model.x[i] for i in model.G3) * weights_ANN.iloc[:, 0][2] + sum(model.x[i] for i in model.G4) * weights_ANN.iloc[:, 0][3] + sum(model.x[i] for i in model.G5) * weights_ANN.iloc[:, 0][4]) + ANN.get_weights()[1][0]) * ANN.get_weights()[2][:,1][0] # + pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * weights_ANN.iloc[:, 1][0] + sum(model.x[i] for i in model.G2) * weights_ANN.iloc[:, 1][1] + sum(model.x[i] for i in model.G3) * weights_ANN.iloc[:, 1][2] + sum(model.x[i] for i in model.G4) * weights_ANN.iloc[:, 1][3] + sum(model.x[i] for i in model.G5) * weights_ANN.iloc[:, 1][4]) + ANN.get_weights()[1][1]) * ANN.get_weights()[2][:,1][1] # + pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * weights_ANN.iloc[:, 2][0] + sum(model.x[i] for i in model.G2) * weights_ANN.iloc[:, 2][1] + sum(model.x[i] for i in model.G3) * weights_ANN.iloc[:, 2][2] + sum(model.x[i] for i in model.G4) * weights_ANN.iloc[:, 2][3] + sum(model.x[i] for i in model.G5)* weights_ANN.iloc[:, 2][4]) + ANN.get_weights()[1][2]) * ANN.get_weights()[2][:,1][2] # + pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * weights_ANN.iloc[:, 3][0] + sum(model.x[i] for i in model.G2) * weights_ANN.iloc[:, 3][1] + sum(model.x[i] for i in model.G3) * weights_ANN.iloc[:, 3][2] + sum(model.x[i] for i in model.G4) * weights_ANN.iloc[:, 3][3] + sum(model.x[i] for i in model.G5) * weights_ANN.iloc[:, 3][4]) + ANN.get_weights()[1][3]) * ANN.get_weights()[2][:,1][3] # + pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * weights_ANN.iloc[:, 4][0] + sum(model.x[i] for i in model.G2) * weights_ANN.iloc[:, 4][1] + sum(model.x[i] for i in model.G3) * weights_ANN.iloc[:, 4][2] + sum(model.x[i] for i in model.G4) * weights_ANN.iloc[:, 4][3] + sum(model.x[i] for i in model.G5) * weights_ANN.iloc[:, 4][4]) + ANN.get_weights()[1][4]) * ANN.get_weights()[2][:,1][4] # + ANN.get_weights()[3][1])*ANN.get_weights()[4][1][0]) # + ANN.get_weights()[5][0]) # )) # return palatability_score*10 >= 5 ''' Call to constraints and O.F. ''' model.cost = Objective(rule=cost_rule, sense=minimize) model.nutrient_limit = Constraint(model.N, rule=nutrient_rule) model.slackNut_limit = Constraint(model.N, rule=slackNut_rule) model.G1_limit = Constraint(rule=G1_rule) model.G2_limit = Constraint(rule=G2_rule) model.G3_limit = Constraint(rule=G3_rule) model.G4_limit = Constraint(rule=G4_rule) model.G5_limit = Constraint(rule=G5_rule) model.salt_limit = Constraint(rule=salt_rule) model.sugar_limit = Constraint(rule=sugar_rule) ''' 'nonlinear_palatability_rule' uses the ANN. 'linear_palatabilit_rule' uses a linear regression ''' model.palatability_limit = Constraint(rule=nonlinear_palatability_rule) # model.palatability_limit = Constraint(rule=linear_palatability_rule) ''' Instantiate the model using the .dat file The GNU Linear Programming Kit is a software package intended for solving large-scale linear programming, mixed integer programming, and other related problems. ''' instance = model.create_instance('WFPdietOriginal.dat', report_timing=False) start = time.time() solver_manager = environ.SolverManagerFactory('neos') # results = solver_manager.solve(instance, opt='knitro', options='algorithm=4 debug=1 outlev=3') # for the non linear palatability constraint results = solver_manager.solve(instance, opt='knitro', tee=True) end = time.time() print("Time:", end - start) # opt = SolverFactory('ipopt') # for the linear palatability constraint # opt.options["interior"] = "" # results = opt.solve(instance) # instance.display() # instance.pprint() # Calculation of the Palatability score with the deterministic formula Sg1 = (sum(instance.x[i].value for i in instance.G1)*100 - (instance.minG1 + instance.maxG1) / 2) Sg2 = (sum(instance.x[i].value for i in instance.G2)*100 - (instance.minG2 + instance.maxG2) / 2) Sg3 = (sum(instance.x[i].value for i in instance.G3)*100 - (instance.minG3 + instance.maxG3) / 2) Sg4 = (sum(instance.x[i].value for i in instance.G4)*100 - (instance.minG4 + instance.maxG4) / 2) Sg5 = (sum(instance.x[i].value for i in instance.G5)*100 - (instance.minG5 + instance.maxG5) / 2) print(Sg1, Sg2, Sg3, Sg4, Sg5) max_palatability = 279.96 max_palatability_nonW = 139.69 weighted_palatability = np.round(math.sqrt(Sg1 ** 2 + (2.5 * Sg2) ** 2 + (10 * Sg3) ** 2 + (4.2 * Sg4) ** 2 + (6.25 * Sg5) ** 2), 2) nonweighted_palatability = np.round(math.sqrt(Sg1 ** 2 + (Sg2) ** 2 + (Sg3) ** 2 + (Sg4) ** 2 + (Sg5) ** 2), 2) palatability = max(max_palatability - weighted_palatability, 0) # palatability = 1/(1+environ.exp(-(pyomo.core.expr.tanh( # pyomo.core.expr.tanh(sum(instance.x[i].value * weights_ANN.iloc[:, 0][i] for i in instance.F) + ANN.get_weights()[1][0])*ANN.get_weights()[2][:,0][0] # + pyomo.core.expr.tanh(sum(instance.x[i].value * weights_ANN.iloc[:, 1][i] for i in instance.F) + ANN.get_weights()[1][1])*ANN.get_weights()[2][:,0][1] # + pyomo.core.expr.tanh(sum(instance.x[i].value * weights_ANN.iloc[:, 2][i] for i in instance.F) + ANN.get_weights()[1][2])*ANN.get_weights()[2][:,0][2] # + pyomo.core.expr.tanh(sum(instance.x[i].value * weights_ANN.iloc[:, 3][i] for i in instance.F) + ANN.get_weights()[1][3])*ANN.get_weights()[2][:,0][3] # + pyomo.core.expr.tanh(sum(instance.x[i].value * weights_ANN.iloc[:, 4][i] for i in instance.F) + ANN.get_weights()[1][4])*ANN.get_weights()[2][:,0][4] # + ANN.get_weights()[3][0])*ANN.get_weights()[4][0][0] # + (pyomo.core.expr.tanh( # pyomo.core.expr.tanh(sum(instance.x[i].value * weights_ANN.iloc[:, 0][i] for i in instance.F) + ANN.get_weights()[1][0])*ANN.get_weights()[2][:,1][0] # + pyomo.core.expr.tanh(sum(instance.x[i].value * weights_ANN.iloc[:, 1][i] for i in instance.F) + ANN.get_weights()[1][1])*ANN.get_weights()[2][:,1][1] # + pyomo.core.expr.tanh(sum(instance.x[i].value * weights_ANN.iloc[:, 2][i] for i in instance.F) + ANN.get_weights()[1][2])*ANN.get_weights()[2][:,1][2] # + pyomo.core.expr.tanh(sum(instance.x[i].value * weights_ANN.iloc[:, 3][i] for i in instance.F) + ANN.get_weights()[1][3])*ANN.get_weights()[2][:,1][3] # + pyomo.core.expr.tanh(sum(instance.x[i].value * weights_ANN.iloc[:, 4][i] for i in instance.F) + ANN.get_weights()[1][4])*ANN.get_weights()[2][:,1][4] # + ANN.get_weights()[3][1])*ANN.get_weights()[4][1][0]) # + ANN.get_weights()[5][0]) # )) # palatability_value = 1 / (1 + environ.exp(- # (pyomo.core.expr.tanh( # pyomo.core.expr.tanh((sum(instance.x[i].value for i in instance.G1) * # weights_ANN.iloc[:, 0][0] + sum( # instance.x[i].value for i in instance.G2) * weights_ANN.iloc[:, 0][ # 1] + sum(instance.x[i].value for i in instance.G3) * # weights_ANN.iloc[:, 0][2] + sum( # instance.x[i].value for i in instance.G4) * weights_ANN.iloc[:, 0][ # 3] + sum(instance.x[i].value for i in instance.G5) * # weights_ANN.iloc[:, 0][4]) + ANN.get_weights()[1][ # 0]) * ANN.get_weights()[2][:, 0][0] # + pyomo.core.expr.tanh((sum(instance.x[i].value for i in instance.G1) * # weights_ANN.iloc[:, 1][0] + sum( # instance.x[i].value for i in instance.G2) * weights_ANN.iloc[:, 1][ # 1] + sum(instance.x[i].value for i in instance.G3) * # weights_ANN.iloc[:, 1][2] + sum( # instance.x[i].value for i in instance.G4) * weights_ANN.iloc[:, 1][ # 3] + sum(instance.x[i].value for i in instance.G5) * # weights_ANN.iloc[:, 1][4]) + ANN.get_weights()[1][ # 1]) * ANN.get_weights()[2][:, 0][1] # + pyomo.core.expr.tanh((sum(instance.x[i].value for i in instance.G1) * # weights_ANN.iloc[:, 2][0] + sum( # instance.x[i].value for i in instance.G2) * weights_ANN.iloc[:, 2][ # 1] + sum(instance.x[i].value for i in instance.G3) * # weights_ANN.iloc[:, 2][2] + sum( # instance.x[i].value for i in instance.G4) * weights_ANN.iloc[:, 2][ # 3] + sum(instance.x[i].value for i in instance.G5) * # weights_ANN.iloc[:, 2][4]) + ANN.get_weights()[1][ # 2]) * ANN.get_weights()[2][:, 0][2] # + pyomo.core.expr.tanh((sum(instance.x[i].value for i in instance.G1) * # weights_ANN.iloc[:, 3][0] + sum( # instance.x[i].value for i in instance.G2) * weights_ANN.iloc[:, 3][ # 1] + sum(instance.x[i].value for i in instance.G3) * # weights_ANN.iloc[:, 3][2] + sum( # instance.x[i].value for i in instance.G4) * weights_ANN.iloc[:, 3][ # 3] + sum(instance.x[i].value for i in instance.G5) * # weights_ANN.iloc[:, 3][4]) + ANN.get_weights()[1][ # 3]) * ANN.get_weights()[2][:, 0][3] # + pyomo.core.expr.tanh((sum(instance.x[i].value for i in instance.G1) * # weights_ANN.iloc[:, 4][0] + sum( # instance.x[i].value for i in instance.G2) * weights_ANN.iloc[:, 4][ # 1] + sum(instance.x[i].value for i in instance.G3) * # weights_ANN.iloc[:, 4][2] + sum( # instance.x[i].value for i in instance.G4) * weights_ANN.iloc[:, 4][ # 3] + sum(instance.x[i].value for i in instance.G5) * # weights_ANN.iloc[:, 4][4]) + ANN.get_weights()[1][ # 4]) * ANN.get_weights()[2][:, 0][4] # + ANN.get_weights()[3][0]) * ANN.get_weights()[4][0][0] # + (pyomo.core.expr.tanh( # pyomo.core.expr.tanh((sum(instance.x[i].value for i in instance.G1) * # weights_ANN.iloc[:, 0][0] + sum( # instance.x[i].value for i in instance.G2) * # weights_ANN.iloc[:, 0][1] + sum( # instance.x[i].value for i in instance.G3) * # weights_ANN.iloc[:, 0][2] + sum( # instance.x[i].value for i in instance.G4) * # weights_ANN.iloc[:, 0][3] + sum( # instance.x[i].value for i in instance.G5) * # weights_ANN.iloc[:, 0][4]) + # ANN.get_weights()[1][0]) * # ANN.get_weights()[2][:, 1][0] # + pyomo.core.expr.tanh((sum(instance.x[i].value for i in instance.G1) * # weights_ANN.iloc[:, 1][0] + sum( # instance.x[i].value for i in instance.G2) * # weights_ANN.iloc[:, 1][1] + sum( # instance.x[i].value for i in instance.G3) * # weights_ANN.iloc[:, 1][2] + sum( # instance.x[i].value for i in instance.G4) * # weights_ANN.iloc[:, 1][3] + sum( # instance.x[i].value for i in instance.G5) * # weights_ANN.iloc[:, 1][4]) + # ANN.get_weights()[1][1]) * # ANN.get_weights()[2][:, 1][1] # + pyomo.core.expr.tanh((sum(instance.x[i].value for i in instance.G1) * # weights_ANN.iloc[:, 2][0] + sum( # instance.x[i].value for i in instance.G2) * # weights_ANN.iloc[:, 2][1] + sum( # instance.x[i].value for i in instance.G3) * # weights_ANN.iloc[:, 2][2] + sum( # instance.x[i].value for i in instance.G4) * # weights_ANN.iloc[:, 2][3] + sum( # instance.x[i].value for i in instance.G5) * # weights_ANN.iloc[:, 2][4]) + # ANN.get_weights()[1][2]) * # ANN.get_weights()[2][:, 1][2] # + pyomo.core.expr.tanh((sum(instance.x[i].value for i in instance.G1) * # weights_ANN.iloc[:, 3][0] + sum( # instance.x[i].value for i in instance.G2) * # weights_ANN.iloc[:, 3][1] + sum( # instance.x[i].value for i in instance.G3) * # weights_ANN.iloc[:, 3][2] + sum( # instance.x[i].value for i in instance.G4) * # weights_ANN.iloc[:, 3][3] + sum( # instance.x[i].value for i in instance.G5) * # weights_ANN.iloc[:, 3][4]) + # ANN.get_weights()[1][3]) * # ANN.get_weights()[2][:, 1][3] # + pyomo.core.expr.tanh((sum(instance.x[i].value for i in instance.G1) * # weights_ANN.iloc[:, 4][0] + sum( # instance.x[i].value for i in instance.G2) * # weights_ANN.iloc[:, 4][1] + sum( # instance.x[i].value for i in instance.G3) * # weights_ANN.iloc[:, 4][2] + sum( # instance.x[i].value for i in instance.G4) * # weights_ANN.iloc[:, 4][3] + sum( # instance.x[i].value for i in instance.G5) * # weights_ANN.iloc[:, 4][4]) + # ANN.get_weights()[1][4]) * # ANN.get_weights()[2][:, 1][4] # + ANN.get_weights()[3][1]) * ANN.get_weights()[4][1][0]) # + ANN.get_weights()[5][0]) # )) # score_comparison = ANN.predict(np.array([[sum(instance.x[i].value for i in instance.G1), # sum(instance.x[i].value for i in instance.G2), # sum(instance.x[i].value for i in instance.G3), # sum(instance.x[i].value for i in instance.G4), # sum(instance.x[i].value for i in instance.G5)]])) ''' Saving of the optimal solution ''' solution = [] print('SOLUTION: ') for i in instance.F: # f = open("solutions.csv", "a") # row = "" solution.append(instance.x[i].value) # row += str(instance.x[i].value) + '\n' # # row += i + '\n' # f.write(row) # f.close() # # print(i, np.round(instance.x[i].value, 2)) # # if(instance.x[i].value > 0.00001): # # print(i, instance.x[i].value) # # To print variables values and obj function # for v in instance.component_objects(Var, active=True): # varobject = getattr(instance, str(v)) # cost = 0 # if (varobject.name == 'Sl'): # for index in varobject: # cost += varobject[index].value # # print(" ", index, varobject[index].value) # print(cost) # f = open("solutions.csv", "a") # f.write('\n') # f.close() print(solution) print('PALATABILITY', palatability) print('THE RESULT IS:', results.Solver._list[0]['Termination condition'])
def adversarialGen(): # Features of the model features_name = [ 'Beans', 'Bulgur', 'Cheese', 'Fish', 'Meat', 'Corn-soya blend (CSB)', 'Dates', 'Dried skim milk (enriched) (DSM)', 'Milk', 'Salt', 'Lentils', 'Maize', 'Maize meal', 'Chickpeas', 'Rice', 'Sorghum/millet', 'Soya-fortified bulgur wheat', 'Soya-fortified maize meal', 'Soya-fortified sorghum grits', 'Soya-fortified wheat flour', 'Sugar', 'Oil', 'Wheat', 'Wheat flour', 'Wheat-soya blend (WSB)' ] # Importing the pre-trained models # file_lr = 'modelsOL/lr_OL.sav' # linear_reg = pickle.load(open(file_lr, 'rb')) file_ANN_simple = 'modelsOL/simple2_OL.h5' ANN = load_model(file_ANN_simple) weights_ANN = pd.DataFrame(ANN.get_weights()[0], index=features_name) # weights = pd.DataFrame(linear_reg.coef_, columns=features_name) # intercept = linear_reg.intercept_ ''' It is used to the difene the context and structure of the problem. An instance is created later with the '.dat' file. ''' model = AbstractModel() # Foods model.F = Set() # Nutrients model.N = Set() # Cereals & grains model.G1 = Set() # Pulses & Vegetables model.G2 = Set() # Oil & Fats model.G3 = Set() # Mixed & Blended Foods model.G4 = Set() # Meat & Fish & Dairy model.G5 = Set() # Cost of each food model.c = Param(model.F, within=PositiveReals) # Amount of nutrient in each food model.a = Param(model.F, model.N, within=NonNegativeReals) # Lower bound on each nutrient model.Nmin = Param(model.N, within=NonNegativeReals, default=0.0) # Volume per serving of food model.V = Param(model.F, within=PositiveReals) # Upper and lower bounds on each group model.maxG1 = Param(within=NonNegativeReals) model.minG1 = Param(within=NonNegativeReals) model.maxG2 = Param(within=NonNegativeReals) model.minG2 = Param(within=NonNegativeReals) model.maxG3 = Param(within=NonNegativeReals) model.minG3 = Param(within=NonNegativeReals) model.maxG4 = Param(within=NonNegativeReals) model.minG4 = Param(within=NonNegativeReals) model.maxG5 = Param(within=NonNegativeReals) model.minG5 = Param(within=NonNegativeReals) # Decision variable model.x = Var(model.F, within=NonNegativeReals) # Slack variables model.Sl = Var(model.N, within=NonNegativeReals) # Extra variables to control the palatability score (working in progress) # model.Sg1 = Var(within=Reals) ### # model.Sg2 = Var(within=Reals) ### # model.Sg3 = Var(within=Reals) ### # model.Sg4 = Var(within=Reals) ### # model.Sg5 = Var(within=Reals) ### # Minimize the cost of food that is consumed def cost_rule1(model): return sum(model.c[i] * model.x[i] / 10000 for i in model.F) # Minimize the value of the Sl[j]s def cost_rule2(model): return sum(model.Sl[i] for i in model.N) # Limit nutrient consumption for each nutrient def nutrient_rule(model, j): value = sum(model.a[i, j] * model.x[i] for i in model.F) return value >= model.Nmin[j] * (1 - model.Sl[j]) def slackNut_rule(model, i): return model.Sl[i] <= 1 ''' Limiting the amount of Food for each group ''' def G1_rule(model): valueG1 = sum(model.x[i] * 100 for i in model.G1) return environ.inequality(model.minG1, valueG1, model.maxG1) def G2_rule(model): valueG2 = sum(model.x[i] * 100 for i in model.G2) return environ.inequality(model.minG2, valueG2, model.maxG2) def G3_rule(model): valueG3 = sum(model.x[i] * 100 for i in model.G3) return environ.inequality(model.minG3, valueG3, model.maxG3) def G4_rule(model): valueG4 = sum(model.x[i] * 100 for i in model.G4) return environ.inequality(model.minG4, valueG4, model.maxG4) def G5_rule(model): valueG5 = sum(model.x[i] * 100 for i in model.G5) return environ.inequality(model.minG5, valueG5, model.maxG5) def salt_rule(model): return environ.inequality(0.05, model.x['Salt'], 0.15) def sugar_rule(model): return environ.inequality(0.00, model.x['Sugar'], 0.05) ''' Palatability constraint. Linear model: LINEAR REGRESSION ''' # def linear_palatability_rule(model): # global counter # palatability_limit = counter # palatability_score = sum(model.x[i]*weights[i][0] for i in model.F) + intercept[0] # return palatability_score >= palatability_limit ''' Palatability constraint. Non-linear model: NEURAL NETWORK with 2 hidden layers composed by 5 and 2 nodes from left to right. Activation functions: tanh and sigmoid for the last layer Loss function: MSE ''' def nonlinear_palatability_rule(model): global counter palatability_limit = counter palatability_score = 1 / (1 + environ.exp(-(pyomo.core.expr.tanh( pyomo.core.expr.tanh( sum(model.x[i] * weights_ANN.iloc[:, 0][i] for i in model.F) + ANN.get_weights()[1][0]) * ANN.get_weights()[2][:, 0][0] + pyomo.core.expr.tanh( sum(model.x[i] * weights_ANN.iloc[:, 1][i] for i in model.F) + ANN.get_weights()[1][1]) * ANN.get_weights()[2][:, 0][1] + pyomo.core.expr.tanh( sum(model.x[i] * weights_ANN.iloc[:, 2][i] for i in model.F) + ANN.get_weights()[1][2]) * ANN.get_weights()[2][:, 0][2] + pyomo.core.expr.tanh( sum(model.x[i] * weights_ANN.iloc[:, 3][i] for i in model.F) + ANN.get_weights()[1][3]) * ANN.get_weights()[2][:, 0][3] + pyomo.core.expr.tanh( sum(model.x[i] * weights_ANN.iloc[:, 4][i] for i in model.F) + ANN.get_weights()[1][4]) * ANN.get_weights()[2][:, 0][4] + ANN.get_weights()[3][0] ) * ANN.get_weights()[4][0][0] + (pyomo.core.expr.tanh( pyomo.core.expr.tanh( sum(model.x[i] * weights_ANN.iloc[:, 0][i] for i in model.F) + ANN.get_weights()[1][0]) * ANN.get_weights()[2][:, 1][0] + pyomo.core.expr.tanh( sum(model.x[i] * weights_ANN.iloc[:, 1][i] for i in model.F) + ANN.get_weights()[1][1]) * ANN.get_weights()[2][:, 1][1] + pyomo.core.expr.tanh( sum(model.x[i] * weights_ANN.iloc[:, 2][i] for i in model.F) + ANN.get_weights()[1][2]) * ANN.get_weights()[2][:, 1][2] + pyomo.core.expr.tanh( sum(model.x[i] * weights_ANN.iloc[:, 3][i] for i in model.F) + ANN.get_weights()[1][3]) * ANN.get_weights()[2][:, 1][3] + pyomo.core.expr.tanh( sum(model.x[i] * weights_ANN.iloc[:, 4][i] for i in model.F) + ANN.get_weights()[1][4]) * ANN.get_weights()[2][:, 1][4] + ANN.get_weights()[3][1] ) * ANN.get_weights()[4][1][0]) + ANN.get_weights()[5][0]))) return palatability_score * 10 >= palatability_limit ############################################################### # def slack1_rule(model): # return sum(model.x[i] * 100 for i in model.G1) - model.Sg1 == (model.minG1 + model.maxG1) / 2 # # def slack2_rule(model): # return sum(model.x[i] * 100 for i in model.G2) - model.Sg2 == (model.minG2 + model.maxG2) / 2 # # def slack3_rule(model): # return sum(model.x[i] * 100 for i in model.G3) - model.Sg3 == (model.minG3 + model.maxG3) / 2 # # def slack4_rule(model): # return sum(model.x[i] * 100 for i in model.G4) - model.Sg4 == (model.minG4 + model.maxG4) / 2 # # def slack5_rule(model): # return sum(model.x[i] * 100 for i in model.G5) - model.Sg5 == (model.minG5 + model.maxG5) / 2 # # def palatability_formula_rule(model): # global counter # weighted_palatability = environ.sqrt(model.Sg1 ** 2 + (2.5 * model.Sg2) ** 2 # + (10 * model.Sg3) ** 2 + (4.2 * model.Sg4) ** 2 # + (6.25 * model.Sg5) ** 2) # return environ.inequality((counter)*28, 279.96-weighted_palatability, (counter + 0.9)*28) # # model.palatability_formula = Constraint(rule=palatability_formula_rule) # model.slack_const1 = Constraint(rule=slack1_rule) # model.slack_const2 = Constraint(rule=slack2_rule) # model.slack_const3 = Constraint(rule=slack3_rule) # model.slack_const4 = Constraint(rule=slack4_rule) # model.slack_const5 = Constraint(rule=slack5_rule) ######################################################################## # def nonlinear_palatability_rule(model): # limit = random.randint(1, 9) # palatability_score = 1 / (1 + environ.exp(- # (pyomo.core.expr.tanh( # pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * # weights_ANN.iloc[:, 0][0] + sum( # model.x[i] for i in model.G2) * # weights_ANN.iloc[:, 0][1] + sum( # model.x[i] for i in model.G3) * # weights_ANN.iloc[:, 0][2] + sum( # model.x[i] for i in model.G4) * # weights_ANN.iloc[:, 0][3] + sum( # model.x[i] for i in model.G5) * # weights_ANN.iloc[:, 0][4]) + # ANN.get_weights()[1][0]) * # ANN.get_weights()[2][:, 0][0] # + pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * # weights_ANN.iloc[:, 1][0] + sum( # model.x[i] for i in model.G2) * # weights_ANN.iloc[:, 1][1] + sum( # model.x[i] for i in model.G3) * # weights_ANN.iloc[:, 1][2] + sum( # model.x[i] for i in model.G4) * # weights_ANN.iloc[:, 1][3] + sum( # model.x[i] for i in model.G5) * # weights_ANN.iloc[:, 1][4]) + # ANN.get_weights()[1][1]) * # ANN.get_weights()[2][:, 0][1] # + pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * # weights_ANN.iloc[:, 2][0] + sum( # model.x[i] for i in model.G2) * # weights_ANN.iloc[:, 2][1] + sum( # model.x[i] for i in model.G3) * # weights_ANN.iloc[:, 2][2] + sum( # model.x[i] for i in model.G4) * # weights_ANN.iloc[:, 2][3] + sum( # model.x[i] for i in model.G5) * # weights_ANN.iloc[:, 2][4]) + # ANN.get_weights()[1][2]) * # ANN.get_weights()[2][:, 0][2] # + pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * # weights_ANN.iloc[:, 3][0] + sum( # model.x[i] for i in model.G2) * # weights_ANN.iloc[:, 3][1] + sum( # model.x[i] for i in model.G3) * # weights_ANN.iloc[:, 3][2] + sum( # model.x[i] for i in model.G4) * # weights_ANN.iloc[:, 3][3] + sum( # model.x[i] for i in model.G5) * # weights_ANN.iloc[:, 3][4]) + # ANN.get_weights()[1][3]) * # ANN.get_weights()[2][:, 0][3] # + pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * # weights_ANN.iloc[:, 4][0] + sum( # model.x[i] for i in model.G2) * # weights_ANN.iloc[:, 4][1] + sum( # model.x[i] for i in model.G3) * # weights_ANN.iloc[:, 4][2] + sum( # model.x[i] for i in model.G4) * # weights_ANN.iloc[:, 4][3] + sum( # model.x[i] for i in model.G5) * # weights_ANN.iloc[:, 4][4]) + # ANN.get_weights()[1][4]) * # ANN.get_weights()[2][:, 0][4] # + ANN.get_weights()[3][0]) * ANN.get_weights()[4][0][0] # + (pyomo.core.expr.tanh( # pyomo.core.expr.tanh((sum(model.x[i] for i in model.G1) * # weights_ANN.iloc[:, 0][0] + sum( # model.x[i] for i in model.G2) * # weights_ANN.iloc[:, 0][1] + sum( # model.x[i] for i in model.G3) * # weights_ANN.iloc[:, 0][2] + sum( # model.x[i] for i in model.G4) * # weights_ANN.iloc[:, 0][3] + sum( # model.x[i] for i in model.G5) * # weights_ANN.iloc[:, 0][4]) + # ANN.get_weights()[1][0]) * # ANN.get_weights()[2][:, 1][0] # + pyomo.core.expr.tanh((sum( # model.x[i] for i in model.G1) * # weights_ANN.iloc[:, 1][0] + sum( # model.x[i] for i in model.G2) * # weights_ANN.iloc[:, 1][1] + sum( # model.x[i] for i in model.G3) * # weights_ANN.iloc[:, 1][2] + sum( # model.x[i] for i in model.G4) * # weights_ANN.iloc[:, 1][3] + sum( # model.x[i] for i in model.G5) * # weights_ANN.iloc[:, 1][4]) + # ANN.get_weights()[1][1]) * # ANN.get_weights()[2][:, 1][1] # + pyomo.core.expr.tanh((sum( # model.x[i] for i in model.G1) * # weights_ANN.iloc[:, 2][0] + sum( # model.x[i] for i in model.G2) * # weights_ANN.iloc[:, 2][1] + sum( # model.x[i] for i in model.G3) * # weights_ANN.iloc[:, 2][2] + sum( # model.x[i] for i in model.G4) * # weights_ANN.iloc[:, 2][3] + sum( # model.x[i] for i in model.G5) * # weights_ANN.iloc[:, 2][4]) + # ANN.get_weights()[1][2]) * # ANN.get_weights()[2][:, 1][2] # + pyomo.core.expr.tanh((sum( # model.x[i] for i in model.G1) * # weights_ANN.iloc[:, 3][0] + sum( # model.x[i] for i in model.G2) * # weights_ANN.iloc[:, 3][1] + sum( # model.x[i] for i in model.G3) * # weights_ANN.iloc[:, 3][2] + sum( # model.x[i] for i in model.G4) * # weights_ANN.iloc[:, 3][3] + sum( # model.x[i] for i in model.G5) * # weights_ANN.iloc[:, 3][4]) + # ANN.get_weights()[1][3]) * # ANN.get_weights()[2][:, 1][3] # + pyomo.core.expr.tanh((sum( # model.x[i] for i in model.G1) * # weights_ANN.iloc[:, 4][0] + sum( # model.x[i] for i in model.G2) * # weights_ANN.iloc[:, 4][1] + sum( # model.x[i] for i in model.G3) * # weights_ANN.iloc[:, 4][2] + sum( # model.x[i] for i in model.G4) * # weights_ANN.iloc[:, 4][3] + sum( # model.x[i] for i in model.G5) * # weights_ANN.iloc[:, 4][4]) + # ANN.get_weights()[1][4]) * # ANN.get_weights()[2][:, 1][4] # + ANN.get_weights()[3][1]) * ANN.get_weights()[4][1][0]) # + ANN.get_weights()[5][0]) # )) # return palatability_score * 10 >= 5 ''' Call to constraints and O.F. ''' model.cost = Objective(rule=cost_rule2) model.nutrient_limit = Constraint(model.N, rule=nutrient_rule) model.slackNut_limit = Constraint(model.N, rule=slackNut_rule) model.G1_limit = Constraint(rule=G1_rule) model.G2_limit = Constraint(rule=G2_rule) model.G3_limit = Constraint(rule=G3_rule) model.G4_limit = Constraint(rule=G4_rule) model.G5_limit = Constraint(rule=G5_rule) model.salt_limit = Constraint(rule=salt_rule) model.sugar_limit = Constraint(rule=sugar_rule) ''' 'nonlinear_palatability_rule' uses the ANN. 'linear_palatabilit_rule' uses a linear regression ''' model.palatability_limit = Constraint(rule=nonlinear_palatability_rule) # model.palatability_limit = Constraint(rule=linear_palatability_rule) ''' Instantiate the model using the .dat file The GNU Linear Programming Kit is a software package intended for solving large-scale linear programming, mixed integer programming, and other related problems. ''' instance = model.create_instance('WFPdietOriginal.dat') solver_manager = environ.SolverManagerFactory('neos') results = solver_manager.solve(instance, opt='knitro') # opt = SolverFactory('glpk') # results = opt.solve(instance) # instance.display() if (results.Solver._list[0]['Termination condition'].key != 'optimal'): print(results.Solver._list[0]['Termination condition'].key) return 0 # Calculation of the Palatability score with the deterministic formula Sg1 = abs( sum(instance.x[i].value for i in instance.G1) * 100 - (instance.minG1 + instance.maxG1) / 2) Sg2 = abs( sum(instance.x[i].value for i in instance.G2) * 100 - (instance.minG2 + instance.maxG2) / 2) Sg3 = abs( sum(instance.x[i].value for i in instance.G3) * 100 - (instance.minG3 + instance.maxG3) / 2) Sg4 = abs( sum(instance.x[i].value for i in instance.G4) * 100 - (instance.minG4 + instance.maxG4) / 2) Sg5 = abs( sum(instance.x[i].value for i in instance.G5) * 100 - (instance.minG5 + instance.maxG5) / 2) palatability = np.round( math.sqrt(Sg1**2 + Sg2**2 + Sg3**2 + Sg4**2 + Sg5**2), 2) weighted_palatability = np.round( math.sqrt(Sg1**2 + (2.5 * Sg2)**2 + (10 * Sg3)**2 + (4.2 * Sg4)**2 + (6.25 * Sg5)**2), 2) print('real palatability:', 279.96 - weighted_palatability) ''' Saving of the solution ''' global counter print('writing on the dataset') f = open("Datasets/datasetOL50it.csv", "a") row = "" for i in instance.F: if i != 'Wheat-soya blend (WSB)': row += str(np.round(instance.x[i].value, 2)) + ',' else: row += str(np.round(instance.x[i].value, 2)) + ',' + str( float(weighted_palatability)) + '\n' f.write(row) f.close() print(results.Solver._list[0]['Termination condition']) return 0
def run_multistart_approach( alpha_variables, initial_variables, maximum_number_iterations_multistart, new_label_values, transformed_label_all_samples, sample_alpha_variables, sample_to_train, number_of_nodes, bounds_weights, perturbation_multistart_variables, seed_multistart, index_SVM_regularization_parameter, iteration_alternating_approach, sample_names, SVM_regularization_parameter, data_all_samples, correspondence_time_period_line_all_samples, sample_by_line, number_of_renewable_energy, line, solver, neos_flag): results_multistart = {} solver_name = solver for iteration_multistart in range(maximum_number_iterations_multistart): print(iteration_multistart) results_multistart[iteration_multistart] = {} initial_variables_multistart = get_initial_variables_multistart( iteration_multistart=iteration_multistart, initial_variables=initial_variables, number_of_nodes=number_of_nodes, bounds_weights=bounds_weights, perturbation_multistart_variables=perturbation_multistart_variables, seed_multistart=seed_multistart, index_SVM_regularization_parameter= index_SVM_regularization_parameter, iteration_alternating_approach=iteration_alternating_approach) if neos_flag: solver = pe.SolverManagerFactory("neos") else: solver = pe.SolverFactory(solver_name) label_to_train = ( transformed_label_all_samples[sample_to_train]).to_frame() data_to_train = data_all_samples[sample_to_train] label_alpha_variables = ( transformed_label_all_samples[sample_alpha_variables].to_frame()) data_alpha_variables = data_all_samples[sample_alpha_variables] multistart_model = opss.optimization_problem_second_step( alpha_variables=alpha_variables, number_of_nodes=number_of_nodes, new_label_values=new_label_values, label_to_train=label_to_train, SVM_regularization_parameter=SVM_regularization_parameter, data_to_train=data_to_train, correspondence_time_period_line_all_samples= correspondence_time_period_line_all_samples, sample_by_line=sample_by_line, sample_to_train=sample_to_train, sample_alpha_variables=sample_alpha_variables, number_of_renewable_energy=number_of_renewable_energy, initial_variables_multistart=initial_variables_multistart, label_alpha_variables=label_alpha_variables, data_alpha_variables=data_alpha_variables) initial_time_second_step = timeit.default_timer() if neos_flag: results_solver = solver.solve(multistart_model, tee=True, opt=solver_name) else: results_solver = solver.solve(multistart_model, tee=True) final_time_second_step = timeit.default_timer() elapsed_time_second_step = final_time_second_step - initial_time_second_step objective_value_multistart = multistart_model.objective_function.expr() epigraph_variables = pd.DataFrame( index=multistart_model.indexes_time_periods) weights_variables = pd.DataFrame(index=multistart_model.indexes_nodes) for time_period in multistart_model.indexes_time_periods: epigraph_variables.loc[ time_period, 0] = multistart_model.epigraph_variables[time_period].value for node in multistart_model.indexes_nodes: weights_variables.loc[ node, 0] = multistart_model.weights_variables[node].value predictions = {} true_label = {} accuracy = {} for sample_name in sample_names: true_label[sample_name] = transformed_label_all_samples[ sample_name] predictions[sample_name] = pred.get_prediction_by_sample( alpha_variables=alpha_variables, SVM_regularization_parameter=SVM_regularization_parameter, weights_variables=weights_variables, first_sample=sample_to_train, second_sample=sample_name, transformed_label_all_samples=transformed_label_all_samples, data_all_samples=data_all_samples, correspondence_time_period_line_all_samples= correspondence_time_period_line_all_samples, sample_by_line=sample_by_line, new_label_values=new_label_values, line=line, number_of_renewable_energy=number_of_renewable_energy) accuracy[sample_name] = ptg.get_accuracy_by_sample( label=true_label[sample_name].values, prediction=predictions[sample_name].values) results_multistart[iteration_multistart]['weights'] = weights_variables results_multistart[iteration_multistart][ 'epigraph_variables'] = epigraph_variables results_multistart[iteration_multistart]['prediction'] = predictions results_multistart[iteration_multistart]['true_label'] = true_label results_multistart[iteration_multistart]['accuracy'] = accuracy results_multistart[iteration_multistart][ 'objective_value'] = objective_value_multistart results_multistart[iteration_multistart][ 'elapsed_time'] = elapsed_time_second_step return results_multistart
def solve(self, solver='cbc', network=True, commit=True, outdir='results'): """Solve the investment problem. :param str solver: the solver to be used. Default is 'cbc' :param bool network: ??? :param bool commit: ??? :param str outdir: The output directory for the results :returns: ??? :rtype: int :Example: >>> import pyeplan >>> sys_inv = pyeplan.invsys("3bus_inv") >>> sys_inv.solve(outdir='res_inv') """ #Define the Model m = pe.ConcreteModel() #Define the Sets m.cg = pe.Set(initialize=list(range(self.ncg)), ordered=True) m.eg = pe.Set(initialize=list(range(self.neg)), ordered=True) m.cr = pe.Set(initialize=list(range(self.ncr)), ordered=True) m.er = pe.Set(initialize=list(range(self.ner)), ordered=True) m.cl = pe.Set(initialize=list(range(self.ncl)), ordered=True) m.el = pe.Set(initialize=list(range(self.nel)), ordered=True) m.bb = pe.Set(initialize=list(range(self.nbb)), ordered=True) m.tt = pe.Set(initialize=list(range(self.ntt)), ordered=True) #Define Variables #Objective Function m.z = pe.Var() #Active and Reactive Power Generations (Conventional) m.pcg = pe.Var(m.cg, m.tt, within=pe.NonNegativeReals) m.peg = pe.Var(m.eg, m.tt, within=pe.NonNegativeReals) m.qcg = pe.Var(m.cg, m.tt, within=pe.NonNegativeReals) m.qeg = pe.Var(m.eg, m.tt, within=pe.NonNegativeReals) #Active and Reactive Power Generations (Renewable) m.pcr = pe.Var(m.cr, m.tt, within=pe.NonNegativeReals) m.per = pe.Var(m.er, m.tt, within=pe.NonNegativeReals) m.qcr = pe.Var(m.cr, m.tt, within=pe.Reals) m.qer = pe.Var(m.er, m.tt, within=pe.Reals) #Demand and Renewable Shedding m.pds = pe.Var(m.bb, m.tt, within=pe.Binary) m.prs = pe.Var(m.bb, m.tt, within=pe.NonNegativeReals) #Voltage Magnitude m.vol = pe.Var(m.bb, m.tt, within=pe.Reals, bounds=(self.vmin, self.vmax)) #Active and Reactive Line Flows m.pcl = pe.Var(m.cl, m.tt, within=pe.Reals) #Active Power m.pel = pe.Var(m.el, m.tt, within=pe.Reals) #Active Power m.qcl = pe.Var(m.cl, m.tt, within=pe.Reals) #Reactive Power m.qel = pe.Var(m.el, m.tt, within=pe.Reals) #Reactive Power #Commitment Status if commit: m.cu = pe.Var(m.cg, m.tt, within=pe.Binary) m.eu = pe.Var(m.eg, m.tt, within=pe.Binary) else: m.cu = pe.Var(m.cg, m.tt, within=pe.NonNegativeReals, bounds=(0, 1)) m.eu = pe.Var(m.eg, m.tt, within=pe.NonNegativeReals, bounds=(0, 1)) #Investment Status (Conventional) m.xg = pe.Var(m.cg, within=pe.Binary) #Investment Status (Renewable) m.xr = pe.Var(m.cr, within=pe.Binary) #Investment Status (Line) m.xl = pe.Var(m.cr, within=pe.Binary) #Objective Function def obj_rule(m): return m.z m.obj = pe.Objective(rule=obj_rule) #Definition Cost def cost_def_rule(m): if commit: return m.z == sum(self.cgen['icost'][cg]*m.xg[cg] for cg in m.cg) + \ sum(self.cren['icost'][cr]*m.xr[cr] for cr in m.cr) + \ sum(self.clin['icost'][cl]*m.xl[cl] for cl in m.cl) + \ sum(self.cgen['scost'][cg]*m.cu[cg,tt] for cg in m.cg for tt in m.tt) + \ sum(self.egen['scost'][eg]*m.cu[eg,tt] for eg in m.eg for tt in m.tt) - \ sum(self.cgen['scost'][cg]*m.cu[cg,tt-1] for cg in m.cg for tt in m.tt if tt>1) - \ sum(self.egen['scost'][eg]*m.eu[eg,tt-1] for eg in m.eg for tt in m.tt if tt>1) + \ self.sb*(sum(self.cgen['ocost'][cg]*m.pcg[cg,tt] for cg in m.cg for tt in m.tt) + \ sum(self.egen['ocost'][eg]*m.peg[eg,tt] for eg in m.eg for tt in m.tt) + \ sum(self.cren['ocost'][cr]*m.pcr[cr,tt] for cr in m.cr for tt in m.tt) + \ sum(self.eren['ocost'][er]*m.per[er,tt] for er in m.er for tt in m.tt) + \ sum(self.cds*self.pdem.iloc[tt,bb]*m.pds[bb,tt] for bb in m.bb for tt in m.tt) + \ sum(self.crs*m.prs[bb,tt] for bb in m.bb for tt in m.tt)) else: return m.z == sum(self.cgen['icost'][cg]*m.xg[cg] for cg in m.cg) + \ sum(self.cren['icost'][cr]*m.xr[cr] for cr in m.cr) + \ sum(self.clin['icost'][cl]*m.xl[cl] for cl in m.cl) + \ self.sb*(sum(self.cgen['ocost'][cg]*m.pcg[cg,tt] for cg in m.cg for tt in m.tt) + \ sum(self.egen['ocost'][eg]*m.peg[eg,tt] for eg in m.eg for tt in m.tt) + \ sum(self.cren['ocost'][cr]*m.pcr[cr,tt] for cr in m.cr for tt in m.tt) + \ sum(self.eren['ocost'][er]*m.per[er,tt] for er in m.er for tt in m.tt) + \ sum(self.cds*self.pdem.iloc[tt,bb]*m.pds[bb,tt] for bb in m.bb for tt in m.tt) + \ sum(self.crs*m.prs[bb,tt] for bb in m.bb for tt in m.tt)) m.cost_def = pe.Constraint(rule=cost_def_rule) #Active Energy Balance def act_bal_rule(m, bb, tt): return sum(m.pcg[cg,tt] for cg in m.cg if self.cgen['bus'][cg] == bb) + \ sum(m.peg[eg,tt] for eg in m.eg if self.egen['bus'][eg] == bb) + \ sum(m.pcr[cr,tt] for cr in m.cr if self.cren['bus'][cr] == bb) + \ sum(m.per[er,tt] for er in m.er if self.eren['bus'][er] == bb) + \ sum(m.pcl[cl,tt] for cl in m.cl if self.clin['to'][cl] == bb) + \ sum(m.pel[el,tt] for el in m.el if self.elin['to'][el] == bb) == \ sum(m.pcl[cl,tt] for cl in m.cl if self.clin['from'][cl] == bb) + \ sum(m.pel[el,tt] for el in m.el if self.elin['from'][el] == bb) + \ self.pdem.iloc[tt,bb]*(1 - m.pds[bb,tt]) m.act_bal = pe.Constraint(m.bb, m.tt, rule=act_bal_rule) #Reactive Energy Balance def rea_bal_rule(m, bb, tt): return sum(m.qcg[cg,tt] for cg in m.cg if self.cgen['bus'][cg] == bb) + \ sum(m.qeg[eg,tt] for eg in m.eg if self.egen['bus'][eg] == bb) + \ sum(m.qcr[cr,tt] for cr in m.cr if self.cren['bus'][cr] == bb) + \ sum(m.qer[er,tt] for er in m.er if self.eren['bus'][er] == bb) + \ sum(m.qcl[cl,tt] for cl in m.cl if self.clin['to'][cl] == bb) + \ sum(m.qel[el,tt] for el in m.el if self.elin['to'][el] == bb) == \ sum(m.qcl[cl,tt] for cl in m.cl if self.clin['from'][cl] == bb) + \ sum(m.qel[el,tt] for el in m.el if self.elin['from'][el] == bb) + \ self.qdem.iloc[tt,bb]*(1 - m.pds[bb,tt]) m.rea_bal = pe.Constraint(m.bb, m.tt, rule=rea_bal_rule) #Minimum Active Generation (Conventional) def min_act_cgen_rule(m, cg, tt): return m.pcg[cg, tt] >= m.cu[cg, tt] * self.cgen['pmin'][cg] m.min_act_cgen = pe.Constraint(m.cg, m.tt, rule=min_act_cgen_rule) def min_act_egen_rule(m, eg, tt): return m.peg[eg, tt] >= m.eu[eg, tt] * self.egen['pmin'][eg] m.min_act_egen = pe.Constraint(m.eg, m.tt, rule=min_act_egen_rule) #Minimum Active Generation (Renewable) def min_act_cren_rule(m, cr, tt): return m.pcr[cr, tt] >= self.cren['pmin'][cr] m.min_act_cren = pe.Constraint(m.cg, m.tt, rule=min_act_cren_rule) def min_act_eren_rule(m, er, tt): return m.per[er, tt] >= self.eren['pmin'][er] m.min_act_eren = pe.Constraint(m.eg, m.tt, rule=min_act_eren_rule) #Maximum Active Generation (Conventional) def max_act_cgen_rule(m, cg, tt): return m.pcg[cg, tt] <= m.cu[cg, tt] * self.cgen['pmax'][cg] m.max_act_cgen = pe.Constraint(m.cg, m.tt, rule=max_act_cgen_rule) def max_act_egen_rule(m, eg, tt): return m.peg[eg, tt] <= m.eu[eg, tt] * self.egen['pmax'][eg] m.max_act_egen = pe.Constraint(m.eg, m.tt, rule=max_act_egen_rule) #Maximum Active Generation (Renewable) def max_act_cren_rule(m, cr, tt): return m.pcr[cr, tt] <= m.xr[cr] * self.cren['pmax'][cr] * sum( self.pren.iloc[tt, bb] for bb in m.bb if self.cren['bus'][cr] == bb) m.max_act_cren = pe.Constraint(m.cr, m.tt, rule=max_act_cren_rule) def max_act_eren_rule(m, er, tt): return m.per[er, tt] <= self.eren['pmax'][er] * sum( self.pren.iloc[tt, bb] for bb in m.bb if self.eren['bus'][er] == bb) m.max_act_eren = pe.Constraint(m.er, m.tt, rule=max_act_eren_rule) #Minimum Reactive Generation (Conventional) def min_rea_cgen_rule(m, cg, tt): return m.qcg[cg, tt] >= m.cu[cg, tt] * self.cgen['qmin'][cg] m.min_rea_cgen = pe.Constraint(m.cg, m.tt, rule=min_rea_cgen_rule) def min_rea_egen_rule(m, eg, tt): return m.qeg[eg, tt] >= m.eu[eg, tt] * self.egen['qmin'][eg] m.min_rea_egen = pe.Constraint(m.eg, m.tt, rule=min_rea_egen_rule) #Minimum Reactive Generation (Renewable) def min_rea_cren_rule(m, cr, tt): return m.qcr[cr, tt] >= m.xr[cr] * self.cren['qmin'][cr] m.min_rea_cren = pe.Constraint(m.cr, m.tt, rule=min_rea_cren_rule) def min_rea_eren_rule(m, er, tt): return m.qer[er, tt] >= self.eren['qmin'][er] m.min_rea_eren = pe.Constraint(m.er, m.tt, rule=min_rea_eren_rule) #Maximum Reactive Generation (Conventional) def max_rea_cgen_rule(m, cg, tt): return m.qcg[cg, tt] <= m.cu[cg, tt] * self.cgen['qmax'][cg] m.max_rea_cgen = pe.Constraint(m.cg, m.tt, rule=max_rea_cgen_rule) def max_rea_egen_rule(m, eg, tt): return m.qeg[eg, tt] <= m.eu[eg, tt] * self.egen['qmax'][eg] m.max_rea_egen = pe.Constraint(m.eg, m.tt, rule=max_rea_egen_rule) #Maximum Reactive Generation (Renewable) def max_rea_cren_rule(m, cr, tt): return m.qcr[cr, tt] <= m.xr[cr] * self.cren['qmax'][cr] m.max_rea_cren = pe.Constraint(m.cr, m.tt, rule=max_rea_cren_rule) def max_rea_eren_rule(m, er, tt): return m.qer[er, tt] <= self.eren['qmax'][er] m.max_rea_eren = pe.Constraint(m.er, m.tt, rule=max_rea_eren_rule) #Maximum Renewable Shedding def max_shed_rule(m, bb, tt): return m.prs[bb,tt] <= (sum(m.xr[cr]*self.cren['pmax'][cr]*sum(self.pren.iloc[tt,bb] for bb in m.bb if self.cren['bus'][cr] == bb) for cr in m.cr) + \ sum(self.eren['pmax'][er]*sum(self.pren.iloc[tt,bb] for bb in m.bb if self.eren['bus'][er] == bb) for er in m.er)) - \ (sum(m.pcr[cr,tt] for cr in m.cr if self.cren['bus'][cr] == bb) + \ sum(m.per[er,tt] for er in m.er if self.eren['bus'][er] == bb)) m.max_shed = pe.Constraint(m.bb, m.tt, rule=max_shed_rule) #Line flow Definition def flow_rule(m, cl, el, tt): if network: if el == cl: return (m.vol[self.clin['from'][cl],tt] - m.vol[self.clin['to'][cl],tt]) == \ self.clin['res'][cl]*(m.pcl[cl,tt]+m.pel[el,tt]) + \ self.clin['rea'][cl]*(m.qcl[cl,tt]+m.qel[el,tt]) else: return pe.Constraint.Skip else: return pe.Constraint.Skip m.flow = pe.Constraint(m.cl, m.el, m.tt, rule=flow_rule) #Max Active Line Flow def max_act_cflow_rule(m, cl, tt): if network: return m.pcl[cl, tt] <= self.clin['pmax'][cl] * m.xl[cl] else: return pe.Constraint.Skip m.max_act_cflow = pe.Constraint(m.cl, m.tt, rule=max_act_cflow_rule) def max_act_eflow_rule(m, el, tt): if network: return m.pel[ el, tt] <= self.elin['pmax'][el] * self.elin['ini'][el] else: return pe.Constraint.Skip m.max_act_eflow = pe.Constraint(m.el, m.tt, rule=max_act_eflow_rule) #Min Active Line Flow def min_act_cflow_rule(m, cl, tt): if network: return m.pcl[cl, tt] >= -self.clin['pmax'][cl] * m.xl[cl] else: return pe.Constraint.Skip m.min_act_cflow = pe.Constraint(m.cl, m.tt, rule=min_act_cflow_rule) def min_act_eflow_rule(m, el, tt): if network: return m.pel[ el, tt] >= -self.elin['pmax'][el] * self.elin['ini'][el] else: return pe.Constraint.Skip m.min_act_eflow = pe.Constraint(m.el, m.tt, rule=min_act_eflow_rule) #Max Reactive Line Flow def max_rea_cflow_rule(m, cl, tt): if network: return m.qcl[cl, tt] <= self.clin['qmax'][cl] * m.xl[cl] else: return pe.Constraint.Skip m.max_rea_cflow = pe.Constraint(m.cl, m.tt, rule=max_rea_cflow_rule) def max_rea_eflow_rule(m, el, tt): if network: return m.qel[ el, tt] <= self.elin['qmax'][el] * self.elin['ini'][el] else: return pe.Constraint.Skip m.max_rea_eflow = pe.Constraint(m.el, m.tt, rule=max_rea_eflow_rule) #Min Reactive Line Flow def min_rea_cflow_rule(m, cl, tt): if network: return m.qcl[cl, tt] >= -self.clin['qmax'][cl] * m.xl[cl] else: return pe.Constraint.Skip m.min_rea_cflow = pe.Constraint(m.cl, m.tt, rule=min_rea_cflow_rule) def min_rea_eflow_rule(m, el, tt): if network: return m.qel[ el, tt] >= -self.elin['qmax'][el] * self.elin['ini'][el] else: return pe.Constraint.Skip m.min_rea_eflow = pe.Constraint(m.el, m.tt, rule=min_rea_eflow_rule) #Voltage Magnitude at Reference Bus def vol_ref_rule(m, tt): if network: return sum(m.vol[bb, tt] for bb in m.bb if bb == 0) == 1 else: return pe.Constraint.Skip m.vol_ref = pe.Constraint(m.tt, rule=vol_ref_rule) #Investment Status def inv_stat_rule(m, cg, tt): return m.cu[cg, tt] <= m.xg[cg] m.inv_stat = pe.Constraint(m.cg, m.tt, rule=inv_stat_rule) #Solve the optimization problem solver_manager = pe.SolverManagerFactory('neos') opt = pe.SolverFactory(solver) opt.options['threads'] = 1 opt.options['mipgap'] = 1e-9 result = solver_manager.solve(m, opt=opt, symbolic_solver_labels=True, tee=True) print(result['Solver'][0]) print(m.display()) #Save the results self.output = m self.xg_output = pyomo2dfinv(m.xg, m.cg).T self.xr_output = pyomo2dfinv(m.xr, m.cr).T self.xl_output = pyomo2dfinv(m.xl, m.cl).T self.cu_output = pyomo2dfopr(m.cu, m.cg, m.tt).T self.eu_output = pyomo2dfopr(m.eu, m.eg, m.tt).T self.pcg_output = pyomo2dfopr(m.pcg, m.cg, m.tt).T self.qcg_output = pyomo2dfopr(m.qcg, m.cg, m.tt).T self.peg_output = pyomo2dfopr(m.peg, m.eg, m.tt).T self.qeg_output = pyomo2dfopr(m.qeg, m.eg, m.tt).T self.pcr_output = pyomo2dfopr(m.pcr, m.cr, m.tt).T self.qcr_output = pyomo2dfopr(m.qcr, m.cr, m.tt).T self.per_output = pyomo2dfopr(m.per, m.er, m.tt).T self.qer_output = pyomo2dfopr(m.qer, m.er, m.tt).T self.pds_output = pyomo2dfopr(m.pds, m.bb, m.tt).T self.prs_output = pyomo2dfopr(m.prs, m.bb, m.tt).T self.vol_output = pyomo2dfopr(m.vol, m.bb, m.tt).T self.pcl_output = pyomo2dfopr(m.pcl, m.cl, m.tt).T self.qcl_output = pyomo2dfopr(m.qcl, m.cl, m.tt).T self.pel_output = pyomo2dfopr(m.pel, m.cl, m.tt).T self.qel_output = pyomo2dfopr(m.qel, m.cl, m.tt).T # Check if output folder exists if not os.path.exists(outdir): os.makedirs(outdir) self.xg_output.to_csv(outdir + os.sep + 'investment_conventional.csv', index=False) self.xr_output.to_csv(outdir + os.sep + 'investment_renewable.csv', index=False) self.xr_output.to_csv(outdir + os.sep + 'investment_line.csv', index=False) self.cu_output.to_csv(outdir + os.sep + 'cu.csv', index=False) self.eu_output.to_csv(outdir + os.sep + 'eu.csv', index=False) self.pcg_output.to_csv(outdir + os.sep + 'pcg.csv', index=False) self.qcg_output.to_csv(outdir + os.sep + 'qcg.csv', index=False) self.peg_output.to_csv(outdir + os.sep + 'peg.csv', index=False) self.qeg_output.to_csv(outdir + os.sep + 'qeg.csv', index=False) self.pcr_output.to_csv(outdir + os.sep + 'pcr.csv', index=False) self.qcr_output.to_csv(outdir + os.sep + 'qcr.csv', index=False) self.per_output.to_csv(outdir + os.sep + 'per.csv', index=False) self.qer_output.to_csv(outdir + os.sep + 'qer.csv', index=False) self.pds_output.to_csv(outdir + os.sep + 'pds.csv', index=False) self.prs_output.to_csv(outdir + os.sep + 'prs.csv', index=False) self.vol_output.to_csv(outdir + os.sep + 'vol.csv', index=False) self.pcl_output.to_csv(outdir + os.sep + 'pcl.csv', index=False) self.qcl_output.to_csv(outdir + os.sep + 'qcl.csv', index=False) self.pel_output.to_csv(outdir + os.sep + 'pel.csv', index=False) self.qel_output.to_csv(outdir + os.sep + 'qel.csv', index=False)
def solve(self, solver='cplex', neos=True, network=True, commit=True): #Define the model m = pe.ConcreteModel() #Define the sets m.g = pe.Set(initialize=list(range(self.ng)), ordered=True) m.l = pe.Set(initialize=list(range(self.nl)), ordered=True) m.b = pe.Set(initialize=list(range(self.nb)), ordered=True) m.t = pe.Set(initialize=list(range(self.nt)), ordered=True) #Define variables m.z = pe.Var() m.pro = pe.Var(m.g, m.t, within=pe.NonNegativeReals) if commit: m.u = pe.Var(m.g, m.t, within=pe.Binary) else: m.u = pe.Var(m.g, m.t, within=pe.NonNegativeReals, bounds=(0, 1)) m.shd = pe.Var(m.b, m.t, within=pe.NonNegativeReals) m.spl = pe.Var(m.b, m.t, within=pe.NonNegativeReals) m.ang = pe.Var(m.b, m.t) m.flw = pe.Var(m.l, m.t) #Objective function def obj_rule(m): return m.z m.obj = pe.Objective(rule=obj_rule) #Definition cost def cost_def_rule(m): return m.z == sum(self.gen['cost'][g] * m.pro[g, t] for g in m.g for t in m.t) + sum(self.cs * m.shd[b, t] for b in m.b for t in m.t) m.cost_def = pe.Constraint(rule=cost_def_rule) #Energy balance def bal_rule(m, b, t): return sum(m.pro[g, t] for g in m.g if self.gen['bus'][g] == b) + self.ren.iloc[t, b] + m.shd[b, t] + sum( m.flw[l, t] for l in m.l if self.lin['to'][l] == b) == self.dem.iloc[t, b] + m.spl[b, t] + sum( m.flw[l, t] for l in m.l if self.lin['from'][l] == b) m.bal = pe.Constraint(m.b, m.t, rule=bal_rule) #Minimum generation def min_gen_rule(m, g, t): return m.pro[g, t] >= m.u[g, t] * self.gen['min'][g] m.min_gen = pe.Constraint(m.g, m.t, rule=min_gen_rule) #Maximum generation def max_gen_rule(m, g, t): return m.pro[g, t] <= m.u[g, t] * self.gen['max'][g] m.max_gen = pe.Constraint(m.g, m.t, rule=max_gen_rule) #Maximum spilage def max_spil_rule(m, b, t): return m.spl[b, t] <= self.ren.iloc[t, b] m.max_spil = pe.Constraint(m.b, m.t, rule=max_spil_rule) #Maximum shedding def max_shed_rule(m, b, t): return m.shd[b, t] <= self.dem.iloc[t, b] m.max_shed = pe.Constraint(m.b, m.t, rule=max_shed_rule) #Power flow definition def flow_rule(m, l, t): return m.flw[l, t] == self.lin['sus'][l] * ( m.ang[self.lin['from'][l], t] - m.ang[self.lin['to'][l], t]) m.flow = pe.Constraint(m.l, m.t, rule=flow_rule) #Max power flow def max_flow_rule(m, l, t): if network: return m.flw[l, t] <= self.lin['cap'][l] else: return pe.Constraint.Skip m.max_flow = pe.Constraint(m.l, m.t, rule=max_flow_rule) #Min power flow def min_flow_rule(m, l, t): if network: return m.flw[l, t] >= -self.lin['cap'][l] else: return pe.Constraint.Skip m.min_flow = pe.Constraint(m.l, m.t, rule=min_flow_rule) #We solve the optimization problem solver_manager = pe.SolverManagerFactory('neos') opt = pe.SolverFactory('cplex') opt.options['threads'] = 1 opt.options['mipgap'] = 1e-9 if neos: res = solver_manager.solve(m, opt=opt, symbolic_solver_labels=True, tee=True) else: res = opt.solve(m, symbolic_solver_labels=True, tee=True) print(res['Solver'][0]) #We save the results self.output = m self.prod = pyomo2df(m.pro, m.g, m.t).T self.stat = pyomo2df(m.u, m.g, m.t).T self.flow = pyomo2df(m.flw, m.l, m.t).T self.shed = pyomo2df(m.shd, m.b, m.t).T self.spil = pyomo2df(m.spl, m.b, m.t).T self.prod.to_csv('results/prod.csv', index=False) self.flow.to_csv('results/flow.csv', index=False)