def test_double_sided_ineq(self): m = ConcreteModel() m.s = Set(initialize=[1.0,2.0,3.0,4.0,5.0]) m.vmin = Param(m.s, initialize=lambda m,i: i) m.vmax = Param(m.s, initialize=lambda m,i: i**2) m.v = Var(m.s) def _con(m, i): return inequality(m.vmin[i]**2, m.v[i], m.vmax[i]**2) m.con = Constraint(m.s, rule=_con) OUT = io.StringIO() for i in m.s: OUT.write(str(_con(m,i))) OUT.write("\n") display(m.con, ostream=OUT) reference="""1.0 <= v[1.0] <= 1.0 4.0 <= v[2.0] <= 16.0 9.0 <= v[3.0] <= 81.0 16.0 <= v[4.0] <= 256.0 25.0 <= v[5.0] <= 625.0 con : Size=5 Key : Lower : Body : Upper 1.0 : 1.0 : None : 1.0 2.0 : 4.0 : None : 16.0 3.0 : 9.0 : None : 81.0 4.0 : 16.0 : None : 256.0 5.0 : 25.0 : None : 625.0 """ self.assertEqual(OUT.getvalue(), reference)
def farmer_lp(solver="cplex"): # concrete model instance = ConcreteModel(name="Farmer_LP") # set instance.plants = ("wheat", "corn", "beet") instance.action = ("buy", "sell") instance.price = ("high", "low") # decision variables instance.area = Var(instance.plants, within=NonNegativeReals) instance.wheat_act = Var(instance.action, within=NonNegativeReals) instance.corn_act = Var(instance.action, within=NonNegativeReals) instance.beet_price = Var(instance.price, bounds=(0, 6000), within=NonNegativeReals) # constraint def area_rule(model): return sum(model.area[pdx] for pdx in model.plants) <= 500 instance.area_constraint = Constraint(rule=area_rule) # constraint def min_wheat_rule(model): return (2.5 * model.area['wheat'] + model.wheat_act['buy'] - model.wheat_act['sell'] >= 200) instance.min_wheat_constraint = Constraint(rule=min_wheat_rule) # constraint def min_corn_rule(model): return (3 * model.area['corn'] + model.corn_act['buy'] - model.corn_act['sell'] >= 240) instance.min_corn_constraint = Constraint(rule=min_corn_rule) # constraint def beet_price_rule(model): return (model.beet_price['high'] + model.beet_price['low'] <= 20 * model.area['beet']) instance.beat_price_constraint = Constraint(rule=beet_price_rule) # objective def min_cost_rule(model): grow_cost = (150 * model.area['wheat'] + 230 * model.area['corn'] + 260 * model.area['beet']) wheat_cost = (238 * model.wheat_act['buy'] - 170 * model.wheat_act['sell']) corn_cost = (210 * model.corn_act['buy'] - 150 * model.corn_act['sell']) beet_cost = -(36 * model.beet_price['high'] + 10 * model.beet_price['low']) return grow_cost + wheat_cost + corn_cost + beet_cost instance.min_cost_objective = Objective(rule=min_cost_rule, sense=minimize) # solve opt = SolverFactory(solver) results = opt.solve(instance) instance.solutions.load_from(results) display(instance) print("LP objective: {}".format(-instance.min_cost_objective()))