def Portfolio(): m = pe.ConcreteModel() m.cons = pe.ConstraintList() N = 5 index = list(range(N)) mean = [0.1, 0.3, 0.5, 0.7, 0.4] m.x = pe.Var(index, bounds=(0, 1)) m.z = pe.Var(within=pe.PositiveReals) m.U = ro.UncSet() m.r = ro.UncParam(index, uncset=m.U, nominal=mean) r = m.r expr = 0 for i in index: expr += (m.r[i] - mean[i])**2 m.U.cons = pe.Constraint(expr=expr <= 0.0005) m.Elib = ro.uncset.EllipsoidalSet(mean, [[0.0005, 0, 0, 0, 0], [0, 0.0005, 0, 0, 0], [0, 0, 0.0005, 0, 0], [0, 0, 0, 0.0005, 0], [0, 0, 0, 0, 0.0005]]) P = [[1, 1, 0, 0, 0], [-1, 1, 0, 0, 0], [1, -1, 0, 0, 0], [-1, -1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, -1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, -1, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, -1]] rhs = [0.001 + mean[0] + mean[1], 0.001 - mean[0] + mean[1], 0.001 + mean[0] - mean[1], 0.001 - mean[0] - mean[1], 0.001 + mean[2], 0.001 - mean[2], 0.001 + mean[3], 0.001 - mean[3], 0.001 + mean[4], 0.001 - mean[4]] m.Plib = ro.uncset.PolyhedralSet(P, rhs) m.P = ro.UncSet() m.P.cons = pe.ConstraintList() for i, row in enumerate(P): m.P.cons.add(expr=pe.quicksum(row[j]*m.r[j] for j in m.r) <= rhs[i]) m.Obj = pe.Objective(expr=m.z, sense=pe.maximize) # x0 = m.x[0] # expr = x0*3 expr = sum([m.x[i] for i in index]) == 1 m.cons.add(expr) m.cons.add(sum([r[i]*m.x[i] for i in index]) >= m.z) return m
def Pooling(): m = pe.ConcreteModel() m.q = pe.Var(con_feed_pool, bounds=(0, 1)) m.y = pe.Var(con_pool_prod, within=pe.NonNegativeReals) m.z = pe.Var(con_feed_prod, within=pe.NonNegativeReals) m.U = ro.UncSet() m.price_product = ro.UncParam(products, nominal=price_product, uncset=m.U) expr = 0 for j in products: expr += (m.price_product[j] - price_product[j])**2 m.U.c = pe.Constraint(expr=expr <= 0.1) m.P = ro.UncSet() m.P.cons = pe.ConstraintList() for j in products: m.P.cons.add(m.price_product[j] - price_product[j] <= 0.01) m.P.cons.add(m.price_product[j] - price_product[j] >= -0.01) m.P.cons.add((m.price_product[0] - price_product[0]) + (m.price_product[1] - price_product[1]) <= 0.01) m.C = ro.UncSet() m.C.cons = pe.ConstraintList() for j in products: m.C.cons.add(m.price_product[j] - price_product[j] <= 0.01) m.C.cons.add(m.price_product[j] - price_product[j] >= -0.01) m.C.cons.add((m.price_product[0] - price_product[0]) + (m.price_product[1] - price_product[1]) <= 0.01) expr = 0 for j in products: expr += (m.price_product[j] - price_product[j])**2 m.C.cons.add(expr <= 0.1) pp = m.price_product obj = 0 for i, l in con_feed_pool: for j in [jj for ll, jj in con_pool_prod if ll == l]: obj += price_feed[j] * m.y[(l, j)] * m.q[i, l] for l, j in con_pool_prod: obj -= pp[j] * m.y[(l, j)] for i, j in con_feed_prod: obj -= (pp[j] - price_feed[i]) * m.z[(i, j)] m.obj = pe.Objective(expr=obj, sense=pe.minimize) m.feed_availability = pe.Constraint(feeds, rule=feed_availability_rule) m.pool_capacity = pe.Constraint(pools, rule=pool_capacity_rule) m.product_demand = pe.Constraint(products, rule=prod_demand_rule) m.simplex = pe.Constraint(pools, rule=simplex_rule) m.prod_quality_upper = pe.Constraint(products, qualities, rule=prod_quality_rule_upper) m.prod_quality_lower = pe.Constraint(products, qualities, rule=prod_quality_rule_lower) return m
def solve_Svestka(points, subtours=[]): points = list(points) V = set(range(len(points))) E = [(i, j) for i in V for j in V if i != j] m = po.ConcreteModel("Svestka") # m.setPresolve(SCIP_PARAMSETTING.OFF) # m.setHeuristics(SCIP_PARAMSETTING.OFF) # m.disablePropagation() # m.setCharParam("lp/initalgorithm", "p") # let's use the primal simplex # solving stops, if the relative gap = |primal - dual|/MIN(|dual|,|primal|) is below the given value #m.setParam("limits/gap", 1.0) # maximal memory usage in MB; reported memory usage is lower than real memory usage! default: 8796093022208 #m.setParam("limits/memory", 32000) # m.setParam("limits/time", 100) # maximal time in seconds to run infinity = float('inf') # BEGIN: Write here your model m.x = po.Var(E, bounds=(0, 1), domain=po.Binary) m.y = po.Var(E, bounds=(0, infinity), domain=po.NonNegativeReals) m.f = po.Param(initialize=0.1, domain=po.PositiveReals) # Objective m.OBJ = po.Objective(expr=sum(tsputil.distance( points[e[0]], points[e[1]]) * m.x[e] for e in E), sense=po.minimize) # Constraints m.arrive_cities = po.ConstraintList() for v in V: if v == 0: m.arrive_cities.add(expr=sum(m.y[(0, j)] for j in V if (0, j) in E) == 1) else: m.arrive_cities.add(expr=sum(m.y[(j, v)] for j in V if (j, v) in E) >= 1) m.flow_gain = po.ConstraintList() for v in V-{0}: m.flow_gain.add(expr=sum(m.y[(v, j)] for j in V if (v, j) in E) - sum(m.y[(j, v)] for j in V if (j, v) in E) == m.f) # cadrinality constraint m.only_pos_vars = po.Constraint(expr=sum(m.x[e] for e in E) <= len(V)) m.link_constraints = po.ConstraintList() for e in E: m.link_constraints.add(expr=m.y[e] <= (1+len(V)*m.f)*m.x[e]) # END # m.pprint() # m.write("svestka.lp") solver = po.SolverFactory('gurobi') results = solver.solve(m, tee=True, keepfiles=False) if (results.solver.status == po.SolverStatus.ok) and (results.solver.termination_condition == po.TerminationCondition.optimal): print('The optimal objective is ', m.OBJ()) return {(i, j): m.x[i, j]() for i, j in E} else: print("Something wrong") exit(0)
def events_to_time(self,subset=[]): m = pe.ConcreteModel() #Only include timeslots that are not banned T = [] for week in range(self.weeks_begin,self.weeks_end+1): for day,time_list in self.split_timeslots.get("week "+str(week)).items(): T.extend([time for time in time_list if time not in self.banned_keys]) E = [key for key in self.events] Index_old = [(e,t) for e in E for t in T] #Remove unnecessary indexes Index = self.remove_var_close_to_banned(Index_old) m.x = pe.Var(Index, domain = pe.Binary) m.obj=pe.Objective(expr=1) #All events must happen m.events_must_happen = pe.ConstraintList() for e in E: if any((e,t) in Index for _,t in list(filter(lambda x: e == x[0],Index))): m.events_must_happen.add(sum(m.x[e,t] for _,t in list(filter(lambda x: e == x[0],Index)))==1) #Precedence constraints m.precedence = pe.ConstraintList() for w in range(self.weeks_begin,self.weeks_end+1): starting_index = self.split_timeslots.get("week "+str(w)).get("day 0")[0] for u,v in self.precedence_graph.get("week "+str(w)): for t in T: if any((u,l) in Index for l in range(starting_index,t)): m.precedence.add(sum(m.x[u,l]-m.x[v,l] for l in range(starting_index,t+1) if (v,l) in Index and (u,l) in Index) >= 0) #No teacher conflicts # m.teacher_conflict = pe.ConstraintList() # for w in range(self.weeks_begin,self.weeks_end+1): # A = self.teacher_conflict_graph.get("week "+str(w)) # for u,v in A: # for t in T: # if any((u,l) in Index and (v,l) in Index for l in range(max(0,t-self.events.get(u).get("duration")+1),t+1)): # m.teacher_conflict.add(sum(m.x[u,l]+m.x[v,l] for l in range(max(0,t-self.events.get(u).get("duration")+1),t+1) if (u,l) in Index and (v,l) in Index) <= 1) #Ensure feasibility of the matching problem m.available_room = pe.ConstraintList() for t,time_dict in self.timeslots.items(): week = time_dict.get("week") starting_index = self.split_timeslots.get("week "+str(week)).get("day 0")[0] events = self.get_events_this_week(week) if any((e,t) in Index for e in events): m.available_room.add(sum(m.x[e,l] for e in events for l in range(max(starting_index,t-self.events.get(e).get("duration")+1),t+1) if (e,l) in Index)<=self.rooms_at_t_count.get(t)) solver = pyomo.opt.SolverFactory('glpk') results = solver.solve(m,tee=True) return [[(e,t) for e,t in Index if pe.value(m.x[e,t]) ==1]]
def add_transportation_problem( model, costs: np.ndarray, supply: np.ndarray, demand: np.ndarray, ): """ Args: model: pymo ConcreteModel to be mutated by adding variables, constraints and objective costs: matrix of costs of transporting an item from a supplier to a customer, of shape (# suppliers, # customers) supply: number of items suppliers can provide demand: number of iterms requested by clents """ n_suppliers = len(supply) n_customers = len(demand) model.nVars = pyo.Param(initialize=n_suppliers * n_customers) model.N = pyo.RangeSet(model.nVars) model.x = pyo.Var(model.N, within=pyo.NonNegativeReals) model.supply_constraints = pyo.ConstraintList() model.demand_constraints = pyo.ConstraintList() for i, s in enumerate(supply): expr = 0 for j in range(n_customers): variable_index = to_flat( i, j, n_rows=n_suppliers, n_cols=n_customers) + 1 expr += model.x[variable_index] model.supply_constraints.add(expr <= s) for i, d in enumerate(demand): expr = 0 for j in range(n_suppliers): variable_index = to_flat( j, i, n_rows=n_suppliers, n_cols=n_customers) + 1 expr += model.x[variable_index] model.demand_constraints.add(expr == d) expr = 0 for i in range(n_suppliers): for j in range(n_customers): var_index = to_flat(i, j, n_rows=n_suppliers, n_cols=n_customers) + 1 expr += model.x[var_index] * costs[i, j] model.obj = pyo.Objective(expr=expr)
def to_model(self): model = pe.ConcreteModel() model.edges = edges = [(i, j) for i in range(self.n_cities) for j in range(i + 1, self.n_cities)] model.x = pe.Var(edges, domain=pe.Binary) model.obj = pe.Objective(expr=sum(model.x[i, j] * self.distances[i, j] for (i, j) in edges), sense=pe.minimize) model.eq_degree = pe.ConstraintList() model.eq_subtour = pe.ConstraintList() for i in range(self.n_cities): model.eq_degree.add( sum(model.x[min(i, j), max(i, j)] for j in range(self.n_cities) if i != j) == 2) return model
def Promo_Retailer_NFL(Model, run=True): """Enforcing certain promotions not to follow each other.""" if run: Promos_Nos = Globals.Promos_Nos_3 Model.Promo_Retailer_NFL_Constraints = pyo.ConstraintList() from itertools import combinations as cmb for Prod in range(len(Promos_Nos)): TPF = getattr(GLV.Model, f"TPR_FLAG_PPG_{Prod}") for comb in cmb(Promos_Nos[Prod], 2): for Promo in range(len(comb) - 1): # for Wk in range(Globals.Tot_Week - 1): Model.Promo_Retailer_NFL_Constraints.add( ( TPF[Wk, comb[Promo] - 1] * TPF[Wk + 1, comb[Promo + 1] - 1] ) + ( TPF[Wk, comb[Promo + 1] - 1] * TPF[Wk + 1, comb[Promo] - 1] ) == 0 )
def Facility(): m = pe.ConcreteModel() # Define variables m.x = pe.Var(range(N), within=pe.Binary) # Define uncertainty set m.uncset = ro.UncSet() m.uncset.cons = pe.ConstraintList() # Define uncertain parameters m.demand = ro.UncParam(range(M), nominal=demand, uncset=m.uncset) m.y = ro.AdjustableVar(range(N), range(M), bounds=(0, None), uncparams=[m.demand]) for i in range(M): m.uncset.cons.add(expr=pe.inequality(0.9*demand[i], m.demand[i], 1.1*demand[i])) # Add objective expr = 0 for i in range(N): for j in range(M): expr += cost_transport[i][j]*m.y[i, j] expr += cost_facility[i]*m.x[i] m.obj = pe.Objective(expr=expr, sense=pe.minimize) # Add constraints def sum_y_rule(m, j): return sum(m.y[i, j] for i in range(N)) == m.demand[j] m.sum_y = pe.Constraint(range(M), rule=sum_y_rule) def max_demand_rule(m, i): lhs = sum(m.y[i, j] for j in range(M)) return lhs <= max_dem[i]*m.x[i] m.max_dem = pe.Constraint(range(N), rule=max_demand_rule) # m.bound_x = pe.Constraint(expr=pe.quicksum(m.x[i] for i in m.x) >= 2) return m
def apply_dynamic_pyo(self, input, model: pyo.ConcreteModel, thetaacc, xacc, env_input_size, action): ''' :param costheta: gurobi variable containing the range of costheta values :param sintheta: gurobi variable containin the range of sintheta values :param input: :param gurobi_model: :param t: :return: ''' tau = self.tau # 0.001 # seconds between state updates x = input[0] x_dot = input[1] theta = input[2] theta_dot = input[3] z = pyo.Var(range(env_input_size), name=f"x_prime", within=pyo.Reals) model.add_component("x_prime", z) x_prime = x + tau * x_dot x_dot_prime = x_dot + tau * xacc theta_prime = theta + tau * theta_dot theta_dot_prime = theta_dot + tau * thetaacc model.dynamic_constraints = pyo.ConstraintList() model.dynamic_constraints.add(expr=z[0] == x_prime) model.dynamic_constraints.add(expr=z[1] == x_dot_prime) model.dynamic_constraints.add(expr=z[2] == theta_prime) model.dynamic_constraints.add(expr=z[3] == theta_dot_prime) return z
def define_optimization_connection_grid( self, optimization_problem: pyomo.core.base.PyomoModel.ConcreteModel, thermal_power_flow_solution: fledge.thermal_grid_models. ThermalPowerFlowSolution, thermal_grid_model: fledge.thermal_grid_models.ThermalGridModel, disconnect_electric_grid=True): # Obtain DER index. der_index = int( fledge.utils.get_index(thermal_grid_model.ders, der_name=self.der_name)) der = thermal_grid_model.ders[der_index] # Define connection constraints. if optimization_problem.find_component( 'der_connection_constraints') is None: optimization_problem.der_connection_constraints = pyo.ConstraintList( ) for timestep in self.timesteps: optimization_problem.der_connection_constraints.add( optimization_problem.der_thermal_power_vector[timestep, der] == -1.0 * optimization_problem.output_vector[ timestep, self.der_name, 'grid_thermal_power_cooling']) # Disable electric grid connection. if disconnect_electric_grid: optimization_problem.der_connection_constraints.add( 0.0 == optimization_problem.output_vector[ timestep, self.der_name, 'grid_electric_power'])
def define_optimization_connection_grid( self, optimization_problem: pyomo.core.base.PyomoModel.ConcreteModel, power_flow_solution: fledge.electric_grid_models.PowerFlowSolution, electric_grid_model: fledge.electric_grid_models. ElectricGridModelDefault): # Obtain DER index. der_index = int( fledge.utils.get_index(electric_grid_model.ders, der_name=self.der_name)) der = electric_grid_model.ders[der_index] # Define connection constraints. if optimization_problem.find_component( 'der_connection_constraints') is None: optimization_problem.der_connection_constraints = pyo.ConstraintList( ) for timestep in self.timesteps: optimization_problem.der_connection_constraints.add( optimization_problem.der_active_power_vector_change[ timestep, der] == self.active_power_nominal_timeseries.at[timestep] - np.real(power_flow_solution.der_power_vector[der_index])) optimization_problem.der_connection_constraints.add( optimization_problem.der_reactive_power_vector_change[timestep, der] == self.reactive_power_nominal_timeseries.at[timestep] - np.imag(power_flow_solution.der_power_vector[der_index]))
def test_passing_indexed_component_not_list(self): model = pyo.ConcreteModel() model.x = pyo.Var(bounds=(-5.0, 5.0)) model.S = pyo.Set(initialize=['A', 'B'], ordered=True) model.y = pyo.Var(model.S, bounds=(-100.0, 100.0)) model.obj_expr = pyo.Expression(expr=model.y['A']) model.obj = pyo.Objective(expr=model.obj_expr) x_points = [-5.0, 5.0] model.under_estimators = pyo.ConstraintList() for xp in x_points: m = 2 * xp b = -(xp ** 2) model.under_estimators.add(model.y['A'] >= m * model.x + b) model.con = pyo.Constraint(expr=model.y['A'] == 1 + model.y['B']) solver = pyo.SolverFactory('ipopt') lower, upper = coramin.domain_reduction.perform_obbt(model=model, solver=solver, varlist=model.y, update_bounds=True) self.assertAlmostEqual(pyo.value(model.x.lb), -5.0, delta=1e-6) self.assertAlmostEqual(pyo.value(model.x.ub), 5.0, delta=1e-6) self.assertAlmostEqual(pyo.value(model.y['A'].lb), -25.0, delta=1e-6) self.assertAlmostEqual(pyo.value(model.y['A'].ub), 100.0, delta=1e-6) self.assertAlmostEqual(pyo.value(model.y['B'].lb), -26.0, delta=1e-6) self.assertAlmostEqual(pyo.value(model.y['B'].ub), 99.0, delta=1e-6) self.assertAlmostEqual(lower[0], -25.0, delta=1e-6) self.assertAlmostEqual(upper[0], 100.0, delta=1e-6) self.assertAlmostEqual(lower[1], -26.0, delta=1e-6) self.assertAlmostEqual(upper[1], 99.0, delta=1e-6)
def set_convexity_constraints(self): self.model.convexity_constraint = pe.ConstraintList() for commodity in self.commodities: if int(commodity) > 0: # TODO não depender desse código self.model.convexity_constraint.add(expr=sum( self.model.var_lambda[dk] for dk in self.model.DK if dk[0] == commodity) == 1)
def pyomo_init_model(self, time=None): """ Initializes the Pyomo model, adds modes for power/energy control and adds the DOF variables as needed. """ if time is None: # times year = 8760 # h t_span = year t_min = 0 time = list(range(t_min, t_min + t_span)) # Define model and add time self.model = pyo.ConcreteModel() self.model.constraint_ID = "constraints" self.model.time = time self.time = time # Initialize constraint list if not hasattr(self.model, self.model.constraint_ID): setattr(self.model, self.model.constraint_ID, pyo.ConstraintList()) for component in self.components: component.initializePyomoVariables(self.model)
def Portfolio(): m = pe.ConcreteModel() m.cons = pe.ConstraintList() N = 5 index = list(range(N)) mean = [0.1, 0.3, 0.5, 0.7, 0.4] m.x = pe.Var(index, bounds=(0, 1)) m.z = pe.Var(within=pe.PositiveReals) m.U = ro.UncSet() m.r = ro.UncParam(index, uncset=m.U, nominal=mean) r = m.r expr = 0 for i in index: expr += (m.r[i] - mean[i])**2 m.U.cons = pe.Constraint(expr=expr <= 0.0005) m.Obj = pe.Objective(expr=m.z, sense=pe.maximize) # x0 = m.x[0] # expr = x0*3 expr = sum([m.x[i] for i in index]) == 1 m.cons.add(expr) m.cons.add(sum([r[i] * m.x[i] for i in index]) >= m.z) return m
def constructGP_infeas(self, model): ''' Construct GP for infeasibility step ''' # number of outputs model.outind = range(self.OutputDimension - 1) model.outcon = pe.ConstraintList() conrhs = self.scaleconrhs(self.prob.conrhs, self.prob.yscaler) # slack model.sl = pe.Var(model.outind, within=pe.Reals, bounds=(0, 0.1)) # for constraints for k in range(1, self.OutputDimension): f = sum( [self.coef[:, k][i] * model.k[i] for i in range(len(model.k))]) - model.sl[k - 1] ConType = self.prob.contype[k - 1] if ConType == 'E': model.outcon.add(f <= conrhs[k - 1]) model.outcon.add(f >= conrhs[k - 1]) elif ConType == 'L': model.outcon.add(f <= conrhs[k - 1]) elif ConType == 'G': model.outcon.add(f >= conrhs[k - 1]) # objective - minimize the sum of slack model.obj = pe.Objective( expr=sum([model.sl[k] for k in range(self.OutputDimension - 1)])) return model
def initialize_model(m, disp=False): """ Initializes drop """ #Fixed Variables m.bounds = pe.ConstraintList() for i in _fixvar: try: m.bounds.add(expr=m.getattr(i) == m.getattr(m).value) except: pass m.Obj = pe.Objective(expr=pow(5 - m.dD, 2)) # Solver opt = SolverFactory("ipopt") opt.solve(m, tee=disp) m.del_component(m.bounds) m.del_component(m.Obj) return m
def Create_Relaxed_Model(self): """Create the relaxed model, without any subtour elimination constraints.""" node_set = set(range(len(self.points))) edge_set = set((i, j) for i in node_set for j in node_set if i < j) cost = {e: tsputil.distance(points[e[0]], points[e[1]]) for e in edge_set} # Create the model and sets m = pe.ConcreteModel() m.node_set = pe.Set(initialize=node_set) m.edge_set = pe.Set(initialize=edge_set, dimen=2) # Define variables m.x = pe.Var(m.edge_set, bounds=(0, 1), domain=pe.Reals) # Objective def obj_rule(m): return sum(m.x[e] * cost[e] for e in m.edge_set) m.OBJ = pe.Objective(rule=obj_rule, sense=pe.minimize) # Add the n-1 constraint def mass_balance_rule(m, v): return sum(m.x[(v, i)] for i in node_set if (v, i) in edge_set) + sum(m.x[(i, v)] for i in node_set if (i, v) in edge_set) == 2 m.mass_balance = pe.Constraint(node_set, rule=mass_balance_rule) # Empty constraint list for subtour elimination constraints # This is where the generated rows will go m.subtour_elimination_cc = pe.ConstraintList() self.m = m
def access_obj_values(): import pyomo.environ as pyo from pyomo.opt import SolverFactory # Create a solver opt = SolverFactory('glpk') # A simple model with binary variables and # an empty constraint list. model = pyo.ConcreteModel() model.n = pyo.Param(default=4) model.x = pyo.Var(pyo.RangeSet(model.n), within=pyo.Binary) # Note: model.x creates an interable using rangeset and returns # 4 values of x indexed using the vals created in the rangeset funct. [print(model.x[i]) for i in range(1,5)] def o_rule(model): return summation(model.x) model.o = pyo.Objective(rule=o_rule) model.c = pyo.ConstraintList() results = opt.solve(model) # Print All Variables for v in model.component_objects(pyo.Var, active=True): print("Variable",v) # Print All Values Assigned to variables for index in v: print (" ",index, pyo.value(v[index])) # Print All Parameters for parmobject in model.component_objects(pyo.Param, active=True): nametoprint = str(str(parmobject.name)) print ("Parameter ", nametoprint) # doctest: +SKIP for index in parmobject: vtoprint = pyo.value(parmobject[index]) print (" ",index, vtoprint) # doctest: +SKIP
def test_quad(self): model = pyo.ConcreteModel() model.x = pyo.Var(bounds=(-5.0, 5.0)) model.y = pyo.Var(bounds=(-100.0, 100.0)) model.obj_expr = pyo.Expression(expr=model.y) model.obj = pyo.Objective(expr=model.obj_expr) x_points = [-5.0, 5.0] model.under_estimators = pyo.ConstraintList() for xp in x_points: m = 2*xp b = -(xp**2) model.under_estimators.add(model.y >= m*model.x + b) solver = pyo.SolverFactory('ipopt') (lower, upper) = coramin.domain_reduction.perform_obbt(model=model, solver=solver, varlist=[model.x, model.y], update_bounds=True) self.assertAlmostEqual(pyo.value(model.x.lb), -5.0, delta=1e-6) self.assertAlmostEqual(pyo.value(model.x.ub), 5.0, delta=1e-6) self.assertAlmostEqual(pyo.value(model.y.lb), -25.0, delta=1e-6) self.assertAlmostEqual(pyo.value(model.y.ub), 100.0, delta=1e-6) self.assertAlmostEqual(lower[0], -5.0, delta=1e-6) self.assertAlmostEqual(upper[0], 5.0, delta=1e-6) self.assertAlmostEqual(lower[1], -25.0, delta=1e-6) self.assertAlmostEqual(upper[1], 100.0, delta=1e-6)
def _populate_block_with_constraints(self, b): b.x = pyo.Var() b.c = pyo.Constraint(expr=b.x == 1) b.C1 = pyo.Constraint([1], rule=lambda m, i: m.x == 1) b.C2 = pyo.Constraint([1], rule=lambda m, i: m.x == 1) b.C3 = pyo.ConstraintList() b.C3.add(b.x == 1)
def __init__(self, geo, drillstring, cost_maint, xfin, deltax=200, xstart=0, method='det', alpha=0.5, mip=True, penalty=False): self.geology = geo self.drillstring = drillstring self.cost_maint = cost_maint # TODO: should be part of DrillString? self.xstart = xstart self.xfin = xfin self.method = method self.alpha = alpha self.mip = mip self.penalty = penalty self.eps = 0.0001 self.get_segments(xstart, xfin, deltax) self.m = p.ConcreteModel() self.m.cons = p.ConstraintList() self.add_vars(mip) self.add_rop(mip) self.add_deg() self.add_obj()
def test_callback(self): m = pe.ConcreteModel() m.x = pe.Var(bounds=(0, 4)) m.y = pe.Var(within=pe.Integers, bounds=(0, None)) m.obj = pe.Objective(expr=2*m.x + m.y) m.cons = pe.ConstraintList() def _add_cut(xval): m.x.value = xval return m.cons.add(m.y >= taylor_series_expansion((m.x - 2)**2)) _add_cut(0) _add_cut(4) opt = Gurobi() opt.set_instance(m) opt.set_gurobi_param('PreCrush', 1) opt.set_gurobi_param('LazyConstraints', 1) def _my_callback(cb_m, cb_opt, cb_where): if cb_where == gurobipy.GRB.Callback.MIPSOL: cb_opt.cbGetSolution(vars=[m.x, m.y]) if m.y.value < (m.x.value - 2)**2 - 1e-6: cb_opt.cbLazy(_add_cut(m.x.value)) opt.set_callback(_my_callback) opt.solve(m) self.assertAlmostEqual(m.x.value, 1) self.assertAlmostEqual(m.y.value, 1)
def test_pw_exp(self): m = pe.ConcreteModel() m.p = pe.Param(initialize=-1, mutable=True) m.x = pe.Var(bounds=(-1, 1)) m.y = pe.Var() m.z = pe.Var(bounds=(0, None)) m.c = coramin.relaxations.PWUnivariateRelaxation() m.c.build(x=m.x, aux_var=m.y, relaxation_side=coramin.utils.RelaxationSide.BOTH, shape=coramin.utils.FunctionShape.CONVEX, f_x_expr=pe.exp(m.x)) m.c.add_partition_point(-0.25) m.c.add_partition_point(0.25) m.c.rebuild() m.c2 = pe.ConstraintList() m.c2.add(m.z >= m.y - m.p) m.c2.add(m.z >= m.p - m.y) m.obj = pe.Objective(expr=m.z) opt = pe.SolverFactory('glpk') for xval in [-1, -0.5, 0, 0.5, 1]: pval = math.exp(xval) m.x.fix(xval) m.p.value = pval res = opt.solve(m, tee=False) self.assertTrue(res.solver.termination_condition == pe.TerminationCondition.optimal) self.assertAlmostEqual(m.y.value, m.p.value, 6)
def createRelaxedModel(self): """Create the relaxed model, without any subtour elimination constraints.""" df = self.df node_set = set(list(df.startNode) + list(df.destNode)) # Create the model and sets m = pe.ConcreteModel() df.set_index(['startNode', 'destNode'], inplace=True) edge_set = df.index.unique() m.edge_set = pe.Set(initialize=edge_set, dimen=2) m.node_set = pe.Set(initialize=node_set) # Define variables m.Y = pe.Var(m.edge_set, domain=pe.Binary) # Objective def obj_rule(m): return sum(m.Y[e] * df.ix[e, 'dist'] for e in m.edge_set) m.OBJ = pe.Objective(rule=obj_rule, sense=pe.minimize) # Add the n-1 constraint def simple_const_rule(m): return sum(m.Y[e] for e in m.edge_set) == len(node_set) - 1 m.simpleConst = pe.Constraint(rule=simple_const_rule) #Empty constraint list for subtour elimination constraints m.ccConstraints = pe.ConstraintList() self.m = m
def subSolve(cap, PF,PTDF,line): # initialize sub sub = pyo.ConcreteModel() sub.N = pyo.Set(ordered=True, initialize=[0, 1, 2, 3]) # Set of the 4 nodes in our system sub.Pup = pyo.Var(sub.N,domain=pyo.NonNegativeReals) # Make 4 P-variables that represent increased power generation at each node sub.Pdown = pyo.Var(sub.N, domain=pyo.NonNegativeReals) # Make 4 P-variables that represent decreased power generation at each node sub.constraints = pyo.ConstraintList() # Define the list of all constraints # Define the objective function to be the sum of change in power production def ObjectiveFunction(sub): return sum(sub.Pup[i] + sub.Pdown[i] for i in sub.N) sub.obj = pyo.Objective(rule=ObjectiveFunction, sense=pyo.minimize) # Load balance constraint sub.constraints.add(sum(sub.Pup[i]-sub.Pdown[i] for i in sub.N) == 0) # Constraint for not violation of line 0-2 lhs=-cap - PF[0, 2] mid= sum((sub.Pup[i] - sub.Pdown[i])*PTDF[line,i] for i in sub.N) rhs= cap - PF[0, 2] sub.constraints.add(pyo.inequality(lhs,mid,rhs)) # Solve model opt = SolverFactory("gurobi") sub.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT) sub.rc = pyo.Suffix(direction=pyo.Suffix.IMPORT) results = opt.solve(sub, load_solutions=True) return sub
def set_input(self, master_vars, tol=1e-6, comm = None): """ It is very important for master_vars to be in the same order for every process. Parameters ---------- master_vars tol """ self.comm = None if comm is not None: self.comm = comm else: self.comm = MPI.COMM_WORLD self.num_subproblems_by_rank = np.zeros(self.comm.Get_size()) del self.cuts self.cuts = pe.ConstraintList() self.subproblems = list() self.master_etas = list() self.complicating_vars_maps = list() self.master_vars = list(master_vars) self.master_vars_indices = pe.ComponentMap() for i, v in enumerate(self.master_vars): self.master_vars_indices[v] = i self.tol = tol self.subproblem_solvers = list() self.all_master_etas = list() self._subproblem_ndx_map = dict()
def set_partitioning_constraints(self, scheduled_trips: list, initial_variables_by_commodity): self.model.partitioning_constraint = pe.ConstraintList() for trip in scheduled_trips: self.model.partitioning_constraint.add(expr=sum( self.model.var_lambda[dk] for dk in self.model.DK if initial_variables_by_commodity[dk[0]][int( dk[1])].scheduled_trips.__contains__(trip)) == 1)
def __init__( self, demand, t_max=30, a_max=3, initial_inventory={ 1: 0, 2: 36 }, fixed_order_cost=225, variable_order_cost=650, holding_cost=130, emergency_procurement_cost=3250, wastage_cost=650, M=100, additional_fifo_constraints=True, weekly_policy=False, shelf_life_at_arrival_dist=[0, 0, 1], ): self.model = pyo.ConcreteModel() # Check that `shelf_life_at_arrival_dist` sums to 1 and had right # number of elements assert ( len(shelf_life_at_arrival_dist) == a_max ), "`shelf_life_at_arrival_dist` must have number of elements equal to `a_max`" assert (np.sum(shelf_life_at_arrival_dist) == 1 ), "`shelf_life_at_arrival_dist` must sum to 1" self.shelf_life_at_arrival_dist = shelf_life_at_arrival_dist self.model.T = pyo.RangeSet(1, t_max) self.model.A = pyo.RangeSet(1, a_max) self.weekly_policy = weekly_policy if self.weekly_policy: self.model.Wd = pyo.RangeSet(0, 6) self.model.M = M # Hydra doesn't support integer keys so convert here if needed self.model.initial_inventory = { int(k): v for k, v in initial_inventory.items() } self.additional_fifo_constraints = additional_fifo_constraints self.model.demand = demand self.model.CssF = fixed_order_cost self.model.CssP = variable_order_cost self.model.CssH = holding_cost self.model.CssE = emergency_procurement_cost self.model.CssW = wastage_cost self.model.cons = pyo.ConstraintList()
def createModel(self): self.m = pe.ConcreteModel() # Create set self.m.arc_set = pe.Set(initialize=self.df.index, dimen=2) # Create variable # don't use dimen parameter here, only use it when creating set self.m.Y = pe.Var(self.m.arc_set, domain=pe.Binary) # pe.Binary # Create obj. In the function, only m doesn't need self since this is what we pass in def obj_rule(m): return sum(self.df.loc[e, "dist"] * m.Y[e] for e in self.m.arc_set) self.m.OBJ = pe.Objective(rule=obj_rule, sense=pe.minimize) # Create constraint rules def tot_edge_rule(m): return sum(m.Y[e] for e in m.arc_set) == len(self.node) - 1 self.m.TotEdge = pe.Constraint(rule=tot_edge_rule) def convertYsToNetworkx(m): ans = networkx.Graph() # get the edges that have value 1 pick_edges = [e for e in m.arc_set if m.Y[e].value == 1.0] ans.add_edges_from(pick_edges) return ans def createConstForCC(m, cc): return sum(m.Y[e] for e in m.arc_set if (e[0] in cc.nodes()) and (e[1] in cc.nodes())) <= len(cc.nodes()) - 1 self.m.ccConstraints = pe.ConstraintList() done = False while done == False: solver = pyomo.opt.SolverFactory("cplex") results = solver.solve( self.m, tee=True, keepfiles=False, options_string= "mip_tolerances_integrality=1e-9 mip_tolerances_mipgap=0") graph = convertYsToNetworkx(self.m) # in graph theory, connected component can be thinked as closed communication class in DTMC # so ccs contains all the connected components (subgraphs) objects. ccs = list(networkx.connected_component_subgraphs(graph)) for cc in ccs: # this cc is one connected component, which is a graph object. print createConstForCC(self.m, cc) # Now we want to add this constraint to our model, however, using traditional way is very complex for several reasons: # add a expression self.m.ccConstraints.add(createConstForCC(self.m, cc)) # stop rule: when the connected component is itself the whole graph if (ccs[0].number_of_nodes() == len(self.node)): done = True