예제 #1
0
model.pTrue = Param(initialize=1)
model.pFalse = Param(initialize=-1)

model.vN1 = Var(initialize=-1)
model.vP1 = Var(initialize=1)
model.v0 = Var(initialize=0)
model.vN2 = Var(initialize=-2)
model.vP2 = Var(initialize=2)

model.obj = Objective(
    expr=10.0 * Expr_if(IF=model.v0, THEN=model.vTrue, ELSE=model.vFalse))

# True/False
model.c1 = Constraint(
    expr=Expr_if(IF=(0), THEN=(model.vTrue), ELSE=(
        model.vFalse)) == model.pFalse)
model.c2 = Constraint(
    expr=Expr_if(IF=(1), THEN=(model.vTrue), ELSE=(
        model.vFalse)) == model.pTrue)

# x <= 0
model.c3 = Constraint(
    expr=Expr_if(IF=(model.vN1 <= 0), THEN=(model.vTrue), ELSE=(
        model.vFalse)) == model.pTrue)
model.c4 = Constraint(
    expr=Expr_if(IF=(model.v0 <= 0), THEN=(model.vTrue), ELSE=(
        model.vFalse)) == model.pTrue)
model.c5 = Constraint(
    expr=Expr_if(IF=(model.vP1 <= 0), THEN=(model.vTrue), ELSE=(
        model.vFalse)) == model.pFalse)
예제 #2
0
    def test_sim_initialization_multi_index(self):

        m = self.m
        m.w1 = Var(m.t, m.s)
        m.dw1 = DerivativeVar(m.w1)

        m.w2 = Var(m.s, m.t)
        m.dw2 = DerivativeVar(m.w2)

        m.w3 = Var([0, 1], m.t, m.s)
        m.dw3 = DerivativeVar(m.w3)

        t = IndexTemplate(m.t)

        def _deq1(m, t, s):
            return m.dw1[t, s] == m.w1[t, s]

        m.deq1 = Constraint(m.t, m.s, rule=_deq1)

        def _deq2(m, s, t):
            return m.dw2[s, t] == m.w2[s, t]

        m.deq2 = Constraint(m.s, m.t, rule=_deq2)

        def _deq3(m, i, t, s):
            return m.dw3[i, t, s] == m.w1[t, s] + m.w2[i + 1, t]

        m.deq3 = Constraint([0, 1], m.t, m.s, rule=_deq3)

        mysim = Simulator(m)

        self.assertIs(mysim._contset, m.t)
        self.assertEqual(len(mysim._diffvars), 12)
        self.assertTrue(_GetItemIndexer(m.w1[t, 1]) in mysim._diffvars)
        self.assertTrue(_GetItemIndexer(m.w1[t, 3]) in mysim._diffvars)
        self.assertTrue(_GetItemIndexer(m.w2[1, t]) in mysim._diffvars)
        self.assertTrue(_GetItemIndexer(m.w2[3, t]) in mysim._diffvars)
        self.assertTrue(_GetItemIndexer(m.w3[0, t, 1]) in mysim._diffvars)
        self.assertTrue(_GetItemIndexer(m.w3[1, t, 3]) in mysim._diffvars)

        self.assertEqual(len(mysim._derivlist), 12)
        self.assertTrue(_GetItemIndexer(m.dw1[t, 1]) in mysim._derivlist)
        self.assertTrue(_GetItemIndexer(m.dw1[t, 3]) in mysim._derivlist)
        self.assertTrue(_GetItemIndexer(m.dw2[1, t]) in mysim._derivlist)
        self.assertTrue(_GetItemIndexer(m.dw2[3, t]) in mysim._derivlist)
        self.assertTrue(_GetItemIndexer(m.dw3[0, t, 1]) in mysim._derivlist)
        self.assertTrue(_GetItemIndexer(m.dw3[1, t, 3]) in mysim._derivlist)

        self.assertEqual(len(mysim._templatemap), 6)
        self.assertTrue(_GetItemIndexer(m.w1[t, 1]) in mysim._templatemap)
        self.assertTrue(_GetItemIndexer(m.w1[t, 3]) in mysim._templatemap)
        self.assertTrue(_GetItemIndexer(m.w2[1, t]) in mysim._templatemap)
        self.assertTrue(_GetItemIndexer(m.w2[3, t]) in mysim._templatemap)
        self.assertFalse(_GetItemIndexer(m.w3[0, t, 1]) in mysim._templatemap)
        self.assertFalse(_GetItemIndexer(m.w3[1, t, 3]) in mysim._templatemap)

        self.assertEqual(len(mysim._rhsdict), 12)
        self.assertTrue(
            isinstance(mysim._rhsdict[_GetItemIndexer(m.dw1[t, 1])], Param))
        self.assertTrue(
            isinstance(mysim._rhsdict[_GetItemIndexer(m.dw1[t, 3])], Param))
        self.assertTrue(
            isinstance(mysim._rhsdict[_GetItemIndexer(m.dw2[1, t])], Param))
        self.assertTrue(
            isinstance(mysim._rhsdict[_GetItemIndexer(m.dw2[3, t])], Param))
        self.assertTrue(
            isinstance(mysim._rhsdict[_GetItemIndexer(m.dw3[0, t, 1])],
                       EXPR.SumExpression))
        self.assertTrue(
            isinstance(mysim._rhsdict[_GetItemIndexer(m.dw3[1, t, 3])],
                       EXPR.SumExpression))
        self.assertEqual(mysim._rhsdict[_GetItemIndexer(m.dw1[t, 1])].name,
                         "'w1[{t},1]'")
        self.assertEqual(mysim._rhsdict[_GetItemIndexer(m.dw1[t, 3])].name,
                         "'w1[{t},3]'")
        self.assertEqual(mysim._rhsdict[_GetItemIndexer(m.dw2[1, t])].name,
                         "'w2[1,{t}]'")
        self.assertEqual(mysim._rhsdict[_GetItemIndexer(m.dw2[3, t])].name,
                         "'w2[3,{t}]'")

        self.assertEqual(len(mysim._rhsfun(0, [0] * 12)), 12)
        self.assertIsNone(mysim._tsim)
        self.assertIsNone(mysim._simsolution)

        m.del_component('deq1')
        m.del_component('deq1_index')
        m.del_component('deq2')
        m.del_component('deq2_index')
        m.del_component('deq3')
        m.del_component('deq3_index')
예제 #3
0
    def run_impactmodel(self,
                        solver=None,
                        output=None,
                        tol=1e-6,
                        DisWeight=1.75,
                        RatWeight=2):
        """
        Run the **MRIA** model with disruptions. This will return an economy with a new equilibrium, based on the new production and demand values.
        
        Parameters
            - *self* - **MRIA_IO** class object
            - solver - Specify the solver to be used with Pyomo. The Default value is set to **None**. If set to **None**, the ipopt solver will be used
            - output - Specify whether you want the solver to print its progress.The default value is set to **None**
            - tol - the tolerance value that determines whether the outcome of the model is feasible. The default value is set to **1e-6**
            - DisWeight - the weight that determines the penalty set to let the model allow for additional imports. A higher penalty value will result in less imports. The default value is set to **1.75**
            - RatWeight - the weight that determines the penalty set to let the model allow to ration goods. A higher penalty value will result in less rationing. The default value is set to **2**
    
        Outputs
            - returns the output of an optimized **MRIA_IO** class and the **MRIA** model

        """
        model = self.m

        if solver is None:
            solver = 'ipopt'

        if DisWeight is None:
            DisWeight = 1.75

        if RatWeight is None:
            RatWeight = 2

        def demDisRat(model, R, S):
            return (self.Demand[R, S] == (
                sum(self.A_matrix[R, S, R, Sb] * self.X[R, Sb]
                    for Sb in model.Sb) + self.lfd[R, S] + self.Rdem[R, S] -
                self.Rat[R, S] +
                sum(self.ImportShare[R, Rb, S] *
                    (sum(self.A_matrix[R, S, Rb, Sb] * self.X[Rb, Sb]
                         for Sb in model.Sb) + self.fd[Rb, S] +
                     self.Rdem[Rb, S] - self.Rat[Rb, S])
                    for Rb in model.Rb if (R != Rb)) +
                sum(self.ImportShare[R, Rb, S] * (self.DisImp[Rb, S])
                    for Rb in model.Rb if (R != Rb)) + self.ExpROW[R, S]))

        model.demDisRat = Constraint(model.R,
                                     model.S,
                                     rule=demDisRat,
                                     doc='Satisfy demand')

        def demsupDis(model, R, S):
            return (self.DisImp[R, S] + self.X[R, S]) >= self.Demand[R, S]

        model.demsupDis = Constraint(model.R,
                                     model.S,
                                     rule=demsupDis,
                                     doc='Satisfy demand')

        def DisImpA(model, R, S):
            return (self.DisImp[R, S] *
                    (self.DisImp[R, S] + (self.Xbase[R, S] * self.X_up[R, S]) -
                     self.Demand[R, S])) == 0

        model.DisImpA = Constraint(model.R,
                                   model.S,
                                   rule=DisImpA,
                                   doc='Satisfy demand')

        def DisImpEq(model, R, S):
            #    return m.DisImp[R, S] >=  (m.Demand[R, S] - (m.X[R, S]))
            return self.DisImp[R, S] >= (self.Demand[R, S] -
                                         (self.X[R, S] * self.X_up[R, S]))

#        model.DisImpEq = Constraint(model.R, model.S, rule=DisImpEq, doc='Satisfy demand')

        def ObjectiveDis2(model):
            return (sum(self.X[R, S] for S in model.S
                        for R in model.R) + DisWeight * sum(
                            (self.Ratmarg[R, S] * self.DisImp[R, S])
                            for R in model.R
                            for S in model.S) + RatWeight * sum(
                                (self.Ratmarg[R, S] * self.Rat[R, S])
                                for R in model.R for S in model.S) +
                    sum((sum(self.ImportShare[R, Rb, S] *
                             (sum(self.A_matrix[R, S, Rb, Sb] * self.X[Rb, Sb]
                                  for Sb in model.Sb) + self.fd[Rb, S] +
                              self.Rdem[Rb, S] - self.Rat[Rb, S])
                             for Rb in model.Rb if (R != Rb)) +
                         sum(self.ImportShare[R, Rb, S] * (self.DisImp[Rb, S])
                             for Rb in model.Rb if (R != Rb))) for R in model.R
                        for S in model.S))

        model.objective = Objective(rule=ObjectiveDis2,
                                    sense=minimize,
                                    doc='Define objective function')

        opt = SolverFactory(solver)
        if solver == 'ipopt':
            opt.options['max_iter'] = 7500
            opt.options['warm_start_init_point'] = 'yes'
            opt.options['warm_start_bound_push'] = 1e-6
            opt.options['warm_start_mult_bound_push'] = 1e-6
            opt.options['mu_init'] = 1e-6
            #opt.options['hessian_approximation'] = 'limited-memory'

            #opt.options['bound_relax_factor'] = 0
            if tol != 1e-6:
                opt.options['tol'] = tol

        if output is None:
            results = opt.solve(model, tee=False)
            return results.solver.status
        else:
            results = opt.solve(model, tee=True)
            # sends results to stdout
            results.write()
            return results.solver.status
예제 #4
0
 def test_bounds_sat(self):
     m = ConcreteModel()
     m.x = Var(bounds=(0, 5))
     m.c1 = Constraint(expr=4.99 == m.x)
     m.o = Objective(expr=m.x)
     self.assertTrue(satisfiable(m))
예제 #5
0
 def test_unhandled_expressions(self):
     m = ConcreteModel()
     m.x = Var()
     m.c1 = Constraint(expr=0 <= log(m.x))
     self.assertTrue(satisfiable(m))
예제 #6
0
 def test_integer_domains(self):
     m = ConcreteModel()
     m.x1 = Var(domain=PositiveIntegers)
     m.c1 = Constraint(expr=m.x1 == 0.5)
     self.assertFalse(satisfiable(m))
예제 #7
0
 def test_binary_domains(self):
     m = ConcreteModel()
     m.x1 = Var(domain=Binary)
     m.c1 = Constraint(expr=m.x1 == 2)
     self.assertFalse(satisfiable(m))
예제 #8
0
파일: test_model.py 프로젝트: vova292/pyomo
    def test_solve1(self):
        model = ConcreteModel()
        model.A = RangeSet(1, 4)
        model.x = Var(model.A, bounds=(-1, 1))

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

        model.obj = Objective(rule=obj_rule)

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

        model.c = Constraint(rule=c_rule)
        opt = SolverFactory('glpk')
        results = opt.solve(model, symbolic_solver_labels=True)
        model.solutions.store_to(results)
        results.write(filename=join(currdir, "solve1.out"), format='json')
        self.assertMatchesJsonBaseline(join(currdir, "solve1.out"),
                                       join(currdir, "solve1.txt"),
                                       tolerance=1e-4)

        #
        def d_rule(model):
            return model.x[1] >= 0

        model.d = Constraint(rule=d_rule)
        model.d.deactivate()
        results = opt.solve(model)
        model.solutions.store_to(results)
        results.write(filename=join(currdir, "solve1x.out"), format='json')
        self.assertMatchesJsonBaseline(join(currdir, "solve1x.out"),
                                       join(currdir, "solve1.txt"),
                                       tolerance=1e-4)
        #
        model.d.activate()
        results = opt.solve(model)
        model.solutions.store_to(results)
        results.write(filename=join(currdir, "solve1a.out"), format='json')
        self.assertMatchesJsonBaseline(join(currdir, "solve1a.out"),
                                       join(currdir, "solve1a.txt"),
                                       tolerance=1e-4)
        #
        model.d.deactivate()

        def e_rule(model, i):
            return model.x[i] >= 0

        model.e = Constraint(model.A, rule=e_rule)
        for i in model.A:
            model.e[i].deactivate()
        results = opt.solve(model)
        model.solutions.store_to(results)
        results.write(filename=join(currdir, "solve1y.out"), format='json')
        self.assertMatchesJsonBaseline(join(currdir, "solve1y.out"),
                                       join(currdir, "solve1.txt"),
                                       tolerance=1e-4)
        #
        model.e.activate()
        results = opt.solve(model)
        model.solutions.store_to(results)
        results.write(filename=join(currdir, "solve1b.out"), format='json')
        self.assertMatchesJsonBaseline(join(currdir, "solve1b.out"),
                                       join(currdir, "solve1b.txt"),
                                       tolerance=1e-4)
예제 #9
0
파일: test_model.py 프로젝트: vova292/pyomo
    def test_solve_with_pickle_then_clone(self):
        # This tests github issue Pyomo-#65
        model = ConcreteModel()
        model.A = RangeSet(1, 4)
        model.b = Block()
        model.b.x = Var(model.A, bounds=(-1, 1))
        model.b.obj = Objective(expr=sum_product(model.b.x))
        model.c = Constraint(expr=model.b.x[1] >= 0)
        opt = SolverFactory('glpk')
        self.assertEqual(len(model.solutions), 0)
        results = opt.solve(model, symbolic_solver_labels=True)
        self.assertEqual(len(model.solutions), 1)
        #
        self.assertEqual(model.solutions[0].gap, 0.0)
        #self.assertEqual(model.solutions[0].status, SolutionStatus.feasible)
        self.assertEqual(model.solutions[0].message, None)
        #
        buf = pickle.dumps(model)
        tmodel = pickle.loads(buf)
        self.assertEqual(len(tmodel.solutions), 1)
        self.assertEqual(tmodel.solutions[0].gap, 0.0)
        #self.assertEqual(tmodel.solutions[0].status, SolutionStatus.feasible)
        self.assertEqual(tmodel.solutions[0].message, None)
        self.assertIn(id(tmodel.b.obj),
                      tmodel.solutions[0]._entry['objective'])
        self.assertIs(
            tmodel.b.obj,
            tmodel.solutions[0]._entry['objective'][id(tmodel.b.obj)][0]())

        inst = tmodel.clone()

        # make sure the clone has all the attributes
        self.assertTrue(hasattr(inst, 'A'))
        self.assertTrue(hasattr(inst, 'b'))
        self.assertTrue(hasattr(inst.b, 'x'))
        self.assertTrue(hasattr(inst.b, 'obj'))
        self.assertTrue(hasattr(inst, 'c'))
        # and that they were all copied
        self.assertIsNot(inst.A, tmodel.A)
        self.assertIsNot(inst.b, tmodel.b)
        self.assertIsNot(inst.b.x, tmodel.b.x)
        self.assertIsNot(inst.b.obj, tmodel.b.obj)
        self.assertIsNot(inst.c, tmodel.c)

        # Make sure the solution is on the new model
        self.assertTrue(hasattr(inst, 'solutions'))
        self.assertEqual(len(inst.solutions), 1)
        self.assertEqual(inst.solutions[0].gap, 0.0)
        #self.assertEqual(inst.solutions[0].status, SolutionStatus.feasible)
        self.assertEqual(inst.solutions[0].message, None)

        # Spot-check some components and make sure all the weakrefs in
        # the ModelSOlution got updated
        self.assertIn(id(inst.b.obj), inst.solutions[0]._entry['objective'])
        _obj = inst.solutions[0]._entry['objective'][id(inst.b.obj)]
        self.assertIs(_obj[0](), inst.b.obj)

        for v in [1, 2, 3, 4]:
            self.assertIn(id(inst.b.x[v]),
                          inst.solutions[0]._entry['variable'])
            _v = inst.solutions[0]._entry['variable'][id(inst.b.x[v])]
            self.assertIs(_v[0](), inst.b.x[v])
예제 #10
0
파일: opt.py 프로젝트: yonggaradit/PyPSA
def l_constraint(model, name, constraints, *args):
    """A replacement for pyomo's Constraint that quickly builds linear
    constraints.

    Instead of

    model.name = Constraint(index1,index2,...,rule=f)

    call instead

    l_constraint(model,name,constraints,index1,index2,...)

    where constraints is a dictionary of constraints of the form:

    constraints[i] = LConstraint object

    OR using the soon-to-be-deprecated list format:

    constraints[i] = [[(coeff1,var1),(coeff2,var2),...],sense,constant_term]

    i.e. the first argument is a list of tuples with the variables and their
    coefficients, the second argument is the sense string (must be one of
    "==","<=",">=","><") and the third argument is the constant term
    (a float). The sense "><" allows lower and upper bounds and requires
    `constant_term` to be a 2-tuple.

    Variables may be repeated with different coefficients, which pyomo
    will sum up.

    Parameters
    ----------
    model : pyomo.environ.ConcreteModel
    name : string
        Name of constraints to be constructed
    constraints : dict
        A dictionary of constraints (see format above)
    *args :
        Indices of the constraints

    """

    setattr(model, name, Constraint(*args, noruleinit=True))
    v = getattr(model, name)
    for i in v._index:
        c = constraints[i]
        if isinstance(c, LConstraint):
            variables = c.lhs.variables + [(-item[0], item[1])
                                           for item in c.rhs.variables]
            sense = c.sense
            constant = c.rhs.constant - c.lhs.constant
        else:
            variables = c[0]
            sense = c[1]
            constant = c[2]

        v._data[i] = pyomo.core.base.constraint._GeneralConstraintData(None, v)
        v._data[i]._body = _build_sum_expression(variables)

        if sense == "==":
            v._data[i]._equality = True
            v._data[i]._lower = pyomo.core.base.numvalue.NumericConstant(
                constant)
            v._data[i]._upper = pyomo.core.base.numvalue.NumericConstant(
                constant)
        elif sense == "<=":
            v._data[i]._equality = False
            v._data[i]._lower = None
            v._data[i]._upper = pyomo.core.base.numvalue.NumericConstant(
                constant)
        elif sense == ">=":
            v._data[i]._equality = False
            v._data[i]._lower = pyomo.core.base.numvalue.NumericConstant(
                constant)
            v._data[i]._upper = None
        elif sense == "><":
            v._data[i]._equality = False
            v._data[i]._lower = pyomo.core.base.numvalue.NumericConstant(
                constant[0])
            v._data[i]._upper = pyomo.core.base.numvalue.NumericConstant(
                constant[1])
        else:
            raise KeyError(
                '`sense` must be one of "==","<=",">=","><"; got: {}'.format(
                    sense))
예제 #11
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
예제 #12
0
    C = np.ones((n, n))
    for i in range(n):
        for j in range(n):
            if not ((data[i] == 1 and data[j] == 4) or
                    (data[i] == 4 and data[j] == 1)):
                if not ((data[i] == 2 and data[j] == 3) or
                        (data[i] == 3 and data[j] == 2)):
                    C[i, j] = 0.7
    return C


C = matrice_costi(data)

#constraint
model.onebond = Constraint(
    model.I,
    rule=lambda model, i: sum(model.P[i, j] + model.P[j, i]
                              for j in model.J) <= 1)


def stack_pairs1(model, i, j):
    return model.P[i, j] + model.P[i + 1, j - 1] - model.Q[i, j] <= 1


def stack_pairs2(model, i, j):
    return 2 * model.Q[i, j] - model.P[i, j] - model.P[i + 1, j - 1] <= 0


model.stack_pairs = ConstraintList()
for i in range(1, n + 1):
    for j in range(i + 1, n + 1):
        model.stack_pairs.add(stack_pairs1(model, i, j))
예제 #13
0
def define_state(b):
    # FTPx formulation always requires a flash, so set flag to True
    # TODO: should have some checking to make sure developers implement this properly
    b.always_flash = True

    # Check that only necessary state_bounds are defined
    expected_keys = ["flow_mol_comp", "enth_mol", "temperature", "pressure"]
    if (b.params.config.state_bounds is not None
            and any(b.params.config.state_bounds.keys()) not in expected_keys):
        for k in b.params.config.state_bounds.keys():
            if k not in expected_keys:
                raise ConfigurationError(
                    "{} - found unexpected state_bounds key {}. Please ensure "
                    "bounds are provided only for expected state variables "
                    "and that you have typed the variable names correctly.".
                    format(b.name, k))

    units = b.params.get_metadata().derived_units
    # Get bounds and initial values from config args
    f_bounds, f_init = get_bounds_from_config(b, "flow_mol_comp",
                                              units["flow_mole"])
    h_bounds, h_init = get_bounds_from_config(b, "enth_mol",
                                              units["energy_mole"])
    p_bounds, p_init = get_bounds_from_config(b, "pressure", units["pressure"])
    t_bounds, t_init = get_bounds_from_config(b, "temperature",
                                              units["temperature"])

    # Add state variables
    b.flow_mol_comp = Var(b.component_list,
                          initialize=f_init,
                          domain=NonNegativeReals,
                          bounds=f_bounds,
                          doc='Component molar flowrate',
                          units=units["flow_mole"])
    b.pressure = Var(initialize=p_init,
                     domain=NonNegativeReals,
                     bounds=p_bounds,
                     doc='State pressure',
                     units=units["pressure"])
    b.enth_mol = Var(initialize=h_init,
                     domain=NonNegativeReals,
                     bounds=h_bounds,
                     doc='Mixture molar specific enthalpy',
                     units=units["energy_mole"])

    # Add supporting variables
    b.flow_mol = Expression(expr=sum(b.flow_mol_comp[j]
                                     for j in b.component_list),
                            doc="Total molar flowrate")

    if f_init is None:
        fp_init = None
    else:
        fp_init = f_init / len(b.phase_list)

    b.flow_mol_phase = Var(b.phase_list,
                           initialize=fp_init,
                           domain=NonNegativeReals,
                           bounds=f_bounds,
                           doc='Phase molar flow rates',
                           units=units["flow_mole"])

    b.temperature = Var(initialize=t_init,
                        domain=NonNegativeReals,
                        bounds=t_bounds,
                        doc='Temperature',
                        units=units["temperature"])

    b.mole_frac_comp = Var(b.component_list,
                           bounds=(0, None),
                           initialize=1 / len(b.component_list),
                           doc='Mixture mole fractions',
                           units=None)

    b.mole_frac_phase_comp = Var(b.phase_component_set,
                                 initialize=1 / len(b.component_list),
                                 bounds=(0, None),
                                 doc='Phase mole fractions',
                                 units=None)

    def Fpc_expr(b, p, j):
        return b.flow_mol_phase[p] * b.mole_frac_phase_comp[p, j]

    b.flow_mol_phase_comp = Expression(b.phase_component_set,
                                       rule=Fpc_expr,
                                       doc='Phase-component molar flowrates')

    b.phase_frac = Var(b.phase_list,
                       initialize=1 / len(b.phase_list),
                       bounds=(0, None),
                       doc='Phase fractions',
                       units=None)

    # Add electrolye state vars if required
    # This must occur before adding the enthalpy constraint, as it needs true
    # species mole fractions
    if b.params._electrolyte:
        define_electrolyte_state(b)

    # Add supporting constraints
    def rule_mole_frac_comp(b, j):
        if len(b.component_list) > 1:
            return b.flow_mol_comp[j] == b.mole_frac_comp[j] * sum(
                b.flow_mol_comp[k] for k in b.component_list)
        else:
            return b.mole_frac_comp[j] == 1

    b.mole_frac_comp_eq = Constraint(b.component_list,
                                     rule=rule_mole_frac_comp)

    def rule_enth_mol(b):
        return b.enth_mol == sum(b.enth_mol_phase[p] * b.phase_frac[p]
                                 for p in b.phase_list)

    b.enth_mol_eq = Constraint(rule=rule_enth_mol,
                               doc="Total molar enthalpy mixing rule")

    if len(b.phase_list) == 1:

        def rule_total_mass_balance(b):
            return b.flow_mol_phase[b.phase_list[1]] == b.flow_mol

        b.total_flow_balance = Constraint(rule=rule_total_mass_balance)

        def rule_comp_mass_balance(b, i):
            return b.mole_frac_comp[i] == \
                b.mole_frac_phase_comp[b.phase_list[1], i]

        b.component_flow_balances = Constraint(b.component_list,
                                               rule=rule_comp_mass_balance)

        def rule_phase_frac(b, p):
            return b.phase_frac[p] == 1

        b.phase_fraction_constraint = Constraint(b.phase_list,
                                                 rule=rule_phase_frac)

    elif len(b.phase_list) == 2:
        # For two phase, use Rachford-Rice formulation
        def rule_total_mass_balance(b):
            return sum(b.flow_mol_phase[p] for p in b.phase_list) == \
                b.flow_mol

        b.total_flow_balance = Constraint(rule=rule_total_mass_balance)

        def rule_comp_mass_balance(b, i):
            return b.flow_mol_comp[i] == sum(
                b.flow_mol_phase[p] * b.mole_frac_phase_comp[p, i]
                for p in b.phase_list if (p, i) in b.phase_component_set)

        b.component_flow_balances = Constraint(b.component_list,
                                               rule=rule_comp_mass_balance)

        def rule_mole_frac(b):
            return sum(b.mole_frac_phase_comp[b.phase_list[1], i]
                       for i in b.component_list
                       if (b.phase_list[1], i) in b.phase_component_set) -\
                sum(b.mole_frac_phase_comp[b.phase_list[2], i]
                    for i in b.component_list
                    if (b.phase_list[2], i) in b.phase_component_set) == 0

        b.sum_mole_frac = Constraint(rule=rule_mole_frac)

        def rule_phase_frac(b, p):
            return b.phase_frac[p] * b.flow_mol == b.flow_mol_phase[p]

        b.phase_fraction_constraint = Constraint(b.phase_list,
                                                 rule=rule_phase_frac)

    else:
        # Otherwise use a general formulation
        def rule_comp_mass_balance(b, i):
            return b.flow_mol_comp[i] == sum(
                b.flow_mol_phase[p] * b.mole_frac_phase_comp[p, i]
                for p in b.phase_list if (p, i) in b.phase_component_set)

        b.component_flow_balances = Constraint(b.component_list,
                                               rule=rule_comp_mass_balance)

        def rule_mole_frac(b, p):
            return sum(b.mole_frac_phase_comp[p, i] for i in b.component_list
                       if (p, i) in b.phase_component_set) == 1

        b.sum_mole_frac = Constraint(b.phase_list, rule=rule_mole_frac)

        def rule_phase_frac(b, p):
            return b.phase_frac[p] * b.flow_mol == b.flow_mol_phase[p]

        b.phase_fraction_constraint = Constraint(b.phase_list,
                                                 rule=rule_phase_frac)

    # -------------------------------------------------------------------------
    # General Methods
    def get_material_flow_terms_FcPh(p, j):
        """Create material flow terms for control volume."""
        return b.flow_mol_phase_comp[p, j]

    b.get_material_flow_terms = get_material_flow_terms_FcPh

    def get_enthalpy_flow_terms_FcPh(p):
        """Create enthalpy flow terms."""
        # enth_mol_phase probably does not exist when this is created
        # Use try/except to build flow term if not present
        try:
            eflow = b._enthalpy_flow_term
        except AttributeError:

            def rule_eflow(b, p):
                return b.flow_mol_phase[p] * b.enth_mol_phase[p]

            eflow = b._enthalpy_flow_term = Expression(b.phase_list,
                                                       rule=rule_eflow)
        return eflow[p]

    b.get_enthalpy_flow_terms = get_enthalpy_flow_terms_FcPh

    def get_material_density_terms_FcPh(p, j):
        """Create material density terms."""
        # dens_mol_phase probably does not exist when this is created
        # Use try/except to build term if not present
        try:
            mdens = b._material_density_term
        except AttributeError:

            def rule_mdens(b, p, j):
                return b.dens_mol_phase[p] * b.mole_frac_phase_comp[p, j]

            mdens = b._material_density_term = Expression(
                b.phase_component_set, rule=rule_mdens)
        return mdens[p, j]

    b.get_material_density_terms = get_material_density_terms_FcPh

    def get_energy_density_terms_FcPh(p):
        """Create energy density terms."""
        # Density and energy terms probably do not exist when this is created
        # Use try/except to build term if not present
        try:
            edens = b._energy_density_term
        except AttributeError:

            def rule_edens(b, p):
                return b.dens_mol_phase[p] * b.energy_internal_mol_phase[p]

            edens = b._energy_density_term = Expression(b.phase_list,
                                                        rule=rule_edens)
        return edens[p]

    b.get_energy_density_terms = get_energy_density_terms_FcPh

    def default_material_balance_type_FcPh():
        return MaterialBalanceType.componentTotal

    b.default_material_balance_type = default_material_balance_type_FcPh

    def default_energy_balance_type_FcPh():
        return EnergyBalanceType.enthalpyTotal

    b.default_energy_balance_type = default_energy_balance_type_FcPh

    def get_material_flow_basis_FcPh():
        return MaterialFlowBasis.molar

    b.get_material_flow_basis = get_material_flow_basis_FcPh

    def define_state_vars_FcPh():
        """Define state vars."""
        return {
            "flow_mol_comp": b.flow_mol_comp,
            "enth_mol": b.enth_mol,
            "pressure": b.pressure
        }

    b.define_state_vars = define_state_vars_FcPh

    def define_display_vars_FcPh():
        """Define display vars."""
        return {
            "Molar Flowrate": b.flow_mol_comp,
            "Molar Enthalpy": b.enth_mol,
            "Pressure": b.pressure
        }

    b.define_display_vars = define_display_vars_FcPh
예제 #14
0
m.tf = Var(initialize=1.0)
m.a.fix()
m.tf.fix()

m.dtime = Var()  #DerivativeVar(m.time)
m.dx = Var()  #DerivativeVar(m.x)
m.dv = Var()  #DerivativeVar(m.v)

#m.obj = Objective(expr=m.tf)

#def _ode1(m,i):
#    if i == 0 :
#        return Constraint.Skip
#    return m.dx[i] == m.tf * m.v[i]
#m.ode1 = Constraint(m.tau, rule=_ode1)
m.ode1 = Constraint(expr=m.dx == m.tf * m.v)

#def _ode2(m,i):
#    if i == 0 :
#        return Constraint.Skip
#    return m.dv[i] == m.tf*(m.a[i] - m.R*m.v[i]**2)
#m.ode2 = Constraint(m.tau, rule=_ode2)
m.ode2 = Constraint(expr=m.dv == m.tf * (m.a - m.R * m.v**2))

#def _ode3(m,i):
#    if i == 0:
#        return Constraint.Skip
#    return m.dtime[i] == m.tf
#m.ode3 = Constraint(m.tau, rule=_ode3)
m.ode3 = Constraint(expr=m.dtime == m.tf)
예제 #15
0
def optimize_distribution(network,
                          R,
                          B,
                          num_balls,
                          goal='min',
                          print_res=False,
                          debug=False):
    N = len(network)
    goal = minimize if goal == 'min' else maximize

    # Define exposure function
    def exposure(model):
        exp = 0
        for node in network:  # For each node
            r_sum, b_sum = 0, 0
            for ind in node:  # Sum all neighbours
                r_sum += model.Fixed[ind]
                b_sum += model.Variable[ind]

            if (r_sum +
                    b_sum) != 0:  # Only add to sum if non-zero denominator.
                exp += r_sum / (r_sum + b_sum)
            else:
                exp += .5

        return exp / N

    # Constraint function for problem
    def ball_constraint(model):
        return summation(model.Variable) == num_balls

    # Function to initialize black values
    def black_init(_, i):
        return B[i]

    # Function to initialize red values
    def red_init(_, i):
        return R[i]

    # Initialize values
    model = ConcreteModel()
    model.F = RangeSet(0, N - 1)
    model.V = RangeSet(0, N - 1)

    # Initialize fixed balls
    model.Fixed = Param(model.F, within=NonNegativeReals, default=red_init)

    # Initialize variable balls
    model.Variable = Var(model.V,
                         domain=NonNegativeReals,
                         bounds=(0, num_balls),
                         initialize=black_init)

    # Define objective function
    model.exposure = Objective(rule=exposure, sense=goal)

    # Define constraint function
    model.constraint = Constraint(rule=ball_constraint)

    # Initialize (ipopt) solver
    solver = SolverFactory('ipopt', executable=ipopt_path)
    # solver = SolverFactory('bonmin', executable='~/.couenne/Couenne-0.5.7/build/bin/bonmin')
    # solver = SolverFactory('couenne', executable='~/.couenne/Couenne-0.5.7/build/bin/couenne')

    # Solve model
    solver.solve(model, tee=debug)

    # Print resulting distribution
    optimal = [0] * N
    if print_res: print('Variable_Fixed')

    for i in range(N):
        optimal[i] = round(model.Variable[i]())

        if print_res:
            print(
                str(i) + ': ' + str(optimal[i]) + '_' +
                str(round(model.Fixed[i])))
    final_exp = round(model.exposure() * 1000) / 1000
    if print_res: print('Final exposure: ' + str(final_exp))

    return optimal, final_exp
예제 #16
0
파일: test_model.py 프로젝트: vova292/pyomo
 def make_invalid(m):
     m.I = RangeSet(3)
     m.x = Var(m.I)
     m.c = Constraint(expr=sum(m.x[i] for i in m.I) >= 0)
예제 #17
0
 def test_abs_expressions(self):
     m = ConcreteModel()
     m.x = Var()
     m.c1 = Constraint(expr=-0.001 >= abs(m.x))
     m.o = Objective(expr=m.x)
     self.assertFalse(satisfiable(m))
예제 #18
0
def define_model(graph, K):
    # childrenを持つkのid
    K_id_has_children = K.get_id_has_children()
    # childrenを持たないkのid
    K_id_has_no_children = K.get_id_has_no_children()

    edges = edge_weight(graph, K)

    model = ConcreteModel()
    model.K = Set(initialize=K_id_has_children)

    def X_init(model):
        result = []
        for k in model.K:
            for i in range(1, len(K[k].children) + 1):
                for node in K[k].children:
                    result.append((i, node.kid, k))
        return result

    model.X = Set(dimen=3, initialize=X_init)
    model.x = Var(model.X, within=Binary)

    def permutation_i(model, _, j, k):
        i_set = set([x[0] for x in model.x if x[2] == k])
        return sum([model.x[(i, j, k)] for i in i_set]) == 1

    model.x_i_constraint = Constraint(model.X, rule=permutation_i)

    def permutation_j(model, i, _, k):
        j_set = set([x[1] for x in model.x if x[2] == k])
        return sum([model.x[(i, j, k)] for j in j_set]) == 1

    model.x_j_constraint = Constraint(model.X, rule=permutation_j)

    # l: box[0], box[1], k
    # 左右の関係
    def L_init(model):
        result = []
        for k in model.K:
            for a, b in itertools.permutations(K[k].children, 2):
                result.append((a.kid, b.kid, k))
        return result

    model.L = Set(dimen=3, initialize=L_init)
    model.l = Var(model.L, within=Binary)

    M = 1000

    def l_rule1(model, a, b, k):
        return model.l[(a, b, k)] + model.l[(b, a, k)] == 1

    model.l_constraint1 = Constraint(model.L, rule=l_rule1)

    # あるボックスjのiの値
    def box_order(model, j, k):
        box_j = [i * model.x[(i, j, k)] for i in range(1, K.k_boxsize(k) + 1)]
        return sum(box_j)

    def l_rule2(model, a, b, k):
        box_a = box_order(model, a, k)
        box_b = box_order(model, b, k)
        return box_b - box_a - M * model.l[(a, b, k)] <= 0

    model.l_constraint2 = Constraint(model.L, rule=l_rule2)

    def get_x_coord(model, j, k):
        '''あるkでのあるボックスjのx座標'''
        j_width = K[j].width
        return sum(
            sum(K[j2].width * model.l[(j2, j1, K[j1].parent.kid)]
                for j2 in K.neighbors(j1))
            for j1 in K.ancestors_x(j)) + j_width / 2

    def get_y_coord(model, j, k):
        '''あるkでのあるボックスjのy座標'''
        j_height = K[j].height
        return sum(
            sum(K[j2].height * model.l[(j2, j1, K[j1].parent.kid)]
                for j2 in K.neighbors(j1))
            for j1 in K.ancestors_y(j)) + j_height / 2

    def D_init(model):
        return itertools.permutations(K_id_has_no_children, 2)

    model.D = Set(dimen=2, initialize=D_init)

    # d_x
    model.d_x = Var(model.D, within=NonNegativeReals)

    def d_x_rule(model, k_a, k_b):
        k_a_parent = K[k_a].parent.kid
        k_b_parent = K[k_b].parent.kid
        return (get_x_coord(model, k_a, k_a_parent) -
                get_x_coord(model, k_b, k_b_parent) - model.d_x[k_a, k_b] +
                model.d_x[k_b, k_a] == 0)

    model.constraint_d_x = Constraint(model.D, rule=d_x_rule)

    # d_y
    model.d_y = Var(model.D, within=NonNegativeReals)

    def d_y_rule(model, k_a, k_b):
        k_a_parent = K[k_a].parent.kid
        k_b_parent = K[k_b].parent.kid
        return (get_y_coord(model, k_a, k_a_parent) -
                get_y_coord(model, k_b, k_b_parent) - model.d_y[k_a, k_b] +
                model.d_y[k_b, k_a] == 0)

    model.constraint_d_y = Constraint(model.D, rule=d_y_rule)

    def obj_expression(model):
        return sum((edges[a][b] * model.d_x[(k_a, k_b)] +
                    edges[a][b] * model.d_y[(k_a, k_b)])
                   for a, k_a in enumerate(K_id_has_no_children)
                   for b, k_b in enumerate(K_id_has_no_children) if k_a != k_b)

    model.OBJ = Objective(rule=obj_expression)

    return model
예제 #19
0
 def test_real_domains(self):
     m = ConcreteModel()
     m.x1 = Var(domain=NonNegativeReals)
     m.c1 = Constraint(expr=m.x1 == -1.3)
     self.assertFalse(satisfiable(m))
예제 #20
0
def define_state(b):
    # FTPx formulation always requires a flash, so set flag to True
    # TODO: should have some checking to make sure developers implement this properly
    b.always_flash = True

    units = b.params.get_metadata().derived_units
    # Get bounds and initial values from config args
    f_bounds, f_init = get_bounds_from_config(
        b, "flow_mol", units["flow_mole"])
    t_bounds, t_init = get_bounds_from_config(
        b, "temperature", units["temperature"])
    p_bounds, p_init = get_bounds_from_config(
        b, "pressure", units["pressure"])

    # Add state variables
    b.flow_mol = Var(initialize=f_init,
                     domain=NonNegativeReals,
                     bounds=f_bounds,
                     doc=' Total molar flowrate',
                     units=units["flow_mole"])
    b.mole_frac_comp = Var(b.params.component_list,
                           bounds=(0, None),
                           initialize=1 / len(b.params.component_list),
                           doc='Mixture mole fractions',
                           units=None)
    b.pressure = Var(initialize=p_init,
                     domain=NonNegativeReals,
                     bounds=p_bounds,
                     doc='State pressure',
                     units=units["pressure"])
    b.temperature = Var(initialize=t_init,
                        domain=NonNegativeReals,
                        bounds=t_bounds,
                        doc='State temperature',
                        units=units["temperature"])

    # Add supporting variables
    if f_init is None:
        fp_init = None
    else:
        fp_init = f_init / len(b.params.phase_list)

    b.flow_mol_phase = Var(b.params.phase_list,
                           initialize=fp_init,
                           domain=NonNegativeReals,
                           bounds=f_bounds,
                           doc='Phase molar flow rates',
                           units=units["flow_mole"])

    b.mole_frac_phase_comp = Var(
        b.params._phase_component_set,
        initialize=1/len(b.params.component_list),
        bounds=(0, None),
        doc='Phase mole fractions',
        units=None)

    b.phase_frac = Var(
        b.params.phase_list,
        initialize=1/len(b.params.phase_list),
        bounds=(0, None),
        doc='Phase fractions',
        units=None)

    # Add supporting constraints
    if b.config.defined_state is False:
        # applied at outlet only
        b.sum_mole_frac_out = Constraint(
            expr=1e3 == 1e3*sum(b.mole_frac_comp[i]
                                for i in b.params.component_list))

    if len(b.params.phase_list) == 1:
        def rule_total_mass_balance(b):
            return b.flow_mol_phase[b.params.phase_list[1]] == b.flow_mol
        b.total_flow_balance = Constraint(rule=rule_total_mass_balance)

        def rule_comp_mass_balance(b, i):
            return 1e3*b.mole_frac_comp[i] == \
                1e3*b.mole_frac_phase_comp[b.params.phase_list[1], i]
        b.component_flow_balances = Constraint(b.params.component_list,
                                               rule=rule_comp_mass_balance)

        def rule_phase_frac(b, p):
            return b.phase_frac[p] == 1
        b.phase_fraction_constraint = Constraint(b.params.phase_list,
                                                 rule=rule_phase_frac)

    elif len(b.params.phase_list) == 2:
        # For two phase, use Rachford-Rice formulation
        def rule_total_mass_balance(b):
            return sum(b.flow_mol_phase[p] for p in b.params.phase_list) == \
                b.flow_mol
        b.total_flow_balance = Constraint(rule=rule_total_mass_balance)

        def rule_comp_mass_balance(b, i):
            return b.flow_mol*b.mole_frac_comp[i] == sum(
                b.flow_mol_phase[p]*b.mole_frac_phase_comp[p, i]
                for p in b.params.phase_list
                if (p, i) in b.params._phase_component_set)
        b.component_flow_balances = Constraint(b.params.component_list,
                                               rule=rule_comp_mass_balance)

        def rule_mole_frac(b):
            return 1e3*sum(b.mole_frac_phase_comp[b.params.phase_list[1], i]
                           for i in b.params.component_list
                           if (b.params.phase_list[1], i)
                           in b.params._phase_component_set) -\
                1e3*sum(b.mole_frac_phase_comp[b.params.phase_list[2], i]
                        for i in b.params.component_list
                        if (b.params.phase_list[2], i)
                        in b.params._phase_component_set) == 0
        b.sum_mole_frac = Constraint(rule=rule_mole_frac)

        def rule_phase_frac(b, p):
            return b.phase_frac[p]*b.flow_mol == b.flow_mol_phase[p]
        b.phase_fraction_constraint = Constraint(b.params.phase_list,
                                                 rule=rule_phase_frac)

    else:
        # Otherwise use a general formulation
        def rule_comp_mass_balance(b, i):
            return b.flow_mol*b.mole_frac_comp[i] == sum(
                b.flow_mol_phase[p]*b.mole_frac_phase_comp[p, i]
                for p in b.params.phase_list
                if (p, i) in b.params._phase_component_set)
        b.component_flow_balances = Constraint(b.params.component_list,
                                               rule=rule_comp_mass_balance)

        def rule_mole_frac(b, p):
            return 1e3*sum(b.mole_frac_phase_comp[p, i]
                           for i in b.params.component_list
                           if (p, i) in b.params._phase_component_set) == 1e3
        b.sum_mole_frac = Constraint(b.params.phase_list,
                                     rule=rule_mole_frac)

        def rule_phase_frac(b, p):
            return b.phase_frac[p]*b.flow_mol == b.flow_mol_phase[p]
        b.phase_fraction_constraint = Constraint(b.params.phase_list,
                                                 rule=rule_phase_frac)

    # -------------------------------------------------------------------------
    # General Methods
    def get_material_flow_terms_FTPx(p, j):
        """Create material flow terms for control volume."""
        if j in b.params.component_list:
            return b.flow_mol_phase[p] * b.mole_frac_phase_comp[p, j]
        else:
            return 0
    b.get_material_flow_terms = get_material_flow_terms_FTPx

    def get_enthalpy_flow_terms_FTPx(p):
        """Create enthalpy flow terms."""
        return b.flow_mol_phase[p] * b.enth_mol_phase[p]
    b.get_enthalpy_flow_terms = get_enthalpy_flow_terms_FTPx

    def get_material_density_terms_FTPx(p, j):
        """Create material density terms."""
        if j in b.params.component_list:
            return b.dens_mol_phase[p] * b.mole_frac_phase_comp[p, j]
        else:
            return 0
    b.get_material_density_terms = get_material_density_terms_FTPx

    def get_energy_density_terms_FTPx(p):
        """Create energy density terms."""
        return b.dens_mol_phase[p] * b.enth_mol_phase[p]
    b.get_energy_density_terms = get_energy_density_terms_FTPx

    def default_material_balance_type_FTPx():
        return MaterialBalanceType.componentTotal
    b.default_material_balance_type = default_material_balance_type_FTPx

    def default_energy_balance_type_FTPx():
        return EnergyBalanceType.enthalpyTotal
    b.default_energy_balance_type = default_energy_balance_type_FTPx

    def get_material_flow_basis_FTPx():
        return MaterialFlowBasis.molar
    b.get_material_flow_basis = get_material_flow_basis_FTPx

    def define_state_vars_FTPx():
        """Define state vars."""
        return {"flow_mol": b.flow_mol,
                "mole_frac_comp": b.mole_frac_comp,
                "temperature": b.temperature,
                "pressure": b.pressure}
    b.define_state_vars = define_state_vars_FTPx

    def define_display_vars_FTPx():
        """Define display vars."""
        return {"Total Molar Flowrate": b.flow_mol,
                "Total Mole Fraction": b.mole_frac_comp,
                "Temperature": b.temperature,
                "Pressure": b.pressure}
    b.define_display_vars = define_display_vars_FTPx
예제 #21
0
 def test_simple_sat_model(self):
     m = ConcreteModel()
     m.x = Var()
     m.c = Constraint(expr=1 == m.x)
     m.o = Objective(expr=m.x)
     self.assertTrue(satisfiable(m))
예제 #22
0
# *NEW* vehicle storage capacity factor
#m.vehicle_cf = m.total_start_capac / m.total_max_capacity


#####################
# Constraints
# generated power + curtailed power serves load
def ServeLoadConstraint_rule(m, t):
    return (
        sum(m.DispatchGen[g, t] for g in m.GENERATORS) + m.DispatchCurtail[t]
        ==
        (m.nominal_load[t] + m.DispatchLoad[t] + m.ChargeCurtail[t])
    )
m.ServeLoadConstraint = Constraint(
    m.TIMEPOINTS, rule=ServeLoadConstraint_rule
)

# dispatched generated power must be less than what exists
def MaxOutputConstraint_rule(m, g, t):
    return (
        m.DispatchGen[g, t] <= m.BuildGen[g] * m.max_cf[g, t]
    )
m.MaxOutputConstraint = Constraint(
    m.GENERATORS, m.TIMEPOINTS, rule=MaxOutputConstraint_rule
)

# emitted CO2 must be less than what's allowed
def LimitCO2_rule(m):
    return (m.co2_total_tons <= m.co2_baseline_tons * m.co2_limit_vs_baseline)
m.LimitCO2 = Constraint(rule=LimitCO2_rule)
예제 #23
0
 def test_lower_bound_unsat(self):
     m = ConcreteModel()
     m.x = Var(bounds=(0, 5))
     m.c = Constraint(expr=-0.01 == m.x)
     m.o = Objective(expr=m.x)
     self.assertFalse(satisfiable(m))
예제 #24
0
    def build(self):
        """Build the model.

        Args:
            None
        Returns:
            None
        """
        # Setup model build logger
        model_log = idaeslog.getModelLogger(self.name, tag="unit")

        # Call UnitModel.build to setup dynamics
        super(ReboilerData, self).build()

        # Add Control Volume for the Reboiler
        self.control_volume = ControlVolume0DBlock(
            default={
                "dynamic": self.config.dynamic,
                "has_holdup": self.config.has_holdup,
                "property_package": self.config.property_package,
                "property_package_args": self.config.property_package_args
            })

        self.control_volume.add_state_blocks(has_phase_equilibrium=True)

        self.control_volume.add_material_balances(
            balance_type=self.config.material_balance_type,
            has_phase_equilibrium=True)

        self.control_volume.add_energy_balances(
            balance_type=self.config.energy_balance_type,
            has_heat_transfer=True)

        self.control_volume.add_momentum_balances(
            balance_type=self.config.momentum_balance_type,
            has_pressure_change=self.config.has_pressure_change)

        # Get liquid and vapor phase objects from the property package
        # to be used below. Avoids repition.
        _liquid_list = []
        _vapor_list = []
        for p in self.config.property_package.phase_list:
            pobj = self.config.property_package.get_phase(p)
            if pobj.is_vapor_phase():
                _vapor_list.append(p)
            elif pobj.is_liquid_phase():
                _liquid_list.append(p)
            else:
                _liquid_list.append(p)
                model_log.warning(
                    "A non-liquid/non-vapor phase was detected but will "
                    "be treated as a liquid.")

        # Create a pyomo set for indexing purposes. This set is appended to
        # model otherwise results in an abstract set.
        self._liquid_set = Set(initialize=_liquid_list)
        self._vapor_set = Set(initialize=_vapor_list)

        if self.config.has_boilup_ratio is True:

            self.boilup_ratio = Var(initialize=0.5,
                                    doc="Boilup ratio for reboiler")

            def rule_boilup_ratio(self, t):
                if hasattr(self.control_volume.properties_out[t],
                           "flow_mol_phase"):
                    return self.boilup_ratio * \
                        sum(self.control_volume.properties_out[t].
                            flow_mol_phase[p] for p in self._liquid_set) == \
                        sum(self.control_volume.
                            properties_out[t].flow_mol_phase["Vap"]
                            for p in self._vapor_set)
                elif hasattr(self.control_volume.properties_out[t],
                             "flow_mol_phase_comp"):
                    return self.boilup_ratio * \
                        sum(self.control_volume.properties_out[t].
                            flow_mol_phase_comp[p, i]
                            for p in self._liquid_set
                            for i in self.control_volume.properties_out[t].
                            params.component_list) == \
                        sum(self.control_volume.properties_out[t].
                            flow_mol_phase_comp[p, i]
                            for p in self._vapor_set
                            for i in self.control_volume.properties_out[t].
                            params.component_list)
                else:
                    raise PropertyNotSupportedError(
                        "Unrecognized names for flow variables encountered "
                        "while building the constraint for reboiler.")

            self.eq_boilup_ratio = Constraint(self.flowsheet().time,
                                              rule=rule_boilup_ratio)

        self._make_ports()

        self._make_splits_reboiler()

        # Add object reference to variables of the control volume
        # Reference to the heat duty
        self.heat_duty = Reference(self.control_volume.heat[:])
        # Reference to the pressure drop (if set to True)
        if self.config.has_pressure_change:
            self.deltaP = Reference(self.control_volume.deltaP[:])
예제 #25
0
    def test_separable_diffeq_case6(self):

        m = self.m
        m.w = Var(m.t, m.s)
        m.dw = DerivativeVar(m.w)
        m.p = Param(initialize=5)
        m.mp = Param(initialize=5, mutable=True)
        m.y = Var()

        t = IndexTemplate(m.t)

        def _deqv(m, i):
            return m.v[i]**2 + m.v[i] == m.dv[i] + m.y

        m.deqv = Constraint(m.t, rule=_deqv)

        def _deqw(m, i, j):
            return m.w[i, j]**2 + m.w[i, j] == m.y + m.dw[i, j]

        m.deqw = Constraint(m.t, m.s, rule=_deqw)

        mysim = Simulator(m)

        self.assertEqual(len(mysim._diffvars), 4)
        self.assertEqual(mysim._diffvars[0], _GetItemIndexer(m.v[t]))
        self.assertEqual(mysim._diffvars[1], _GetItemIndexer(m.w[t, 1]))
        self.assertEqual(mysim._diffvars[2], _GetItemIndexer(m.w[t, 2]))
        self.assertEqual(len(mysim._derivlist), 4)
        self.assertEqual(mysim._derivlist[0], _GetItemIndexer(m.dv[t]))
        self.assertEqual(mysim._derivlist[1], _GetItemIndexer(m.dw[t, 1]))
        self.assertEqual(mysim._derivlist[2], _GetItemIndexer(m.dw[t, 2]))
        self.assertEqual(len(mysim._rhsdict), 4)
        m.del_component('deqv')
        m.del_component('deqw')
        m.del_component('deqv_index')
        m.del_component('deqw_index')

        def _deqv(m, i):
            return m.v[i]**2 + m.v[i] == m.mp + m.dv[i]

        m.deqv = Constraint(m.t, rule=_deqv)

        def _deqw(m, i, j):
            return m.w[i, j]**2 + m.w[i, j] == m.dw[i, j] + m.p

        m.deqw = Constraint(m.t, m.s, rule=_deqw)

        mysim = Simulator(m)

        self.assertEqual(len(mysim._diffvars), 4)
        self.assertEqual(mysim._diffvars[0], _GetItemIndexer(m.v[t]))
        self.assertEqual(mysim._diffvars[1], _GetItemIndexer(m.w[t, 1]))
        self.assertEqual(mysim._diffvars[2], _GetItemIndexer(m.w[t, 2]))
        self.assertEqual(len(mysim._derivlist), 4)
        self.assertEqual(mysim._derivlist[0], _GetItemIndexer(m.dv[t]))
        self.assertEqual(mysim._derivlist[1], _GetItemIndexer(m.dw[t, 1]))
        self.assertEqual(mysim._derivlist[2], _GetItemIndexer(m.dw[t, 2]))
        self.assertEqual(len(mysim._rhsdict), 4)
        m.del_component('deqv')
        m.del_component('deqw')
        m.del_component('deqv_index')
        m.del_component('deqw_index')
        m.del_component('w')
        m.del_component('dw')
        m.del_component('p')
        m.del_component('mp')
        m.del_component('y')
예제 #26
0
파일: OptiTope.py 프로젝트: lkuchenb/fred
    def __init__(self, results,  threshold=None, k=10, solver="glpk", verbosity=0):
        """
        :param result: Epitope prediction result object from which the epitope selection should be performed
        :type result: :class:`~Fred2.Core.Result.EpitopePredictionResult`
        :param dict(str,float) threshold: A dictionary scoring the binding thresholds for each HLA
                                          :class:`~Fred2.Core.Allele.Allele` key = allele name; value = the threshold
        :param int k: The number of epitopes to select
        :param str solver: The solver to be used (default glpk)
        :param int verbosity: Integer defining whether additional debugg prints are made >0 => debug mode
        """

        #check input data
        if not isinstance(results, EpitopePredictionResult):
            raise ValueError("first input parameter is not of type EpitopePredictionResult")

        _alleles = copy.deepcopy(results.columns.values.tolist())

        #test if allele prob is set, if not set allele prob uniform
        #if only partly set infer missing values (assuming uniformity of missing value)
        prob = []
        no_prob = []
        for a in _alleles:
            if a.prob is None:
                no_prob.append(a)
            else:
                prob.append(a)

        if len(no_prob) > 0:
            #group by locus
            no_prob_grouped = {}
            prob_grouped = {}
            for a in no_prob:
                no_prob_grouped.setdefault(a.locus, []).append(a)
            for a in prob:
                prob_grouped.setdefault(a.locus, []).append(a)

            for g, v in no_prob_grouped.iteritems():
                total_loc_a = len(v)
                if g in prob_grouped:
                    remaining_mass = 1.0 - sum(a.prob for a in prob_grouped[g])
                    for a in v:
                        a.prob = remaining_mass/total_loc_a
                else:
                    for a in v:
                        a.prob = 1.0/total_loc_a
        probs = {a.name:a.prob for a in _alleles}
        if verbosity:
            for a in _alleles:
                print a.name, a.prob

        #start constructing model
        self.__solver = SolverFactory(solver)
        self.__verbosity = verbosity
        self.__changed = True
        self.__alleleProb = _alleles
        self.__k = k
        self.__result = None
        self.__thresh = {} if threshold is None else threshold

        # Variable, Set and Parameter preparation
        alleles_I = {}
        variations = []
        epi_var = {}
        imm = {}
        peps = {}
        cons = {}

        #unstack multiindex df to get normal df based on first prediction method
        #and filter for binding epitopes
        method = results.index.values[0][1]
        res_df = results.xs(results.index.values[0][1], level="Method")
        res_df = res_df[res_df.apply(lambda x: any(x[a] > self.__thresh.get(a.name, -float("inf"))
                                                   for a in res_df.columns), axis=1)]

        for tup in res_df.itertuples():
            p = tup[0]
            seq = str(p)
            peps[seq] = p
            for a, s in itr.izip(res_df.columns, tup[1:]):
                if method in ["smm", "smmpmbec", "arb", "comblibsidney"]:
                    try:
                        thr = min(1., max(0.0, 1.0 - math.log(self.__thresh.get(a.name),
                                                      50000))) if a.name in self.__thresh else -float("inf")
                    except:
                        thr = 0

                    if s >= thr:
                        alleles_I.setdefault(a.name, set()).add(seq)
                    imm[seq, a.name] = min(1., max(0.0, 1.0 - math.log(s, 50000)))
                else:
                    if s > self.__thresh.get(a.name, -float("inf")):
                        alleles_I.setdefault(a.name, set()).add(seq)
                    imm[seq, a.name] = s

            prots = set(pr for pr in p.get_all_proteins())
            cons[seq] = len(prots)
            for prot in prots:
                variations.append(prot.gene_id)
                epi_var.setdefault(prot.gene_id, set()).add(seq)
        self.__peptideSet = peps

        #calculate conservation
        variations = set(variations)
        total = len(variations)
        for e, v in cons.iteritems():
            try:
                cons[e] = v / total
            except ZeroDivisionError:
                cons[e] = 1
        model = ConcreteModel()

        #set definition
        model.Q = Set(initialize=variations)

        model.E = Set(initialize=set(peps.keys()))

        model.A = Set(initialize=alleles_I.keys())
        model.E_var = Set(model.Q, initialize=lambda mode, v: epi_var[v])
        model.A_I = Set(model.A, initialize=lambda model, a: alleles_I[a])


        #parameter definition
        model.k = Param(initialize=self.__k, within=PositiveIntegers, mutable=True)
        model.p = Param(model.A, initialize=lambda model, a: probs[a])

        model.c = Param(model.E, initialize=lambda model, e: cons[e],mutable=True)

        #threshold parameters
        model.i = Param(model.E, model.A, initialize=lambda model, e, a: imm[e, a])
        model.t_allele = Param(initialize=0, within=NonNegativeIntegers, mutable=True)
        model.t_var = Param(initialize=0, within=NonNegativeIntegers, mutable=True)
        model.t_c = Param(initialize=0.0, within=NonNegativeReals, mutable=True)

        # Variable Definition
        model.x = Var(model.E, within=Binary)
        model.y = Var(model.A, within=Binary)
        model.z = Var(model.Q, within=Binary)

        # Objective definition
        model.Obj = Objective(
            rule=lambda model: sum(model.x[e] * sum(model.p[a] * model.i[e, a] for a in model.A) for e in model.E),
            sense=maximize)


        #Obligatory Constraint (number of selected epitopes)
        model.NofSelectedEpitopesCov = Constraint(rule=lambda model: sum(model.x[e] for e in model.E) <= model.k)

        #optional constraints (in basic model they are disabled)
        model.IsAlleleCovConst = Constraint(model.A,
                                            rule=lambda model, a: sum(model.x[e] for e in model.A_I[a]) >= model.y[a])
        model.MinAlleleCovConst = Constraint(rule=lambda model: sum(model.y[a] for a in model.A) >= model.t_allele)

        model.IsAntigenCovConst = Constraint(model.Q,
                                             rule=lambda model, q: sum(model.x[e] for e in model.E_var[q]) >= model.z[q])
        model.MinAntigenCovConst = Constraint(rule=lambda model: sum(model.z[q] for q in model.Q) >= model.t_var)
        model.EpitopeConsConst = Constraint(model.E,
                                            rule=lambda model, e: (1 - model.c[e]) * model.x[e] <= 1 - model.t_c)

        #generate instance
        self.instance = model
        if self.__verbosity > 0:
            print "MODEL INSTANCE"
            self.instance.pprint()

        #constraints
        self.instance.IsAlleleCovConst.deactivate()
        self.instance.MinAlleleCovConst.deactivate()
        self.instance.IsAntigenCovConst.deactivate()
        self.instance.MinAntigenCovConst.deactivate()
        self.instance.EpitopeConsConst.deactivate()
예제 #27
0
    def test_sim_initialization_multi_index2(self):

        m = self.m
        m.s2 = Set(initialize=[(1, 1), (2, 2)])
        m.w1 = Var(m.t, m.s2)
        m.dw1 = DerivativeVar(m.w1)

        m.w2 = Var(m.s2, m.t)
        m.dw2 = DerivativeVar(m.w2)

        m.w3 = Var([0, 1], m.t, m.s2)
        m.dw3 = DerivativeVar(m.w3)

        t = IndexTemplate(m.t)

        def _deq1(m, t, i, j):
            return m.dw1[t, i, j] == m.w1[t, i, j]

        m.deq1 = Constraint(m.t, m.s2, rule=_deq1)

        def _deq2(m, *idx):
            return m.dw2[idx] == m.w2[idx]

        m.deq2 = Constraint(m.s2, m.t, rule=_deq2)

        def _deq3(m, i, t, j, k):
            return m.dw3[i, t, j, k] == m.w1[t, j, k] + m.w2[j, k, t]

        m.deq3 = Constraint([0, 1], m.t, m.s2, rule=_deq3)

        mysim = Simulator(m)

        self.assertIs(mysim._contset, m.t)
        self.assertEqual(len(mysim._diffvars), 8)
        self.assertTrue(_GetItemIndexer(m.w1[t, 1, 1]) in mysim._diffvars)
        self.assertTrue(_GetItemIndexer(m.w1[t, 2, 2]) in mysim._diffvars)
        self.assertTrue(_GetItemIndexer(m.w2[1, 1, t]) in mysim._diffvars)
        self.assertTrue(_GetItemIndexer(m.w2[2, 2, t]) in mysim._diffvars)
        self.assertTrue(_GetItemIndexer(m.w3[0, t, 1, 1]) in mysim._diffvars)
        self.assertTrue(_GetItemIndexer(m.w3[1, t, 2, 2]) in mysim._diffvars)

        self.assertEqual(len(mysim._derivlist), 8)
        self.assertTrue(_GetItemIndexer(m.dw1[t, 1, 1]) in mysim._derivlist)
        self.assertTrue(_GetItemIndexer(m.dw1[t, 2, 2]) in mysim._derivlist)
        self.assertTrue(_GetItemIndexer(m.dw2[1, 1, t]) in mysim._derivlist)
        self.assertTrue(_GetItemIndexer(m.dw2[2, 2, t]) in mysim._derivlist)
        self.assertTrue(_GetItemIndexer(m.dw3[0, t, 1, 1]) in mysim._derivlist)
        self.assertTrue(_GetItemIndexer(m.dw3[1, t, 2, 2]) in mysim._derivlist)

        self.assertEqual(len(mysim._templatemap), 4)
        self.assertTrue(_GetItemIndexer(m.w1[t, 1, 1]) in mysim._templatemap)
        self.assertTrue(_GetItemIndexer(m.w1[t, 2, 2]) in mysim._templatemap)
        self.assertTrue(_GetItemIndexer(m.w2[1, 1, t]) in mysim._templatemap)
        self.assertTrue(_GetItemIndexer(m.w2[2, 2, t]) in mysim._templatemap)
        self.assertFalse(
            _GetItemIndexer(m.w3[0, t, 1, 1]) in mysim._templatemap)
        self.assertFalse(
            _GetItemIndexer(m.w3[1, t, 2, 2]) in mysim._templatemap)

        self.assertEqual(len(mysim._rhsdict), 8)
        self.assertTrue(
            isinstance(mysim._rhsdict[_GetItemIndexer(m.dw1[t, 1, 1])], Param))
        self.assertTrue(
            isinstance(mysim._rhsdict[_GetItemIndexer(m.dw1[t, 2, 2])], Param))
        self.assertTrue(
            isinstance(mysim._rhsdict[_GetItemIndexer(m.dw2[1, 1, t])], Param))
        self.assertTrue(
            isinstance(mysim._rhsdict[_GetItemIndexer(m.dw2[2, 2, t])], Param))
        self.assertTrue(
            isinstance(mysim._rhsdict[_GetItemIndexer(m.dw3[0, t, 1, 1])],
                       EXPR.SumExpression))
        self.assertTrue(
            isinstance(mysim._rhsdict[_GetItemIndexer(m.dw3[1, t, 2, 2])],
                       EXPR.SumExpression))
        self.assertEqual(mysim._rhsdict[_GetItemIndexer(m.dw1[t, 1, 1])].name,
                         "'w1[{t},1,1]'")
        self.assertEqual(mysim._rhsdict[_GetItemIndexer(m.dw1[t, 2, 2])].name,
                         "'w1[{t},2,2]'")
        self.assertEqual(mysim._rhsdict[_GetItemIndexer(m.dw2[1, 1, t])].name,
                         "'w2[1,1,{t}]'")
        self.assertEqual(mysim._rhsdict[_GetItemIndexer(m.dw2[2, 2, t])].name,
                         "'w2[2,2,{t}]'")

        self.assertEqual(len(mysim._rhsfun(0, [0] * 8)), 8)
        self.assertIsNone(mysim._tsim)
        self.assertIsNone(mysim._simsolution)

        m.del_component('deq1')
        m.del_component('deq1_index')
        m.del_component('deq2')
        m.del_component('deq2_index')
        m.del_component('deq3')
        m.del_component('deq3_index')
예제 #28
0
    def build(self):
        """
        Begin building model (pre-DAE transformation).

        Args:
            None

        Returns:
            None
        """
        # Call UnitModel.build to setup dynamics
        super(FlashData, self).build()

        # Build Control Volume
        self.control_volume = ControlVolume0DBlock(
            default={
                "dynamic": self.config.dynamic,
                "has_holdup": self.config.has_holdup,
                "property_package": self.config.property_package,
                "property_package_args": self.config.property_package_args
            })

        self.control_volume.add_state_blocks(has_phase_equilibrium=True)

        self.control_volume.add_material_balances(
            balance_type=self.config.material_balance_type,
            has_phase_equilibrium=True)

        self.control_volume.add_energy_balances(
            balance_type=self.config.energy_balance_type,
            has_heat_transfer=self.config.has_heat_transfer)

        self.control_volume.add_momentum_balances(
            balance_type=self.config.momentum_balance_type,
            has_pressure_change=self.config.has_pressure_change)

        # Add Ports
        self.add_inlet_port()

        split_map = {}
        for p in self.control_volume.properties_in.phase_list:
            p_obj = self.config.property_package.get_phase(p)
            if p_obj.is_vapor_phase():
                # Vapor leaves through Vap outlet
                split_map[p] = "Vap"
            else:
                # All other phases leave through Liq outlet
                split_map[p] = "Liq"

        self.split = Separator(
            default={
                "property_package": self.config.property_package,
                "property_package_args": self.config.property_package_args,
                "outlet_list": ["Vap", "Liq"],
                "split_basis": SplittingType.phaseFlow,
                "ideal_separation": self.config.ideal_separation,
                "ideal_split_map": split_map,
                "mixed_state_block": self.control_volume.properties_out,
                "has_phase_equilibrium": not self.config.ideal_separation,
                "energy_split_basis": self.config.energy_split_basis
            })
        if not self.config.ideal_separation:

            def split_frac_rule(b, t, o):
                return b.split.split_fraction[t, o, o] == 1

            self.split_fraction_eq = Constraint(self.flowsheet().config.time,
                                                self.split.outlet_idx,
                                                rule=split_frac_rule)

        self.vap_outlet = Port(extends=self.split.Vap)
        self.liq_outlet = Port(extends=self.split.Liq)

        # Add references
        if (self.config.has_heat_transfer is True
                and self.config.energy_balance_type != EnergyBalanceType.none):
            self.heat_duty = Reference(self.control_volume.heat[:])
        if (self.config.has_pressure_change is True and
                self.config.momentum_balance_type != MomentumBalanceType.none):
            self.deltaP = Reference(self.control_volume.deltaP[:])
예제 #29
0
def main():
    # Create a Concrete Model as the top level object
    m = ConcreteModel()

    # Add a flowsheet object to the model
    m.fs = FlowsheetBlock(default={"dynamic": False})

    # Add property packages to flowsheet library
    m.fs.thermo_params = thermo_props.HDAParameterBlock()
    m.fs.reaction_params = reaction_props.HDAReactionParameterBlock(
        default={"property_package": m.fs.thermo_params})

    # Create unit models
    m.fs.M101 = Mixer(
        default={
            "property_package": m.fs.thermo_params,
            "inlet_list": ["toluene_feed", "hydrogen_feed", "vapor_recycle"]
        })

    m.fs.H101 = Heater(
        default={
            "property_package": m.fs.thermo_params,
            "has_pressure_change": False,
            "has_phase_equilibrium": True
        })

    m.fs.R101 = StoichiometricReactor(
        default={
            "property_package": m.fs.thermo_params,
            "reaction_package": m.fs.reaction_params,
            "has_heat_of_reaction": True,
            "has_heat_transfer": True,
            "has_pressure_change": False
        })

    m.fs.F101 = Flash(
        default={
            "property_package": m.fs.thermo_params,
            "has_heat_transfer": True,
            "has_pressure_change": True
        })

    m.fs.S101 = Splitter(
        default={
            "property_package": m.fs.thermo_params,
            "ideal_separation": False,
            "outlet_list": ["purge", "recycle"]
        })

    # This is needed to avoid pressure degeneracy in recylce loop
    m.fs.C101 = PressureChanger(
        default={
            "property_package": m.fs.thermo_params,
            "compressor": True,
            "thermodynamic_assumption": ThermodynamicAssumption.isothermal
        })

    m.fs.F102 = Flash(
        default={
            "property_package": m.fs.thermo_params,
            "has_heat_transfer": True,
            "has_pressure_change": True
        })

    m.fs.H101.control_volume.scaling_factor_energy = 1e-3
    m.fs.R101.control_volume.scaling_factor_energy = 1e-3
    m.fs.F101.control_volume.scaling_factor_energy = 1e-3
    m.fs.C101.control_volume.scaling_factor_energy = 1e-3
    m.fs.F102.control_volume.scaling_factor_energy = 1e-3

    # Connect units
    m.fs.s03 = Arc(source=m.fs.M101.outlet, destination=m.fs.H101.inlet)
    m.fs.s04 = Arc(source=m.fs.H101.outlet, destination=m.fs.R101.inlet)
    m.fs.s05 = Arc(source=m.fs.R101.outlet, destination=m.fs.F101.inlet)
    m.fs.s06 = Arc(source=m.fs.F101.vap_outlet, destination=m.fs.S101.inlet)
    m.fs.s08 = Arc(source=m.fs.S101.recycle, destination=m.fs.C101.inlet)
    m.fs.s09 = Arc(source=m.fs.C101.outlet,
                   destination=m.fs.M101.vapor_recycle)
    m.fs.s10 = Arc(source=m.fs.F101.liq_outlet, destination=m.fs.F102.inlet)

    TransformationFactory("network.expand_arcs").apply_to(m)

    # Set operating conditions
    m.fs.M101.toluene_feed.flow_mol_phase_comp[0, "Vap", "benzene"].fix(1e-5)
    m.fs.M101.toluene_feed.flow_mol_phase_comp[0, "Vap", "toluene"].fix(1e-5)
    m.fs.M101.toluene_feed.flow_mol_phase_comp[0, "Vap", "hydrogen"].fix(1e-5)
    m.fs.M101.toluene_feed.flow_mol_phase_comp[0, "Vap", "methane"].fix(1e-5)
    m.fs.M101.toluene_feed.flow_mol_phase_comp[0, "Liq", "benzene"].fix(1e-5)
    m.fs.M101.toluene_feed.flow_mol_phase_comp[0, "Liq", "toluene"].fix(0.30)
    m.fs.M101.toluene_feed.flow_mol_phase_comp[0, "Liq", "hydrogen"].fix(1e-5)
    m.fs.M101.toluene_feed.flow_mol_phase_comp[0, "Liq", "methane"].fix(1e-5)
    m.fs.M101.toluene_feed.temperature.fix(303.2)
    m.fs.M101.toluene_feed.pressure.fix(350000)

    m.fs.M101.hydrogen_feed.flow_mol_phase_comp[0, "Vap", "benzene"].fix(1e-5)
    m.fs.M101.hydrogen_feed.flow_mol_phase_comp[0, "Vap", "toluene"].fix(1e-5)
    m.fs.M101.hydrogen_feed.flow_mol_phase_comp[0, "Vap", "hydrogen"].fix(0.30)
    m.fs.M101.hydrogen_feed.flow_mol_phase_comp[0, "Vap", "methane"].fix(0.02)
    m.fs.M101.hydrogen_feed.flow_mol_phase_comp[0, "Liq", "benzene"].fix(1e-5)
    m.fs.M101.hydrogen_feed.flow_mol_phase_comp[0, "Liq", "toluene"].fix(1e-5)
    m.fs.M101.hydrogen_feed.flow_mol_phase_comp[0, "Liq", "hydrogen"].fix(1e-5)
    m.fs.M101.hydrogen_feed.flow_mol_phase_comp[0, "Liq", "methane"].fix(1e-5)
    m.fs.M101.hydrogen_feed.temperature.fix(303.2)
    m.fs.M101.hydrogen_feed.pressure.fix(350000)

    m.fs.H101.outlet.temperature.fix(600)

    m.fs.R101.conversion = Var(initialize=0.75, bounds=(0, 1))

    m.fs.R101.conv_constraint = Constraint(
        expr=m.fs.R101.conversion *
        m.fs.R101.inlet.flow_mol_phase_comp[0, "Vap", "toluene"] == (
            m.fs.R101.inlet.flow_mol_phase_comp[0, "Vap", "toluene"] -
            m.fs.R101.outlet.flow_mol_phase_comp[0, "Vap", "toluene"]))

    m.fs.R101.conversion.fix(0.75)
    m.fs.R101.heat_duty.fix(0)

    m.fs.F101.vap_outlet.temperature.fix(325.0)
    m.fs.F101.deltaP.fix(0)

    m.fs.S101.split_fraction[0, "purge"].fix(0.2)

    m.fs.C101.outlet.pressure.fix(350000)

    m.fs.F102.vap_outlet.temperature.fix(375)
    m.fs.F102.deltaP.fix(-200000)

    # Define expressions
    # Product purity
    m.fs.purity = Expression(
        expr=m.fs.F102.vap_outlet.flow_mol_phase_comp[0, "Vap", "benzene"] /
        (m.fs.F102.vap_outlet.flow_mol_phase_comp[0, "Vap", "benzene"] +
         m.fs.F102.vap_outlet.flow_mol_phase_comp[0, "Vap", "toluene"]))

    # Operating cost ($/yr)
    m.fs.cooling_cost = Expression(expr=0.212e-7 * -m.fs.F101.heat_duty[0] +
                                   0.212e-7 * -m.fs.R101.heat_duty[0])
    m.fs.heating_cost = Expression(expr=2.2e-7 * m.fs.H101.heat_duty[0] +
                                   1.9e-7 * m.fs.F102.heat_duty[0])
    m.fs.operating_cost = Expression(
        expr=(3600 * 24 * 365 * (m.fs.heating_cost + m.fs.cooling_cost)))
    print(degrees_of_freedom(m))

    # Initialize Units
    # Define method for initialising each block
    def function(unit):
        unit.initialize(outlvl=1)

    # Create instance of sequential decomposition tool
    seq = SequentialDecomposition()
    seq.options.select_tear_method = "heuristic"
    seq.options.tear_method = "Wegstein"
    seq.options.iterLim = 5

    # Determine tear stream and calculation order
    G = seq.create_graph(m)
    heu_result = seq.tear_set_arcs(G, method="heuristic")
    order = seq.calculation_order(G)

    # Display tear stream and calculation order
    for o in heu_result:
        print(o.name)
    for o in order:
        for oo in o:
            print(oo.name)

    # Set guesses for tear stream
    tear_guesses = {
        "flow_mol_phase_comp": {
            (0, "Vap", "benzene"): 1e-5,
            (0, "Vap", "toluene"): 1e-5,
            (0, "Vap", "hydrogen"): 0.30,
            (0, "Vap", "methane"): 0.02,
            (0, "Liq", "benzene"): 1e-5,
            (0, "Liq", "toluene"): 0.30,
            (0, "Liq", "hydrogen"): 1e-5,
            (0, "Liq", "methane"): 1e-5
        },
        "temperature": {
            0: 303
        },
        "pressure": {
            0: 350000
        }
    }
    seq.set_guesses_for(m.fs.H101.inlet, tear_guesses)

    # Run sequential initialization
    seq.run(m, function)

    # # Create a solver
    solver = SolverFactory('ipopt')
    solver.options = {'tol': 1e-6}
    solver.options = {'tol': 1e-6, 'max_iter': 5000}
    results = solver.solve(m, tee=True)

    # Print results
    print("M101 Outlet")
    m.fs.M101.outlet.display()

    print("H101 Outlet")
    m.fs.H101.outlet.display()

    print("R101 Outlet")
    m.fs.R101.outlet.display()

    print("F101")
    m.fs.F101.liq_outlet.display()
    m.fs.F101.vap_outlet.display()

    print("F102")
    m.fs.F102.liq_outlet.display()
    m.fs.F102.vap_outlet.display()

    print("Purge")
    m.fs.S101.purge.display()

    print("Purity:", value(m.fs.purity))

    # Optimize process
    m.fs.objective = Objective(sense=minimize, expr=m.fs.operating_cost)

    # Decision variables
    m.fs.H101.outlet.temperature.unfix()
    m.fs.R101.heat_duty.unfix()
    m.fs.F101.vap_outlet.temperature.unfix()
    m.fs.F102.vap_outlet.temperature.unfix()
    m.fs.F102.deltaP.unfix()

    # Variable bounds
    m.fs.H101.outlet.temperature[0].setlb(500)
    m.fs.H101.outlet.temperature[0].setub(600)
    m.fs.R101.outlet.temperature[0].setlb(600)
    m.fs.R101.outlet.temperature[0].setub(800)
    m.fs.F101.vap_outlet.temperature[0].setlb(298.0)
    m.fs.F101.vap_outlet.temperature[0].setub(450.0)
    m.fs.F102.vap_outlet.temperature[0].setlb(298.0)
    m.fs.F102.vap_outlet.temperature[0].setub(450.0)
    m.fs.F102.vap_outlet.pressure[0].setlb(105000)
    m.fs.F102.vap_outlet.pressure[0].setub(110000)

    # Additional Constraints
    m.fs.overhead_loss = Constraint(
        expr=m.fs.F101.vap_outlet.flow_mol_phase_comp[0, "Vap",
                                                      "benzene"] <= 0.20 *
        m.fs.R101.outlet.flow_mol_phase_comp[0, "Vap", "benzene"])

    m.fs.product_flow = Constraint(
        expr=m.fs.F102.vap_outlet.flow_mol_phase_comp[0, "Vap",
                                                      "benzene"] >= 0.15)

    m.fs.product_purity = Constraint(expr=m.fs.purity >= 0.80)

    # Create a solver
    solver = SolverFactory('ipopt')
    solver.options = {'tol': 1e-6}
    solver.options = {'tol': 1e-6, 'max_iter': 5000}
    results = solver.solve(m, tee=True)

    # Print optimization results
    print()
    print("Optimal Solution")
    m.fs.operating_cost.display()
    m.fs.H101.heat_duty.display()
    m.fs.R101.heat_duty.display()
    m.fs.F101.heat_duty.display()
    m.fs.F102.heat_duty.display()

    # Print results
    print("M101 Outlet")
    m.fs.M101.outlet.display()

    print("H101 Outlet")
    m.fs.H101.outlet.display()

    print("R101 Outlet")
    m.fs.R101.outlet.display()

    print("F101")
    m.fs.F101.liq_outlet.display()
    m.fs.F101.vap_outlet.display()

    print("F102")
    m.fs.F102.liq_outlet.display()
    m.fs.F102.vap_outlet.display()

    print("Purge")
    m.fs.S101.purge.display()

    print("Recycle")
    m.fs.S101.recycle.display()

    print("Purity:", value(m.fs.purity))

    # For testing purposes
    return (m, results)
예제 #30
0
    def __init__(self, y, x, b=None, gy=[1], gx=[1], gb=None, fun='prod'):
        """
        Initialize the CNLSDDF model

        * y: Output variables
        * x: Input variables
        * b: Undesirable output variables
        * gy: Output directional vector
        * gx: Input directional vector
        * gb: Undesirable output directional vector
        * fun = "prod": Production frontier
              = "cost": Cost frontier
        """

        # TODO(error/warning handling): Check the configuration of the model exist
        self.y = y.tolist()
        self.x = x.tolist()
        self.b = b
        self.gy = self.__to_1d_list(gy)
        self.gx = self.__to_1d_list(gx)
        self.gb = self.__to_1d_list(gb)

        self.fun = fun

        if type(self.x[0]) != list:
            self.x = []
            for x_value in x.tolist():
                self.x.append([x_value])

        if type(self.y[0]) != list:
            self.y = []
            for y_value in y.tolist():
                self.y.append([y_value])

        self.__model__ = ConcreteModel()

        # Initialize the sets
        self.__model__.I = Set(initialize=range(len(self.y)))
        self.__model__.J = Set(initialize=range(len(self.x[0])))
        self.__model__.K = Set(initialize=range(len(self.y[0])))

        # Initialize the variables
        self.__model__.alpha = Var(self.__model__.I, doc='alpha')
        self.__model__.beta = Var(self.__model__.I,
                                  self.__model__.J,
                                  bounds=(0.0, None),
                                  doc='beta')
        self.__model__.epsilon = Var(self.__model__.I, doc='residuals')
        self.__model__.gamma = Var(self.__model__.I,
                                   self.__model__.K,
                                   bounds=(0.0, None),
                                   doc='gamma')

        if type(self.b) != type(None):
            self.b = b.tolist()
            self.gb = self.__to_1d_list(gb)

            if type(self.b[0]) != list:
                self.b = []
                for b_value in b.tolist():
                    self.b.append([b_value])

            self.__model__.L = Set(initialize=range(len(self.b[0])))
            self.__model__.delta = Var(self.__model__.I,
                                       self.__model__.L,
                                       bounds=(0.0, None),
                                       doc='delta')

        # Setup the objective function and constraints
        self.__model__.objective = Objective(rule=self._CNLS__objective_rule(),
                                             sense=minimize,
                                             doc='objective function')
        self.__model__.regression_rule = Constraint(
            self.__model__.I,
            rule=self.__regression_rule(),
            doc='regression equation')
        self.__model__.translation_rule = Constraint(
            self.__model__.I,
            rule=self.__translation_property(),
            doc='translation property')
        self.__model__.afriat_rule = Constraint(self.__model__.I,
                                                self.__model__.I,
                                                rule=self.__afriat_rule(),
                                                doc='afriat inequality')

        # Optimize model
        self.optimization_status = 0
        self.problem_status = 0