Example #1
0
    def test_solve7(self):
        #
        # Test that solution values are writen with appropriate
        # quotations in results
        #
        model = ConcreteModel()
        model.y = Var(bounds=(-1, 1))
        model.A = RangeSet(1, 4)
        model.B = Set(initialize=['A B', 'C,D', 'E'])
        model.x = Var(model.A, model.B, bounds=(-1, 1))

        def obj_rule(model):
            return sum_product(model.x)

        model.obj = Objective(rule=obj_rule)

        def c_rule(model):
            expr = model.y
            for i in model.A:
                for j in model.B:
                    expr += i * model.x[i, j]
            return expr == 0

        model.c = Constraint(rule=c_rule)
        opt = SolverFactory('glpk')
        results = opt.solve(model, symbolic_solver_labels=True)
        #model.display()
        model.solutions.store_to(results)
        results.write(filename=join(currdir, 'solve7.out'), format='json')
        self.assertMatchesJsonBaseline(join(currdir, "solve7.out"),
                                       join(currdir, "solve7.txt"),
                                       tolerance=1e-4)
Example #2
0
    def test_stats3(self):
        model = ConcreteModel()
        model.x = Var([1, 2])

        def obj_rule(model, i):
            return sum_product(model.x)

        model.obj = Objective([1, 2], rule=obj_rule)

        def c_rule(model, i):
            expr = 0
            for j in [1, 2]:
                expr += j * model.x[j]
            return expr == 0

        model.c = Constraint([1, 2], rule=c_rule)
        #
        model.B = Block()
        model.B.x = Var([1, 2])
        model.B.o = ObjectiveList()
        model.B.o.add(model.B.x[1])
        model.B.o.add(model.B.x[2])
        model.B.c = ConstraintList()
        model.B.c.add(model.x[1] == 0)
        model.B.c.add(model.x[2] == 0)
        self.assertEqual(model.nvariables(), 4)
        self.assertEqual(model.nobjectives(), 4)
        self.assertEqual(model.nconstraints(), 4)
Example #3
0
    def test_expr5(self):
        model = ConcreteModel()
        model.A = Set(initialize=[1, 2, 3], doc='set A')
        model.B = Param(model.A,
                        initialize={
                            1: 100,
                            2: 200,
                            3: 300
                        },
                        doc='param B',
                        mutable=True)
        model.C = Param(initialize=3, doc='param C', mutable=True)
        model.x = Var(model.A, doc='var x')
        model.y = Var(doc='var y')
        model.o = Objective(expr=model.y, doc='obj o')
        model.c1 = Constraint(expr=model.x[1] >= 0, doc='con c1')

        def c2_rule(model, a):
            return model.B[a] * model.x[a] <= 1

        model.c2 = Constraint(model.A, doc='con c2', rule=c2_rule)
        model.c3 = ConstraintList(doc='con c3')
        model.c3.add(model.y <= 0)
        #
        OUTPUT = open(join(currdir, "test_expr5.out"), "w")
        model.pprint(ostream=OUTPUT)
        OUTPUT.close()
        _out, _txt = join(currdir,
                          "test_expr5.out"), join(currdir, "test_expr5.txt")
        self.assertTrue(cmp(_out, _txt),
                        msg="Files %s and %s differ" % (_out, _txt))
Example #4
0
 def test_solve7(self):
     #
     # Test that solution values are writen with appropriate
     # quotations in results
     #
     model = ConcreteModel()
     model.y = Var(bounds=(-1,1))
     model.A = RangeSet(1,4)
     model.B = Set(initialize=['A B', 'C,D', 'E'])
     model.x = Var(model.A, model.B, bounds=(-1,1))
     def obj_rule(model):
         return sum_product(model.x)
     model.obj = Objective(rule=obj_rule)
     def c_rule(model):
         expr = model.y
         for i in model.A:
             for j in model.B:
                 expr += i*model.x[i,j]
         return expr == 0
     model.c = Constraint(rule=c_rule)
     opt = SolverFactory('glpk')
     results = opt.solve(model, symbolic_solver_labels=True)
     #model.display()
     model.solutions.store_to(results)
     results.write(filename=join(currdir,'solve7.out'), format='json')
     with open(join(currdir,"solve7.out"), 'r') as out, \
         open(join(currdir,"solve7.txt"), 'r') as txt:
         self.assertStructuredAlmostEqual(json.load(txt), json.load(out),
                                          abstol=1e-4,
                                          allow_second_superset=True)
Example #5
0
    def test_add_block_containing_multiple_constraints(self):
        model = ConcreteModel()
        model.X = Var(within=Binary)

        opt = SolverFactory("cplex", solver_io="python")
        opt._set_instance(model)

        self.assertEqual(opt._solver_model.linear_constraints.get_num(), 0)

        model.B = Block()
        model.B.C1 = Constraint(expr=model.X == 1)
        model.B.C2 = Constraint(expr=model.X <= 1)
        model.B.C3 = Constraint(expr=model.X >= 1)

        con_interface = opt._solver_model.linear_constraints
        with unittest.mock.patch.object(
                con_interface, "add",
                wraps=con_interface.add) as wrapped_add_call:
            opt._add_block(model.B)

            self.assertEqual(wrapped_add_call.call_count, 1)
            self.assertEqual(
                wrapped_add_call.call_args,
                ({
                    "lin_expr": [[[0], (1, )], [[0], (1, )], [[0], (1, )]],
                    "names": ["x2", "x3", "x4"],
                    "range_values": [0.0, 0.0, 0.0],
                    "rhs": [1.0, 1.0, 1.0],
                    "senses": ["E", "L", "G"],
                }, ),
            )

        self.assertEqual(opt._solver_model.linear_constraints.get_num(), 3)
Example #6
0
def OT(H1, H2):
    n = len(H1)
    
    mod = ConcreteModel()
    
    mod.I = RangeSet(0,n-1)
    mod.J = RangeSet(0,n-1)
    
    mod.x = Var(mod.I, mod.J, within=NonNegativeReals)
    
    mod.obj = Objective(expr=sum(D(H1[i], H2[j]) * mod.x[i,j] for i,j in mod.x))
    
    mod.A = Constraint(mod.I,
                       rule = lambda m, i: sum(m.x[i,j] for j in m.J) == 1)

    mod.B = Constraint(mod.J,
                       rule = lambda m, j: sum(m.x[i,j] for i in m.I) == 1)
    

    SolverFactory('gurobi').solve(mod, tee=True)
    
    ColMap = []

    for i in mod.I:
        for j in mod.J:
            if mod.x[i,j]() > 0.5:
                ColMap.append(j)
                
    return ColMap
Example #7
0
    def test_expr1_option(self):
        """Test expr option"""
        model = ConcreteModel()
        model.B = RangeSet(1, 4)
        model.x = Var(model.B, initialize=2)
        ans = 0
        for i in model.B:
            ans = ans + model.x[i]
        model.obj = Objective(expr=ans)

        self.assertEqual(model.obj(), 8)
        self.assertEqual(value(model.obj), 8)
        self.assertEqual(value(model.obj._data[None]), 8)
Example #8
0
    def test_rule5(self):
        """Test rule option"""
        model = ConcreteModel()
        model.B = RangeSet(1,4)
        def f(model):
            ans=0
            for i in model.B:
                ans = ans + model.x[i]
            return (ans, 1)
        model.x = Var(model.B, initialize=2)
        model.c = Constraint(rule=f)

        self.assertEqual(model.c(), 8)
        self.assertEqual(value(model.c.body), 8)
Example #9
0
    def test_rule5(self):
        """Test rule option"""
        model = ConcreteModel()
        model.B = RangeSet(1,4)
        def f(model):
            ans=0
            for i in model.B:
                ans = ans + model.x[i]
            return (ans, 1)
        model.x = Var(model.B, initialize=2)
        model.c = Constraint(rule=f)

        self.assertEqual(model.c(), 8)
        self.assertEqual(value(model.c.body), 8)
Example #10
0
    def test_stats4(self):
        model = ConcreteModel()
        model.x = Var([1])

        model.B = Block()
        model.B.x = Var([1, 2, 3])
        model.B.o = ObjectiveList()
        model.B.o.add(model.B.x[1])
        model.B.c = ConstraintList()
        model.B.c.add(model.B.x[1] == 0)
        model.B.c.add(model.B.x[2] == 0)
        model.B.c.add(model.B.x[3] == 0)
        self.assertEqual(model.nvariables(), 4)
        self.assertEqual(model.nobjectives(), 1)
        self.assertEqual(model.nconstraints(), 3)
        model.clear()
        self.assertEqual(model.nvariables(), 0)
        self.assertEqual(model.nobjectives(), 0)
        self.assertEqual(model.nconstraints(), 0)
@author: changlinli
"""

from pyomo.environ import ConcreteModel, AbstractModel, Param, RangeSet, Set, BuildAction, Var, Objective, Piecewise, minimize, value
from pyomo.environ import NonNegativeReals, Integers, Binary, PositiveIntegers
from pyomo.opt import SolverStatus, TerminationCondition
from pyomo.opt import SolverFactory

v = {}
v[1, 1] = 9
v[2, 2] = 16
v[3, 3] = 25
model = ConcreteModel()
model.A = RangeSet(1, 3)
model.B = RangeSet(1, 3)
model.P = Param(model.A, model.B)
model.S = Param(model.A, model.B, initialize=v, default=0)


def s_validate(model, v, i):
    return v > 3.14159


model.S = Param(model.A, validate=s_validate)


def s_init(model, i, j):
    if i == j:
        return i * i
    else:
Example #12
0
def build_column(min_trays, max_trays, xD, xB):
    """Builds the column model."""
    m = ConcreteModel('benzene-toluene column')
    m.comps = Set(initialize=['benzene', 'toluene'])
    min_T, max_T = 300, 400
    max_flow = 500
    m.T_feed = Var(doc='Feed temperature [K]',
                   domain=NonNegativeReals,
                   bounds=(min_T, max_T),
                   initialize=368)
    m.feed_vap_frac = Var(doc='Vapor fraction of feed',
                          initialize=0,
                          bounds=(0, 1))
    m.feed = Var(m.comps,
                 doc='Total component feed flow [mol/s]',
                 initialize=50)

    m.condens_tray = max_trays
    m.feed_tray = int(round(max_trays / 2))
    m.reboil_tray = 1
    m.distillate_purity = xD
    m.bottoms_purity = xB

    m.trays = RangeSet(max_trays, doc='Set of potential trays')
    m.conditional_trays = Set(initialize=m.trays -
                              [m.condens_tray, m.feed_tray, m.reboil_tray],
                              doc="Trays that may be turned on and off.")
    m.tray = Disjunct(m.conditional_trays, doc='Disjunct for tray existence')
    m.no_tray = Disjunct(m.conditional_trays, doc='Disjunct for tray absence')

    @m.Disjunction(m.conditional_trays, doc='Tray exists or does not')
    def tray_no_tray(b, t):
        return [b.tray[t], b.no_tray[t]]

    m.minimum_num_trays = Constraint(
        expr=sum(m.tray[t].indicator_var
                 for t in m.conditional_trays) + 1  # for feed tray
        >= min_trays)

    m.x = Var(m.comps,
              m.trays,
              doc='Liquid mole fraction',
              bounds=(0, 1),
              domain=NonNegativeReals,
              initialize=0.5)
    m.y = Var(m.comps,
              m.trays,
              doc='Vapor mole fraction',
              bounds=(0, 1),
              domain=NonNegativeReals,
              initialize=0.5)
    m.L = Var(m.comps,
              m.trays,
              doc='component liquid flows from tray in kmol',
              domain=NonNegativeReals,
              bounds=(0, max_flow),
              initialize=50)
    m.V = Var(m.comps,
              m.trays,
              doc='component vapor flows from tray in kmol',
              domain=NonNegativeReals,
              bounds=(0, max_flow),
              initialize=50)
    m.liq = Var(m.trays,
                domain=NonNegativeReals,
                doc='liquid flows from tray in kmol',
                initialize=100,
                bounds=(0, max_flow))
    m.vap = Var(m.trays,
                domain=NonNegativeReals,
                doc='vapor flows from tray in kmol',
                initialize=100,
                bounds=(0, max_flow))
    m.B = Var(m.comps,
              domain=NonNegativeReals,
              doc='bottoms component flows in kmol',
              bounds=(0, max_flow),
              initialize=50)
    m.D = Var(m.comps,
              domain=NonNegativeReals,
              doc='distillate component flows in kmol',
              bounds=(0, max_flow),
              initialize=50)
    m.bot = Var(domain=NonNegativeReals,
                initialize=50,
                bounds=(0, 100),
                doc='bottoms flow in kmol')
    m.dis = Var(domain=NonNegativeReals,
                initialize=50,
                doc='distillate flow in kmol',
                bounds=(0, 100))
    m.reflux_ratio = Var(domain=NonNegativeReals,
                         bounds=(0.5, 4),
                         doc='reflux ratio',
                         initialize=0.8329)
    m.reboil_ratio = Var(domain=NonNegativeReals,
                         bounds=(0.5, 4),
                         doc='reboil ratio',
                         initialize=0.9527)
    m.reflux_frac = Var(domain=NonNegativeReals,
                        bounds=(0, 1 - 1E-6),
                        doc='reflux fractions')
    m.boilup_frac = Var(domain=NonNegativeReals,
                        bounds=(0, 1 - 1E-6),
                        doc='boilup fraction')

    m.partial_cond = Disjunct()
    m.total_cond = Disjunct()
    m.condenser_choice = Disjunction(expr=[m.partial_cond, m.total_cond])

    for t in m.conditional_trays:
        _build_conditional_tray_mass_balance(m, t, m.tray[t], m.no_tray[t])
    _build_feed_tray_mass_balance(m)
    _build_condenser_mass_balance(m)
    _build_reboiler_mass_balance(m)

    @m.Constraint(m.comps,
                  doc="Bottoms flow is equal to liquid leaving reboiler.")
    def bottoms_mass_balance(m, c):
        return m.B[c] == m.L[c, m.reboil_tray]

    @m.Constraint()
    def boilup_frac_defn(m):
        return m.bot == (1 - m.boilup_frac) * m.liq[m.reboil_tray + 1]

    @m.Constraint()
    def reflux_frac_defn(m):
        return m.dis == (1 - m.reflux_frac) * (m.vap[m.condens_tray - 1] -
                                               m.vap[m.condens_tray])

    @m.Constraint(m.trays)
    def liquid_sum(m, t):
        return sum(m.L[c, t] for c in m.comps) == m.liq[t]

    @m.Constraint(m.trays)
    def vapor_sum(m, t):
        return sum(m.V[c, t] for c in m.comps) == m.vap[t]

    m.bottoms_sum = Constraint(expr=sum(m.B[c] for c in m.comps) == m.bot)
    m.distil_sum = Constraint(expr=sum(m.D[c] for c in m.comps) == m.dis)
    """Phase Equilibrium relations"""
    m.Kc = Var(m.comps,
               m.trays,
               doc='Phase equilibrium constant',
               domain=NonNegativeReals,
               initialize=1,
               bounds=(0, 1000))
    m.T = Var(m.trays,
              doc='Temperature [K]',
              domain=NonNegativeReals,
              bounds=(min_T, max_T))

    @m.Constraint(m.trays)
    def monotonoic_temperature(_, t):
        return m.T[t] >= m.T[t + 1] if t < max_trays else Constraint.Skip

    m.P = Var(doc='Pressure [bar]', bounds=(0, 5))
    m.P.fix(1.01)
    m.T_ref = 298.15
    m.gamma = Var(m.comps,
                  m.trays,
                  doc='liquid activity coefficent of component on tray',
                  domain=NonNegativeReals,
                  bounds=(0, 10),
                  initialize=1)
    m.Pvap = Var(
        m.comps,
        m.trays,
        doc='pure component vapor pressure of component on tray in bar',
        domain=NonNegativeReals,
        bounds=(1E-3, 5),
        initialize=0.4)
    m.Pvap_X = Var(
        m.comps,
        m.trays,
        doc='Related to fraction of critical temperature (1 - T/Tc)',
        bounds=(0.25, 0.5),
        initialize=0.4)

    m.pvap_const = {
        'benzene': {
            'A': -6.98273,
            'B': 1.33213,
            'C': -2.62863,
            'D': -3.33399,
            'Tc': 562.2,
            'Pc': 48.9
        },
        'toluene': {
            'A': -7.28607,
            'B': 1.38091,
            'C': -2.83433,
            'D': -2.79168,
            'Tc': 591.8,
            'Pc': 41.0
        }
    }

    for t in m.conditional_trays:
        _build_tray_phase_equilibrium(m, t, m.tray[t])
    m.feed_tray_phase_eq = Block()
    m.reboiler_phase_eq = Block()
    m.condenser_phase_eq = Block()
    _build_tray_phase_equilibrium(m, m.feed_tray, m.feed_tray_phase_eq)
    _build_tray_phase_equilibrium(m, m.reboil_tray, m.reboiler_phase_eq)
    _build_tray_phase_equilibrium(m, m.condens_tray, m.condenser_phase_eq)

    m.H_L = Var(m.comps,
                m.trays,
                bounds=(0.1, 16),
                doc='Liquid molar enthalpy of component in tray (kJ/mol)')
    m.H_V = Var(m.comps,
                m.trays,
                bounds=(30, 16 + 40),
                doc='Vapor molar enthalpy of component in tray (kJ/mol)')
    m.H_L_spec_feed = Var(
        m.comps,
        doc='Component liquid molar enthalpy in feed [kJ/mol]',
        initialize=0,
        bounds=(0.1, 16))
    m.H_V_spec_feed = Var(
        m.comps,
        doc='Component vapor molar enthalpy in feed [kJ/mol]',
        initialize=0,
        bounds=(30, 16 + 40))
    m.Qb = Var(domain=NonNegativeReals,
               doc='reboiler duty (MJ/s)',
               initialize=1,
               bounds=(0, 8))
    m.Qc = Var(domain=NonNegativeReals,
               doc='condenser duty (MJ/s)',
               initialize=1,
               bounds=(0, 8))

    m.vap_Cp_const = {
        'benzene': {
            'A': -3.392E1,
            'B': 4.739E-1,
            'C': -3.017E-4,
            'D': 7.130E-8,
            'E': 0
        },
        'toluene': {
            'A': -2.435E1,
            'B': 5.125E-1,
            'C': -2.765E-4,
            'D': 4.911E-8,
            'E': 0
        }
    }
    m.liq_Cp_const = {
        'benzene': {
            'A': 1.29E5,
            'B': -1.7E2,
            'C': 6.48E-1,
            'D': 0,
            'E': 0
        },
        'toluene': {
            'A': 1.40E5,
            'B': -1.52E2,
            'C': 6.95E-1,
            'D': 0,
            'E': 0
        }
    }
    m.dH_vap = {'benzene': 33.770E3, 'toluene': 38.262E3}  # J/mol

    _build_column_heat_relations(m)

    @m.Constraint()
    def distillate_req(m):
        return m.D['benzene'] >= m.distillate_purity * m.dis

    @m.Constraint()
    def bottoms_req(m):
        return m.B['toluene'] >= m.bottoms_purity * m.bot

    # m.obj = Objective(expr=(m.Qc + m.Qb) * 1E-3, sense=minimize)
    m.obj = Objective(expr=(m.Qc + m.Qb) * 1E3 + 1E3 *
                      (sum(m.tray[t].indicator_var
                           for t in m.conditional_trays) + 1),
                      sense=minimize)
    # m.obj = Objective(
    #     expr=sum(m.tray[t].indicator_var for t in m.conditional_trays) + 1)

    @m.Constraint()
    def reflux_ratio_calc(m):
        return m.reflux_frac * (m.reflux_ratio + 1) == m.reflux_ratio

    @m.Constraint()
    def reboil_ratio_calc(m):
        return m.boilup_frac * (m.reboil_ratio + 1) == m.reboil_ratio

    @m.Constraint(m.conditional_trays)
    def tray_ordering(m, t):
        """Trays close to the feed should be activated first."""
        if t + 1 < m.condens_tray and t > m.feed_tray:
            return m.tray[t].indicator_var >= m.tray[t + 1].indicator_var
        elif t > m.reboil_tray and t + 1 < m.feed_tray:
            return m.tray[t + 1].indicator_var >= m.tray[t].indicator_var
        else:
            return Constraint.NoConstraint

    return m