コード例 #1
0
ファイル: test_induced_linearity.py プロジェクト: Pyomo/pyomo
 def test_induced_linearity_case2(self):
     m = ConcreteModel()
     m.x = Var([0], bounds=(-3, 8))
     m.y = Var(RangeSet(4), domain=Binary)
     m.z = Var(domain=Integers, bounds=(-1, 2))
     m.constr = Constraint(
         expr=m.x[0] == m.y[1] + 2 * m.y[2] + m.y[3] + 2 * m.y[4] + m.z)
     m.logical = ConstraintList()
     m.logical.add(expr=m.y[1] + m.y[2] == 1)
     m.logical.add(expr=m.y[3] + m.y[4] == 1)
     m.logical.add(expr=m.y[2] + m.y[4] <= 1)
     m.b = Var(bounds=(-2, 7))
     m.c = Var()
     m.bilinear = Constraint(
         expr=(m.x[0] - 3) * (m.b + 2) - (m.c + 4) * m.b +
         exp(m.b ** 2) * m.x[0] <= m.c)
     TransformationFactory('contrib.induced_linearity').apply_to(m)
     xfrmed_blk = m._induced_linearity_info.x0_b_bilinear
     self.assertSetEqual(
         set(xfrmed_blk.valid_values), set([1, 2, 3, 4, 5]))
     select_one_repn = generate_standard_repn(
         xfrmed_blk.select_one_value.body)
     self.assertEqual(
         ComponentSet(select_one_repn.linear_vars),
         ComponentSet(xfrmed_blk.x_active[i] for i in xfrmed_blk.valid_values))
コード例 #2
0
ファイル: test_induced_linearity.py プロジェクト: Pyomo/pyomo
 def test_bilinear_in_disjuncts(self):
     m = ConcreteModel()
     m.x = Var([0], bounds=(-3, 8))
     m.y = Var(RangeSet(4), domain=Binary)
     m.z = Var(domain=Integers, bounds=(-1, 2))
     m.constr = Constraint(
         expr=m.x[0] == m.y[1] + 2 * m.y[2] + m.y[3] + 2 * m.y[4] + m.z)
     m.logical = ConstraintList()
     m.logical.add(expr=m.y[1] + m.y[2] == 1)
     m.logical.add(expr=m.y[3] + m.y[4] == 1)
     m.logical.add(expr=m.y[2] + m.y[4] <= 1)
     m.v = Var([1, 2])
     m.v[1].setlb(-2)
     m.v[1].setub(7)
     m.v[2].setlb(-4)
     m.v[2].setub(5)
     m.bilinear = Constraint(
         expr=(m.x[0] - 3) * (m.v[1] + 2) - (m.v[2] + 4) * m.v[1] +
         exp(m.v[1] ** 2) * m.x[0] <= m.v[2])
     m.disjctn = Disjunction(expr=[
         [m.x[0] * m.v[1] <= 4],
         [m.x[0] * m.v[2] >= 6]
     ])
     TransformationFactory('contrib.induced_linearity').apply_to(m)
     self.assertEqual(
         m.disjctn.disjuncts[0].constraint[1].body.polynomial_degree(), 1)
     self.assertEqual(
         m.disjctn.disjuncts[1].constraint[1].body.polynomial_degree(), 1)
コード例 #3
0
ファイル: test_calc_var_value.py プロジェクト: Pyomo/pyomo
 def f(m):
     return m.pc * \
         exp((m.psc['A'] * (1 - m.x / m.tc) +
              m.psc['B'] * (1 - m.x / m.tc)**1.5 +
              m.psc['C'] * (1 - m.x / m.tc)**3 +
              m.psc['D'] * (1 - m.x / m.tc)**6
          ) / (1 - (1 - m.x / m.tc))) - m.p == 0
コード例 #4
0
ファイル: test_derivs.py プロジェクト: Pyomo/pyomo
 def test_exp(self):
     m = pe.ConcreteModel()
     m.x = pe.Var(initialize=2.0)
     e = pe.exp(m.x)
     derivs = reverse_ad(e)
     symbolic = reverse_sd(e)
     self.assertAlmostEqual(derivs[m.x], pe.value(symbolic[m.x]), tol+3)
     self.assertAlmostEqual(derivs[m.x], approx_deriv(e, m.x), tol)
コード例 #5
0
ファイル: test_derivs.py プロジェクト: Pyomo/pyomo
 def test_nested(self):
     m = pe.ConcreteModel()
     m.x = pe.Var(initialize=2)
     m.y = pe.Var(initialize=3)
     m.p = pe.Param(initialize=0.5, mutable=True)
     e = pe.exp(m.x**m.p + 3.2*m.y - 12)
     derivs = reverse_ad(e)
     symbolic = reverse_sd(e)
     self.assertAlmostEqual(derivs[m.x], pe.value(symbolic[m.x]), tol+3)
     self.assertAlmostEqual(derivs[m.y], pe.value(symbolic[m.y]), tol+3)
     self.assertAlmostEqual(derivs[m.p], pe.value(symbolic[m.p]), tol+3)
     self.assertAlmostEqual(derivs[m.x], approx_deriv(e, m.x), tol)
     self.assertAlmostEqual(derivs[m.y], approx_deriv(e, m.y), tol)
     self.assertAlmostEqual(derivs[m.p], approx_deriv(e, m.p), tol)
コード例 #6
0
ファイル: test_induced_linearity.py プロジェクト: Pyomo/pyomo
 def test_detect_bilinear_vars(self):
     m = ConcreteModel()
     m.x = Var()
     m.y = Var()
     m.z = Var()
     m.c = Constraint(
         expr=(m.x - 3) * (m.y + 2) - (m.z + 4) * m.y + (m.x + 2) ** 2
         + exp(m.y ** 2) * m.x <= m.z)
     m.c2 = Constraint(expr=m.x * m.y == 3)
     bilinear_map = _bilinear_expressions(m)
     self.assertEqual(len(bilinear_map), 3)
     self.assertEqual(len(bilinear_map[m.x]), 2)
     self.assertEqual(len(bilinear_map[m.y]), 2)
     self.assertEqual(len(bilinear_map[m.z]), 1)
     self.assertEqual(bilinear_map[m.x][m.x], ComponentSet([m.c]))
     self.assertEqual(bilinear_map[m.x][m.y], ComponentSet([m.c, m.c2]))
     self.assertEqual(bilinear_map[m.y][m.x], ComponentSet([m.c, m.c2]))
     self.assertEqual(bilinear_map[m.y][m.z], ComponentSet([m.c]))
     self.assertEqual(bilinear_map[m.z][m.y], ComponentSet([m.c]))
コード例 #7
0
ファイル: test_gams.py プロジェクト: Pyomo/pyomo
    def test_expr_xfrm(self):
        from pyomo.repn.plugins.gams_writer import (
            expression_to_string, StorageTreeChecker)
        from pyomo.core.expr.symbol_map import SymbolMap
        M = ConcreteModel()
        M.abc = Var()

        smap = SymbolMap()
        tc = StorageTreeChecker(M)

        expr = M.abc**2.0
        self.assertEqual(str(expr), "abc**2.0")
        self.assertEqual(expression_to_string(
            expr, tc, smap=smap), "power(abc, 2.0)")

        expr = log(M.abc**2.0)
        self.assertEqual(str(expr), "log(abc**2.0)")
        self.assertEqual(expression_to_string(
            expr, tc, smap=smap), "log(power(abc, 2.0))")

        expr = log(M.abc**2.0) + 5
        self.assertEqual(str(expr), "log(abc**2.0) + 5")
        self.assertEqual(expression_to_string(
            expr, tc, smap=smap), "log(power(abc, 2.0)) + 5")

        expr = exp(M.abc**2.0) + 5
        self.assertEqual(str(expr), "exp(abc**2.0) + 5")
        self.assertEqual(expression_to_string(
            expr, tc, smap=smap), "exp(power(abc, 2.0)) + 5")

        expr = log(M.abc**2.0)**4
        self.assertEqual(str(expr), "log(abc**2.0)**4")
        self.assertEqual(expression_to_string(
            expr, tc, smap=smap), "power(log(power(abc, 2.0)), 4)")

        expr = log(M.abc**2.0)**4.5
        self.assertEqual(str(expr), "log(abc**2.0)**4.5")
        self.assertEqual(expression_to_string(
            expr, tc, smap=smap), "log(power(abc, 2.0)) ** 4.5")
コード例 #8
0
ファイル: test_fbbt.py プロジェクト: mskarha/pyomo
 def test_exp(self):
     c_bounds = [(-2.5, 2.8), (0.5, 2.8), (0, 2.8), (1, 2.8), (0.5, 1)]
     for cl, cu in c_bounds:
         m = pe.Block(concrete=True)
         m.x = pe.Var()
         m.c = pe.Constraint(expr=pe.inequality(body=pe.exp(m.x), lower=cl, upper=cu))
         fbbt(m)
         if pe.value(m.c.lower) <= 0:
             _cl = 1e-6
         else:
             _cl = pe.value(m.c.lower)
         z = np.linspace(_cl, pe.value(m.c.upper), 100)
         if m.x.lb is None:
             xl = -np.inf
         else:
             xl = pe.value(m.x.lb)
         if m.x.ub is None:
             xu = np.inf
         else:
             xu = pe.value(m.x.ub)
         x = np.log(z)
         self.assertTrue(np.all(xl <= x))
         self.assertTrue(np.all(xu >= x))
コード例 #9
0
ファイル: rooney_biegler.py プロジェクト: Pyomo/pyomo
 def response_rule(m, h):
     expr = m.asymptote * (1 - pyo.exp(-m.rate_constant * h))
     return expr
コード例 #10
0
def build_eight_process_flowsheet():
    """Build flowsheet for the 8 process problem."""
    m = ConcreteModel(name='DuranEx3 Disjunctive')

    """Set declarations"""
    m.streams = RangeSet(2, 25, doc="process streams")
    m.units = RangeSet(1, 8, doc="process units")

    """Parameter and initial point declarations"""
    # FIXED COST INVESTMENT COEFF FOR PROCESS UNITS
    # Format: process #: cost
    fixed_cost = {1: 5, 2: 8, 3: 6, 4: 10, 5: 6, 6: 7, 7: 4, 8: 5}
    CF = m.CF = Param(m.units, initialize=fixed_cost)

    # VARIABLE COST COEFF FOR PROCESS UNITS - STREAMS
    # Format: stream #: cost
    variable_cost = {3: -10, 5: -15, 9: -40, 19: 25, 21: 35, 25: -35,
                     17: 80, 14: 15, 10: 15, 2: 1, 4: 1, 18: -65, 20: -60,
                     22: -80}
    CV = m.CV = Param(m.streams, initialize=variable_cost, default=0)

    # initial point information for stream flows
    initX = {2: 2, 3: 1.5, 6: 0.75, 7: 0.5, 8: 0.5, 9: 0.75, 11: 1.5,
             12: 1.34, 13: 2, 14: 2.5, 17: 2, 18: 0.75, 19: 2, 20: 1.5,
             23: 1.7, 24: 1.5, 25: 0.5}

    """Variable declarations"""
    # FLOWRATES OF PROCESS STREAMS
    m.flow = Var(m.streams, domain=NonNegativeReals, initialize=initX,
                 bounds=(0, 10))
    # OBJECTIVE FUNCTION CONSTANT TERM
    CONSTANT = m.constant = Param(initialize=122.0)

    """Constraint definitions"""
    # INPUT-OUTPUT RELATIONS FOR process units 1 through 8
    m.use_unit1 = Disjunct()
    m.use_unit1.inout1 = Constraint(expr=exp(m.flow[3]) - 1 == m.flow[2])
    m.use_unit1.no_unit2_flow1 = Constraint(expr=m.flow[4] == 0)
    m.use_unit1.no_unit2_flow2 = Constraint(expr=m.flow[5] == 0)
    m.use_unit2 = Disjunct()
    m.use_unit2.inout2 = Constraint(
        expr=exp(m.flow[5] / 1.2) - 1 == m.flow[4])
    m.use_unit2.no_unit1_flow1 = Constraint(expr=m.flow[2] == 0)
    m.use_unit2.no_unit1_flow2 = Constraint(expr=m.flow[3] == 0)

    m.use_unit3 = Disjunct()
    m.use_unit3.inout3 = Constraint(
        expr=1.5 * m.flow[9] + m.flow[10] == m.flow[8])
    m.no_unit3 = Disjunct()
    m.no_unit3.no_unit3_flow1 = Constraint(expr=m.flow[9] == 0)
    m.no_unit3.flow_pass_through = Constraint(expr=m.flow[10] == m.flow[8])

    m.use_unit4 = Disjunct()
    m.use_unit4.inout4 = Constraint(
        expr=1.25 * (m.flow[12] + m.flow[14]) == m.flow[13])
    m.use_unit4.no_unit5_flow = Constraint(expr=m.flow[15] == 0)
    m.use_unit5 = Disjunct()
    m.use_unit5.inout5 = Constraint(expr=m.flow[15] == 2 * m.flow[16])
    m.use_unit5.no_unit4_flow1 = Constraint(expr=m.flow[12] == 0)
    m.use_unit5.no_unit4_flow2 = Constraint(expr=m.flow[14] == 0)
    m.no_unit4or5 = Disjunct()
    m.no_unit4or5.no_unit5_flow = Constraint(expr=m.flow[15] == 0)
    m.no_unit4or5.no_unit4_flow1 = Constraint(expr=m.flow[12] == 0)
    m.no_unit4or5.no_unit4_flow2 = Constraint(expr=m.flow[14] == 0)

    m.use_unit6 = Disjunct()
    m.use_unit6.inout6 = Constraint(
        expr=exp(m.flow[20] / 1.5) - 1 == m.flow[19])
    m.use_unit6.no_unit7_flow1 = Constraint(expr=m.flow[21] == 0)
    m.use_unit6.no_unit7_flow2 = Constraint(expr=m.flow[22] == 0)
    m.use_unit7 = Disjunct()
    m.use_unit7.inout7 = Constraint(expr=exp(m.flow[22]) - 1 == m.flow[21])
    m.use_unit7.no_unit6_flow1 = Constraint(expr=m.flow[19] == 0)
    m.use_unit7.no_unit6_flow2 = Constraint(expr=m.flow[20] == 0)
    m.no_unit6or7 = Disjunct()
    m.no_unit6or7.no_unit7_flow1 = Constraint(expr=m.flow[21] == 0)
    m.no_unit6or7.no_unit7_flow2 = Constraint(expr=m.flow[22] == 0)
    m.no_unit6or7.no_unit6_flow = Constraint(expr=m.flow[19] == 0)
    m.no_unit6or7.no_unit6_flow2 = Constraint(expr=m.flow[20] == 0)

    m.use_unit8 = Disjunct()
    m.use_unit8.inout8 = Constraint(
        expr=exp(m.flow[18]) - 1 == m.flow[10] + m.flow[17])
    m.no_unit8 = Disjunct()
    m.no_unit8.no_unit8_flow1 = Constraint(expr=m.flow[10] == 0)
    m.no_unit8.no_unit8_flow2 = Constraint(expr=m.flow[17] == 0)
    m.no_unit8.no_unit8_flow3 = Constraint(expr=m.flow[18] == 0)

    # Mass balance equations
    m.massbal1 = Constraint(expr=m.flow[13] == m.flow[19] + m.flow[21])
    m.massbal2 = Constraint(
        expr=m.flow[17] == m.flow[9] + m.flow[16] + m.flow[25])
    m.massbal3 = Constraint(expr=m.flow[11] == m.flow[12] + m.flow[15])
    m.massbal4 = Constraint(
        expr=m.flow[3] + m.flow[5] == m.flow[6] + m.flow[11])
    m.massbal5 = Constraint(expr=m.flow[6] == m.flow[7] + m.flow[8])
    m.massbal6 = Constraint(expr=m.flow[23] == m.flow[20] + m.flow[22])
    m.massbal7 = Constraint(expr=m.flow[23] == m.flow[14] + m.flow[24])

    # process specifications
    m.specs1 = Constraint(expr=m.flow[10] <= 0.8 * m.flow[17])
    m.specs2 = Constraint(expr=m.flow[10] >= 0.4 * m.flow[17])
    m.specs3 = Constraint(expr=m.flow[12] <= 5 * m.flow[14])
    m.specs4 = Constraint(expr=m.flow[12] >= 2 * m.flow[14])

    # pure integer constraints
    m.use1or2 = Disjunction(expr=[m.use_unit1, m.use_unit2])
    m.use4or5maybe = Disjunction(
        expr=[m.use_unit4, m.use_unit5, m.no_unit4or5])
    m.use4or5 = Constraint(
        expr=m.use_unit4.indicator_var + m.use_unit5.indicator_var <= 1)
    m.use6or7maybe = Disjunction(
        expr=[m.use_unit6, m.use_unit7, m.no_unit6or7])
    m.use4implies6or7 = Constraint(
        expr=m.use_unit6.indicator_var + m.use_unit7.indicator_var -
        m.use_unit4.indicator_var == 0)
    m.use3maybe = Disjunction(expr=[m.use_unit3, m.no_unit3])
    m.either3ornot = Constraint(
        expr=m.use_unit3.indicator_var + m.no_unit3.indicator_var == 1)
    m.use8maybe = Disjunction(expr=[m.use_unit8, m.no_unit8])
    m.use3implies8 = Constraint(
        expr=m.use_unit3.indicator_var - m.use_unit8.indicator_var <= 0)

    """Profit (objective) function definition"""
    m.profit = Objective(expr=sum(
        getattr(m, 'use_unit%s' % (unit,)).indicator_var * CF[unit]
        for unit in m.units) +
        sum(m.flow[stream] * CV[stream]
            for stream in m.streams) + CONSTANT,
        sense=minimize)

    """Bound definitions"""
    # x (flow) upper bounds
    x_ubs = {3: 2, 5: 2, 9: 2, 10: 1, 14: 1, 17: 2, 19: 2, 21: 2, 25: 3}
    for i, x_ub in iteritems(x_ubs):
        m.flow[i].setub(x_ub)

    # # optimal solution
    # m.use_unit1.indicator_var = 0
    # m.use_unit2.indicator_var = 1
    # m.use_unit3.indicator_var = 0
    # m.no_unit3.indicator_var = 1
    # m.use_unit4.indicator_var = 1
    # m.use_unit5.indicator_var = 0
    # m.no_unit4or5.indicator_var = 0
    # m.use_unit6.indicator_var = 1
    # m.use_unit7.indicator_var = 0
    # m.no_unit6or7.indicator_var = 0
    # m.use_unit8.indicator_var = 1
    # m.no_unit8.indicator_var = 0

    return m
コード例 #11
0
 def rule_visc(self):
     return self.visc_kin == \
         exp(586.375 / (self.temperature - 273.15 + 62.5) - 2.2809)
コード例 #12
0
ファイル: eight_proc_model.py プロジェクト: Pyomo/pyomo
def build_eight_process_flowsheet():
    """Build flowsheet for the 8 process problem."""
    m = ConcreteModel(name='DuranEx3 Disjunctive')

    """Set declarations"""
    m.streams = RangeSet(2, 25, doc="process streams")
    m.units = RangeSet(1, 8, doc="process units")

    """Parameter and initial point declarations"""
    # FIXED COST INVESTMENT COEFF FOR PROCESS UNITS
    # Format: process #: cost
    fixed_cost = {1: 5, 2: 8, 3: 6, 4: 10, 5: 6, 6: 7, 7: 4, 8: 5}
    m.CF = Param(m.units, initialize=fixed_cost)

    def fixed_cost_bounds(m, unit):
        return (0, m.CF[unit])
    m.yCF = Var(m.units, initialize=0, bounds=fixed_cost_bounds)

    # VARIABLE COST COEFF FOR PROCESS UNITS - STREAMS
    # Format: stream #: cost
    variable_cost = {3: -10, 5: -15, 9: -40, 19: 25, 21: 35, 25: -35,
                     17: 80, 14: 15, 10: 15, 2: 1, 4: 1, 18: -65, 20: -60,
                     22: -80}
    CV = m.CV = Param(m.streams, initialize=variable_cost, default=0)

    # initial point information for stream flows
    initX = {2: 2, 3: 1.5, 6: 0.75, 7: 0.5, 8: 0.5, 9: 0.75, 11: 1.5,
             12: 1.34, 13: 2, 14: 2.5, 17: 2, 18: 0.75, 19: 2, 20: 1.5,
             23: 1.7, 24: 1.5, 25: 0.5}

    """Variable declarations"""
    # FLOWRATES OF PROCESS STREAMS
    m.flow = Var(m.streams, domain=NonNegativeReals, initialize=initX,
                 bounds=(0, 10))
    # OBJECTIVE FUNCTION CONSTANT TERM
    CONSTANT = m.constant = Param(initialize=122.0)

    """Constraint definitions"""
    # INPUT-OUTPUT RELATIONS FOR process units 1 through 8
    m.use_unit_1or2 = Disjunction(
        expr=[
            # use unit 1 disjunct
            [m.yCF[1] == m.CF[1],
             exp(m.flow[3]) - 1 == m.flow[2],
             m.flow[4] == 0,
             m.flow[5] == 0],
            # use unit 2 disjunct
            [m.yCF[2] == m.CF[2],
             exp(m.flow[5] / 1.2) - 1 == m.flow[4],
             m.flow[2] == 0,
             m.flow[3] == 0]
        ])
    m.use_unit_3ornot = Disjunction(
        expr=[
            # Use unit 3 disjunct
            [m.yCF[3] == m.CF[3],
             1.5 * m.flow[9] + m.flow[10] == m.flow[8]],
            # No unit 3 disjunct
            [m.flow[9] == 0,
             m.flow[10] == m.flow[8]]
        ])
    m.use_unit_4or5ornot = Disjunction(
        expr=[
            # Use unit 4 disjunct
            [m.yCF[4] == m.CF[4],
             1.25 * (m.flow[12] + m.flow[14]) == m.flow[13],
             m.flow[15] == 0],
            # Use unit 5 disjunct
            [m.yCF[5] == m.CF[5],
             m.flow[15] == 2 * m.flow[16],
             m.flow[12] == 0,
             m.flow[14] == 0],
            # No unit 4 or 5 disjunct
            [m.flow[15] == 0,
             m.flow[12] == 0,
             m.flow[14] == 0]
        ])
    m.use_unit_6or7ornot = Disjunction(
        expr=[
            # use unit 6 disjunct
            [m.yCF[6] == m.CF[6],
             exp(m.flow[20] / 1.5) - 1 == m.flow[19],
             m.flow[21] == 0,
             m.flow[22] == 0],
            # use unit 7 disjunct
            [m.yCF[7] == m.CF[7],
             exp(m.flow[22]) - 1 == m.flow[21],
             m.flow[19] == 0,
             m.flow[20] == 0],
            # No unit 6 or 7 disjunct
            [m.flow[21] == 0,
                m.flow[22] == 0,
                m.flow[19] == 0,
                m.flow[20] == 0]
        ])
    m.use_unit_8ornot = Disjunction(
        expr=[
            # use unit 8 disjunct
            [m.yCF[8] == m.CF[8],
             exp(m.flow[18]) - 1 == m.flow[10] + m.flow[17]],
            # no unit 8 disjunct
            [m.flow[10] == 0,
                m.flow[17] == 0,
                m.flow[18] == 0]
        ])

    # Mass balance equations
    m.massbal1 = Constraint(expr=m.flow[13] == m.flow[19] + m.flow[21])
    m.massbal2 = Constraint(
        expr=m.flow[17] == m.flow[9] + m.flow[16] + m.flow[25])
    m.massbal3 = Constraint(expr=m.flow[11] == m.flow[12] + m.flow[15])
    m.massbal4 = Constraint(
        expr=m.flow[3] + m.flow[5] == m.flow[6] + m.flow[11])
    m.massbal5 = Constraint(expr=m.flow[6] == m.flow[7] + m.flow[8])
    m.massbal6 = Constraint(expr=m.flow[23] == m.flow[20] + m.flow[22])
    m.massbal7 = Constraint(expr=m.flow[23] == m.flow[14] + m.flow[24])

    # process specifications
    m.specs1 = Constraint(expr=m.flow[10] <= 0.8 * m.flow[17])
    m.specs2 = Constraint(expr=m.flow[10] >= 0.4 * m.flow[17])
    m.specs3 = Constraint(expr=m.flow[12] <= 5 * m.flow[14])
    m.specs4 = Constraint(expr=m.flow[12] >= 2 * m.flow[14])

    # pure integer constraints
    m.use4implies6or7 = Constraint(
        expr=m.use_unit_6or7ornot.disjuncts[0].indicator_var +
        m.use_unit_6or7ornot.disjuncts[1].indicator_var -
        m.use_unit_4or5ornot.disjuncts[0].indicator_var == 0)
    m.use3implies8 = Constraint(
        expr=m.use_unit_3ornot.disjuncts[0].indicator_var
        - m.use_unit_8ornot.disjuncts[0].indicator_var <= 0)

    """Profit (objective) function definition"""
    m.profit = Objective(expr=sum(
        m.yCF[unit]
        for unit in m.units) +
        sum(m.flow[stream] * CV[stream]
            for stream in m.streams) + CONSTANT,
        sense=minimize)

    """Bound definitions"""
    # x (flow) upper bounds
    x_ubs = {3: 2, 5: 2, 9: 2, 10: 1, 14: 1, 17: 2, 19: 2, 21: 2, 25: 3}
    for i, x_ub in iteritems(x_ubs):
        m.flow[i].setub(x_ub)

    # Optimal solution uses units 2, 4, 6, 8 with objective value 68.

    return m
コード例 #13
0
    def initialize(
            blk,
            state_args={
                "flow_component": {
                    "N2": 1.0,
                    "CO2": 1.0,
                    "NO": 1.0,
                    "O2": 1.0,
                    "H2O": 1.0,
                    "SO2": 1.0
                },
                "pressure": 1e5,
                "temperature": 495.0
            },
            hold_state=False,
            state_vars_fixed=False,
            outlvl=0,
            solver='ipopt',
            optarg={'tol': 1e-8}):
        '''
        Initialisation routine for property package.

        Key values for the state_args dict:
            flow_component : value at which to initialize component flows
                             (default=27.5e3 mol/s)
            pressure : value at which to initialize pressure (default=2.97e7 Pa)
            temperature : value at which to initialize temperature
                          (default=866.5 K)
            outlvl : sets output level of initialisation routine

                     * 0 = no output (default)
                     * 1 = return solver state for each step in routine
                     * 2 = include solver output infomation (tee=True)
            state_vars_fixed: Flag to denote if state vars have already been
                              fixed.
                              - True - states have already been fixed by the
                                       control volume 1D. Control volume 0D
                                       does not fix the state vars, so will
                                       be False if this state block is used
                                       with 0D blocks.
                             - False - states have not been fixed. The state
                                       block will deal with fixing/unfixing.
            optarg : solver options dictionary object (default=None)
            solver : str indicating whcih solver to use during
                     initialization (default = 'ipopt')
            hold_state : flag indicating whether the initialization routine
                         should unfix any state variables fixed during
                         initialization (default=False).
                         - True - states varaibles are not unfixed, and
                                 a dict of returned containing flags for
                                 which states were fixed during
                                 initialization.
                        - False - state variables are unfixed after
                                 initialization by calling the
                                 relase_state method

        Returns:
            If hold_states is True, returns a dict containing flags for
            which states were fixed during initialization.
        '''

        if state_vars_fixed is False:
            flags = fix_state_vars(blk, state_args)

        # Check when the state vars are fixed already result in dof 0
        for k in blk.keys():
            if degrees_of_freedom(blk[k]) != 0:
                raise Exception("State vars fixed but degrees of freedom "
                                "for state block is not zero during "
                                "initialization.")
        # Set solver options
        if outlvl > 1:
            stee = True
        else:
            stee = False

        opt = SolverFactory(solver)
        opt.options = optarg

        # ---------------------------------------------------------------------
        # Solve 1st stage
        for k in blk.keys():
            if hasattr(blk[k], "vapor_pressure_correlation"):
                blk[k].vapor_pressure = \
                                exp(blk[k].vapor_pressure_coeff[1].value +
                                    blk[k].vapor_pressure_coeff[2].value /
                                    value(blk.temperature) +
                                    blk[k].vapor_pressure_coeff[3].value *
                                    value(blk.temperature) +
                                    blk[k].vapor_pressure_coeff[4].value *
                                    log(value(blk.temperature)) +
                                    blk[k].vapor_pressure_coeff[5].value *
                                    value(blk.temperature)**2)

            if hasattr(blk[k], 'enthalpy_correlation'):
                blk[k].enthalpy_correlation.deactivate()
            if hasattr(blk[k], "volumetric_flow_calculation"):
                blk[k].volumetric_flow_calculation.deactivate()
            if hasattr(blk[k], "entropy_correlation"):
                blk[k].entropy_correlation.deactivate()
            if hasattr(blk[k], "density_mol_calculation"):
                blk[k].density_mol_calculation.deactivate()

            results = opt.solve(blk[k], tee=stee)

            if outlvl > 0:
                if results.solver.termination_condition \
                        == TerminationCondition.optimal:
                    logger.info('{} Initialisation Step 1 Complete.'.format(
                        blk.name))
                else:
                    logger.warning('{} Initialisation Step 1 Failed.'.format(
                        blk.name))

        # ---------------------------------------------------------------------
        # Solve 2nd stage
        for k in blk.keys():
            if hasattr(blk[k], 'enthalpy_correlation'):
                blk[k].enthalpy_correlation.activate()
            if hasattr(blk[k], "volumetric_flow_calculation"):
                blk[k].volumetric_flow_calculation.activate()
            if hasattr(blk[k], "entropy_correlation"):
                blk[k].entropy_correlation.activate()
            if hasattr(blk[k], "density_mol_calculation"):
                blk[k].density_mol_calculation.activate()

            results = opt.solve(blk[k], tee=stee)

            if outlvl > 0:
                if results.solver.termination_condition \
                        == TerminationCondition.optimal:
                    logger.info('{} Initialisation Step 2 Complete.'.format(
                        blk.name))
                else:
                    logger.warning('{} Initialisation Step 2 Failed.'.format(
                        blk.name))
        # ---------------------------------------------------------------------
        # If input block, return flags, else release state

        if outlvl > 0:
            if outlvl > 0:
                logger.info('{} Initialisation Complete.'.format(blk.name))

        if state_vars_fixed is False:
            if hold_state is True:
                return flags
            else:
                blk.release_state(flags)
コード例 #14
0
 def act_phase_comp_true(b, p, j):
     ln_gamma = getattr(b, p + "_log_gamma")
     return b.mole_frac_phase_comp_true[p, j] * exp(ln_gamma[j])
コード例 #15
0
ファイル: diff.py プロジェクト: Pyomo/pyomo
import pyomo.environ as pe
from pyomo.contrib.derivatives.differentiate import reverse_ad, reverse_sd

m = pe.ConcreteModel()
m.x = pe.Var(initialize=2)
m.y = pe.Var(initialize=3)
m.p = pe.Param(initialize=0.5, mutable=True)

e = pe.exp(m.x**m.p + 0.1*m.y)
derivs = reverse_ad(e)
print('dfdx: ', derivs[m.x])
print('dfdy: ', derivs[m.y])
print('dfdp: ', derivs[m.p])
derivs = reverse_sd(e)
print('dfdx: ', derivs[m.x])
print('dfdy: ', derivs[m.y])
print('dfdp: ', derivs[m.p])
コード例 #16
0
model.ONE = Var(initialize=1)
model.ZERO = Var(initialize=0)


model.obj = Objective(expr=model.ONE+model.ZERO)

model.c_log     = Constraint(expr=log(model.ONE) == 0)
model.c_log10   = Constraint(expr=log10(model.ONE) == 0)

model.c_sin     = Constraint(expr=sin(model.ZERO) == 0)
model.c_cos     = Constraint(expr=cos(model.ZERO) == 1)
model.c_tan     = Constraint(expr=tan(model.ZERO) == 0)

model.c_sinh    = Constraint(expr=sinh(model.ZERO) == 0)
model.c_cosh    = Constraint(expr=cosh(model.ZERO) == 1)
model.c_tanh    = Constraint(expr=tanh(model.ZERO) == 0)

model.c_asin    = Constraint(expr=asin(model.ZERO) == 0)
model.c_acos    = Constraint(expr=acos(model.ZERO) == pi/2)
model.c_atan    = Constraint(expr=atan(model.ZERO) == 0)

model.c_asinh   = Constraint(expr=asinh(model.ZERO) == 0)
model.c_acosh   = Constraint(expr=acosh((e**2 + model.ONE)/(2*e)) == 0)
model.c_atanh   = Constraint(expr=atanh(model.ZERO) == 0)

model.c_exp     = Constraint(expr=exp(model.ZERO) == 1)
model.c_sqrt    = Constraint(expr=sqrt(model.ONE) == 1)
model.c_ceil    = Constraint(expr=ceil(model.ONE) == 1)
model.c_floor   = Constraint(expr=floor(model.ONE) == 1)
model.c_abs     = Constraint(expr=abs(model.ONE) == 1)
コード例 #17
0
 def _B_mol_bal(m, t):
     k1 = po.exp(m.theta_10 + m.theta_11 * (m.T - 273.15) / m.T)
     k2 = po.exp(m.theta_20 + m.theta_21 * (m.T - 273.15) / m.T)
     k3 = po.exp(m.theta_30 + m.theta_31 * (m.T - 273.15) / m.T)
     r = k1 * m.cA[t]**m.alpha / (k2 + k3 * m.cA[t]**m.beta)
     return m.dcBdt[t] == m.tau * m.nu * r
コード例 #18
0
ファイル: test_calc_var_value.py プロジェクト: Pyomo/pyomo
    def test_nonlinear(self):
        m = ConcreteModel()
        m.x = Var()
        m.y = Var(initialize=0)

        m.c = Constraint(expr=m.x**2 == 16)
        m.x.set_value(1.0) # set an initial value
        calculate_variable_from_constraint(m.x, m.c, linesearch=False)
        self.assertAlmostEqual(value(m.x), 4)

        # test that infeasible constraint throws error
        m.d = Constraint(expr=m.x**2 == -1)
        m.x.set_value(1.25) # set the initial value
        with self.assertRaisesRegexp(
               RuntimeError, 'Iteration limit \(10\) reached'):
           calculate_variable_from_constraint(
               m.x, m.d, iterlim=10, linesearch=False)

        # same problem should throw a linesearch error if linesearch is on
        m.x.set_value(1.25) # set the initial value
        with self.assertRaisesRegexp(
                RuntimeError, "Linesearch iteration limit reached"):
           calculate_variable_from_constraint(
               m.x, m.d, iterlim=10, linesearch=True)

        # same problem should raise an error if initialized at 0
        m.x = 0
        with self.assertRaisesRegexp(
                RuntimeError, "Initial value for variable results in a "
                "derivative value that is very close to zero."):
            calculate_variable_from_constraint(m.x, m.c)

        # same problem should raise a value error if we are asked to
        # solve for a variable that is not present
        with self.assertRaisesRegexp(
                ValueError, "Variable derivative == 0"):
            calculate_variable_from_constraint(m.y, m.c)


        # should succeed with or without a linesearch
        m.e = Constraint(expr=(m.x - 2.0)**2 - 1 == 0)
        m.x.set_value(3.1)
        calculate_variable_from_constraint(m.x, m.e, linesearch=False)
        self.assertAlmostEqual(value(m.x), 3)

        m.x.set_value(3.1)
        calculate_variable_from_constraint(m.x, m.e, linesearch=True)
        self.assertAlmostEqual(value(m.x), 3)


        # we expect this to succeed with the linesearch
        m.f = Constraint(expr=1.0/(1.0+exp(-m.x))-0.5 == 0)
        m.x.set_value(3.0)
        calculate_variable_from_constraint(m.x, m.f, linesearch=True)
        self.assertAlmostEqual(value(m.x), 0)

        # we expect this to fail without a linesearch
        m.x.set_value(3.0)
        with self.assertRaisesRegexp(
                RuntimeError, "Newton's method encountered a derivative "
                "that was too close to zero"):
            calculate_variable_from_constraint(m.x, m.f, linesearch=False)

        # Calculate the bubble point of Benzene.  THe first step
        # computed by calculate_variable_from_constraint will make the
        # second term become complex, and the evaluation will fail.
        # This tests that the algorithm cleanly continues
        m = ConcreteModel()
        m.x = Var()
        m.pc = 48.9e5
        m.tc = 562.2
        m.psc = {'A': -6.98273,
                 'B': 1.33213,
                 'C': -2.62863,
                 'D': -3.33399,
        }
        m.p = 101325
        @m.Constraint()
        def f(m):
            return m.pc * \
                exp((m.psc['A'] * (1 - m.x / m.tc) +
                     m.psc['B'] * (1 - m.x / m.tc)**1.5 +
                     m.psc['C'] * (1 - m.x / m.tc)**3 +
                     m.psc['D'] * (1 - m.x / m.tc)**6
                 ) / (1 - (1 - m.x / m.tc))) - m.p == 0
        m.x.set_value(298.15)
        calculate_variable_from_constraint(m.x, m.f, linesearch=False)
        self.assertAlmostEqual(value(m.x), 353.31855602)
        m.x.set_value(298.15)
        calculate_variable_from_constraint(m.x, m.f, linesearch=True)
        self.assertAlmostEqual(value(m.x), 353.31855602)

        # Starting with an invalid guess (above TC) should raise an
        # exception
        m.x.set_value(600)
        output = six.StringIO()
        with LoggingIntercept(output, 'pyomo', logging.WARNING):
            if six.PY2:
                expectedException = ValueError
            else:
                expectedException = TypeError
            with self.assertRaises(expectedException):
                calculate_variable_from_constraint(m.x, m.f, linesearch=False)
        self.assertIn('Encountered an error evaluating the expression '
                      'at the initial guess', output.getvalue())

        # This example triggers an expression evaluation error if the
        # linesearch is turned off because the first step in Newton's
        # method will cause the LHS to become complex
        m = ConcreteModel()
        m.x = Var()
        m.c = Constraint(expr=(1/m.x**3)**0.5 == 100)
        m.x = .1
        calculate_variable_from_constraint(m.x, m.c, linesearch=True)
        self.assertAlmostEqual(value(m.x), 0.046415888)
        m.x = .1
        output = six.StringIO()
        with LoggingIntercept(output, 'pyomo', logging.WARNING):
            with self.assertRaises(ValueError):
                # Note that the ValueError is different between Python 2
                # and Python 3: in Python 2 it is a specific error
                # "negative number cannot be raised to a fractional
                # power", and We mock up that error in Python 3 by
                # raising a generic ValueError in
                # calculate_variable_from_constraint
                calculate_variable_from_constraint(m.x, m.c, linesearch=False)
        self.assertIn("Newton's method encountered an error evaluating "
                      "the expression.", output.getvalue())

        # This is a completely contrived example where the linesearch
        # hits the iteration limit before Newton's method ever finds a
        # feasible step
        m = ConcreteModel()
        m.x = Var()
        m.c = Constraint(expr=m.x**0.5 == -1e-8)
        m.x = 1e-8#197.932807183
        with self.assertRaisesRegexp(
                RuntimeError, "Linesearch iteration limit reached; "
                "remaining residual = {function evaluation error}"):
            calculate_variable_from_constraint(m.x, m.c, linesearch=True,
                                               alpha_min=.5)
コード例 #19
0
 def act_coeff_phase_comp_appr(b, p, j):
     ln_gamma = getattr(b, p + "_log_gamma_appr")
     return exp(ln_gamma[j])
コード例 #20
0
 def act_coeff_phase_comp(b, p, j):
     if b.params.config.state_components == StateIndex.true:
         ln_gamma = getattr(b, p + "_log_gamma")
     else:
         ln_gamma = getattr(b, p + "_log_gamma_appr")
     return exp(ln_gamma[j])
コード例 #21
0
 def act_phase_comp_appr(b, p, j):
     ln_gamma = getattr(b, p + "_log_gamma_appr")
     return b.mole_frac_phase_comp_apparent[p, j] * exp(ln_gamma[j])
コード例 #22
0
ファイル: semi_bayes_ode.py プロジェクト: icepringrolls/pydex
 def _material_balance_b(m, t):
     k = po.exp(m.theta_0 + m.theta_1 * (m.temp - 273.15) / m.temp)
     return m.dcb_dt[t] / m.tau == m.nu * k * (m.ca[t]**model.alpha_a) * (
         model.cb[t]**model.alpha_b)
コード例 #23
0
 def fug_coeff_phase_comp_eq(blk, p, j, pp):
     return exp(_log_fug_coeff_phase_comp_eq(blk, p, j, pp))
コード例 #24
0
ファイル: test_calc_var_value.py プロジェクト: CanLi1/pyomo-1
    def test_nonlinear(self):
        m = ConcreteModel()
        m.x = Var()
        m.y = Var(initialize=0)

        m.c = Constraint(expr=m.x**2 == 16)
        m.x.set_value(1.0)  # set an initial value
        calculate_variable_from_constraint(m.x, m.c, linesearch=False)
        self.assertAlmostEqual(value(m.x), 4)

        # test that infeasible constraint throws error
        m.d = Constraint(expr=m.x**2 == -1)
        m.x.set_value(1.25)  # set the initial value
        with self.assertRaisesRegexp(RuntimeError,
                                     'Iteration limit \(10\) reached'):
            calculate_variable_from_constraint(m.x,
                                               m.d,
                                               iterlim=10,
                                               linesearch=False)

        # same problem should throw a linesearch error if linesearch is on
        m.x.set_value(1.25)  # set the initial value
        with self.assertRaisesRegexp(RuntimeError,
                                     "Linesearch iteration limit reached"):
            calculate_variable_from_constraint(m.x,
                                               m.d,
                                               iterlim=10,
                                               linesearch=True)

        # same problem should raise an error if initialized at 0
        m.x = 0
        with self.assertRaisesRegexp(
                RuntimeError, "Initial value for variable results in a "
                "derivative value that is very close to zero."):
            calculate_variable_from_constraint(m.x, m.c)

        # same problem should raise a value error if we are asked to
        # solve for a variable that is not present
        with self.assertRaisesRegexp(ValueError, "Variable derivative == 0"):
            calculate_variable_from_constraint(m.y, m.c)

        # should succeed with or without a linesearch
        m.e = Constraint(expr=(m.x - 2.0)**2 - 1 == 0)
        m.x.set_value(3.1)
        calculate_variable_from_constraint(m.x, m.e, linesearch=False)
        self.assertAlmostEqual(value(m.x), 3)

        m.x.set_value(3.1)
        calculate_variable_from_constraint(m.x, m.e, linesearch=True)
        self.assertAlmostEqual(value(m.x), 3)

        # we expect this to succeed with the linesearch
        m.f = Constraint(expr=1.0 / (1.0 + exp(-m.x)) - 0.5 == 0)
        m.x.set_value(3.0)
        calculate_variable_from_constraint(m.x, m.f, linesearch=True)
        self.assertAlmostEqual(value(m.x), 0)

        # we expect this to fail without a linesearch
        m.x.set_value(3.0)
        with self.assertRaisesRegexp(
                RuntimeError, "Newton's method encountered a derivative "
                "that was too close to zero"):
            calculate_variable_from_constraint(m.x, m.f, linesearch=False)

        # Calculate the bubble point of Benzene.  THe first step
        # computed by calculate_variable_from_constraint will make the
        # second term become complex, and the evaluation will fail.
        # This tests that the algorithm cleanly continues
        m = ConcreteModel()
        m.x = Var()
        m.pc = 48.9e5
        m.tc = 562.2
        m.psc = {
            'A': -6.98273,
            'B': 1.33213,
            'C': -2.62863,
            'D': -3.33399,
        }
        m.p = 101325

        @m.Constraint()
        def f(m):
            return m.pc * \
                exp((m.psc['A'] * (1 - m.x / m.tc) +
                     m.psc['B'] * (1 - m.x / m.tc)**1.5 +
                     m.psc['C'] * (1 - m.x / m.tc)**3 +
                     m.psc['D'] * (1 - m.x / m.tc)**6
                 ) / (1 - (1 - m.x / m.tc))) - m.p == 0

        m.x.set_value(298.15)
        calculate_variable_from_constraint(m.x, m.f, linesearch=False)
        self.assertAlmostEqual(value(m.x), 353.31855602)
        m.x.set_value(298.15)
        calculate_variable_from_constraint(m.x, m.f, linesearch=True)
        self.assertAlmostEqual(value(m.x), 353.31855602)

        # Starting with an invalid guess (above TC) should raise an
        # exception
        m.x.set_value(600)
        output = six.StringIO()
        with LoggingIntercept(output, 'pyomo', logging.WARNING):
            if six.PY2:
                expectedException = ValueError
            else:
                expectedException = TypeError
            with self.assertRaises(expectedException):
                calculate_variable_from_constraint(m.x, m.f, linesearch=False)
        self.assertIn(
            'Encountered an error evaluating the expression '
            'at the initial guess', output.getvalue())

        # This example triggers an expression evaluation error if the
        # linesearch is turned off because the first step in Newton's
        # method will cause the LHS to become complex
        m = ConcreteModel()
        m.x = Var()
        m.c = Constraint(expr=(1 / m.x**3)**0.5 == 100)
        m.x = .1
        calculate_variable_from_constraint(m.x, m.c, linesearch=True)
        self.assertAlmostEqual(value(m.x), 0.046415888)
        m.x = .1
        output = six.StringIO()
        with LoggingIntercept(output, 'pyomo', logging.WARNING):
            with self.assertRaises(ValueError):
                # Note that the ValueError is different between Python 2
                # and Python 3: in Python 2 it is a specific error
                # "negative number cannot be raised to a fractional
                # power", and We mock up that error in Python 3 by
                # raising a generic ValueError in
                # calculate_variable_from_constraint
                calculate_variable_from_constraint(m.x, m.c, linesearch=False)
        self.assertIn(
            "Newton's method encountered an error evaluating "
            "the expression.", output.getvalue())

        # This is a completely contrived example where the linesearch
        # hits the iteration limit before Newton's method ever finds a
        # feasible step
        m = ConcreteModel()
        m.x = Var()
        m.c = Constraint(expr=m.x**0.5 == -1e-8)
        m.x = 1e-8  #197.932807183
        with self.assertRaisesRegexp(
                RuntimeError, "Linesearch iteration limit reached; "
                "remaining residual = {function evaluation error}"):
            calculate_variable_from_constraint(m.x,
                                               m.c,
                                               linesearch=True,
                                               alpha_min=.5)
コード例 #25
0
ファイル: rooney_biegler.py プロジェクト: vova292/pyomo
 def response_rule(m, h):
     expr = m.asymptote * (1 - pyo.exp(-m.rate_constant * h))
     return expr
コード例 #26
0
 def rule_visc_d(b, p):
     return b.visc_d[p] == (b.params.mu_A *
                            exp(b.params.mu_B /
                                (b.temperature - b.params.mu_C)))
コード例 #27
0
 def response_rule(m, h):
     expr = m.theta['asymptote'] * (
         1 - pyo.exp(-m.theta['rate_constant'] * h))
     return expr
コード例 #28
0
 def gt1(b, t):
     return 1 / (exp(380 / b.temperature_coal[t]) - 1)
コード例 #29
0
 def _G_appr(b, pobj, i, j, T):  # Eqn 23
     if i != j:
         return exp(-alpha_rule(b, pobj, i, j, T) *
                    tau_rule(b, pobj, i, j, T))
     else:
         return 1
コード例 #30
0
ファイル: eight_process_problem.py プロジェクト: Pyomo/pyomo
    def __init__(self, *args, **kwargs):
        """Create the flowsheet."""
        kwargs.setdefault('name', 'DuranEx3')
        super(EightProcessFlowsheet, self).__init__(*args, **kwargs)
        m = self

        """Set declarations"""
        I = m.I = RangeSet(2, 25, doc="process streams")
        J = m.J = RangeSet(1, 8, doc="process units")
        m.PI = RangeSet(1, 4, doc="integer constraints")
        m.DS = RangeSet(1, 4, doc="design specifications")
        """
        1: Unit 8
        2: Unit 8
        3: Unit 4
        4: Unit 4
        """
        m.MB = RangeSet(1, 7, doc="mass balances")
        """Material balances:
        1: 4-6-7
        2: 3-5-8
        3: 4-5
        4: 1-2
        5: 1-2-3
        6: 6-7-4
        7: 6-7
        """

        """Parameter and initial point declarations"""
        # FIXED COST INVESTMENT COEFF FOR PROCESS UNITS
        # Format: process #: cost
        fixed_cost = {1: 5, 2: 8, 3: 6, 4: 10, 5: 6, 6: 7, 7: 4, 8: 5}
        CF = m.CF = Param(J, initialize=fixed_cost)

        # VARIABLE COST COEFF FOR PROCESS UNITS - STREAMS
        # Format: stream #: cost
        variable_cost = {3: -10, 5: -15, 9: -40, 19: 25, 21: 35, 25: -35,
                         17: 80, 14: 15, 10: 15, 2: 1, 4: 1, 18: -65, 20: -60,
                         22: -80}
        CV = m.CV = Param(I, initialize=variable_cost, default=0)

        # initial point information for equipment selection (for each NLP
        # subproblem)
        initY = {
            'sub1': {1: 1, 2: 0, 3: 1, 4: 1, 5: 0, 6: 0, 7: 1, 8: 1},
            'sub2': {1: 0, 2: 1, 3: 1, 4: 1, 5: 0, 6: 1, 7: 0, 8: 1},
            'sub3': {1: 1, 2: 0, 3: 1, 4: 0, 5: 1, 6: 0, 7: 0, 8: 1}
        }
        # initial point information for stream flows
        initX = {1: 0, 2: 2, 3: 1.5, 4: 0, 5: 0, 6: 0.75, 7: 0.5, 8: 0.5,
                 9: 0.75, 10: 0, 11: 1.5, 12: 1.34, 13: 2, 14: 2.5, 15: 0,
                 16: 0, 17: 2, 18: 0.75, 19: 2, 20: 1.5, 21: 0, 22: 0,
                 23: 1.7, 24: 1.5, 25: 0.5}

        """Variable declarations"""
        # BINARY VARIABLE DENOTING EXISTENCE-NONEXISTENCE
        Y = m.Y = Var(J, domain=Binary, initialize=initY['sub1'])
        # FLOWRATES OF PROCESS STREAMS
        X = m.X = Var(I, domain=NonNegativeReals, initialize=initX)
        # OBJECTIVE FUNCTION CONSTANT TERM
        CONSTANT = m.constant = Param(initialize=122.0)

        """Constraint definitions"""
        # INPUT-OUTPUT RELATIONS FOR process units 1 through 8
        m.inout1 = Constraint(expr=exp(m.X[3]) - 1 == m.X[2])
        m.inout2 = Constraint(expr=exp(m.X[5] / 1.2) - 1 == m.X[4])
        m.inout3 = Constraint(expr=1.5 * m.X[9] + m.X[10] == m.X[8])
        m.inout4 = Constraint(expr=1.25 * (m.X[12] + m.X[14]) == m.X[13])
        m.inout5 = Constraint(expr=m.X[15] == 2 * m.X[16])
        m.inout6 = Constraint(expr=exp(m.X[20] / 1.5) - 1 == m.X[19])
        m.inout7 = Constraint(expr=exp(m.X[22]) - 1 == m.X[21])
        m.inout8 = Constraint(expr=exp(m.X[18]) - 1 == m.X[10] + m.X[17])

        # Mass balance equations
        m.massbal1 = Constraint(expr=m.X[13] == m.X[19] + m.X[21])
        m.massbal2 = Constraint(expr=m.X[17] == m.X[9] + m.X[16] + m.X[25])
        m.massbal3 = Constraint(expr=m.X[11] == m.X[12] + m.X[15])
        m.massbal4 = Constraint(expr=m.X[3] + m.X[5] == m.X[6] + m.X[11])
        m.massbal5 = Constraint(expr=m.X[6] == m.X[7] + m.X[8])
        m.massbal6 = Constraint(expr=m.X[23] == m.X[20] + m.X[22])
        m.massbal7 = Constraint(expr=m.X[23] == m.X[14] + m.X[24])

        # process specifications
        m.specs1 = Constraint(expr=m.X[10] <= 0.8 * m.X[17])
        m.specs2 = Constraint(expr=m.X[10] >= 0.4 * m.X[17])
        m.specs3 = Constraint(expr=m.X[12] <= 5 * m.X[14])
        m.specs4 = Constraint(expr=m.X[12] >= 2 * m.X[14])

        # Logical constraints (big-M) for each process.
        # These allow for flow iff unit j exists
        m.logical1 = Constraint(expr=m.X[2] <= 10 * m.Y[1])
        m.logical2 = Constraint(expr=m.X[4] <= 10 * m.Y[2])
        m.logical3 = Constraint(expr=m.X[9] <= 10 * m.Y[3])
        m.logical4 = Constraint(expr=m.X[12] + m.X[14] <= 10 * m.Y[4])
        m.logical5 = Constraint(expr=m.X[15] <= 10 * m.Y[5])
        m.logical6 = Constraint(expr=m.X[19] <= 10 * m.Y[6])
        m.logical7 = Constraint(expr=m.X[21] <= 10 * m.Y[7])
        m.logical8 = Constraint(expr=m.X[10] + m.X[17] <= 10 * m.Y[8])

        # pure integer constraints
        m.pureint1 = Constraint(expr=m.Y[1] + m.Y[2] == 1)
        m.pureint2 = Constraint(expr=m.Y[4] + m.Y[5] <= 1)
        m.pureint3 = Constraint(expr=m.Y[6] + m.Y[7] - m.Y[4] == 0)
        m.pureint4 = Constraint(expr=m.Y[3] - m.Y[8] <= 0)

        """Cost (objective) function definition"""
        m.cost = Objective(expr=sum(Y[j] * CF[j] for j in J) +
                           sum(X[i] * CV[i] for i in I) + CONSTANT,
                           sense=minimize)

        """Bound definitions"""
        # x (flow) upper bounds
        x_ubs = {3: 2, 5: 2, 9: 2, 10: 1, 14: 1, 17: 2, 19: 2, 21: 2, 25: 3}
        for i, x_ub in iteritems(x_ubs):
            X[i].setub(x_ub)
コード例 #31
0
 def gt2(b, t):
     return 1 / (exp(1800 / b.temperature_coal[t]) - 1)
コード例 #32
0
 def gt2_flyash_eqn(b, t):
     return b.gt2_flyash[t] \
         * (exp(1800/b.flue_gas[t].temperature)-1) == 1
コード例 #33
0
 def f(model):
     return model.x[1]**4 + (model.x[1] + model.x[2])**2 + (
         -1.0 + pyo.exp(model.x[2]))**2