Exemplo n.º 1
0
def test_revert_state_vars_fixed_guesses(model):
    # Note that flow_mol_phase_comp is labled as compoennt_flow
    # in define_state_vars
    model.fs.sb.flow_mol_phase_comp["p1", "c1"].fix(10)
    model.fs.sb.pressure.fix(1.5e5)

    state_args = {
        "component_flow_phase": {
            ("p1", "c1"): 1,
            ("p1", "c2"): 2,
            ("p2", "c1"): 3,
            ("p2", "c2"): 4
        },
        "pressure": 2e5,
        "temperature": 500
    }

    flags = fix_state_vars(model.fs.sb, state_args)
    revert_state_vars(model.fs.sb, flags)

    # Pressure and componet_flow[p1, c1] should still be fixed
    assert model.fs.sb.flow_mol_phase_comp[("p1", "c1")].fixed
    assert model.fs.sb.flow_mol_phase_comp[("p1", "c1")].value == 10
    assert not model.fs.sb.flow_mol_phase_comp[("p1", "c2")].fixed
    assert model.fs.sb.flow_mol_phase_comp[("p1", "c2")].value == 2
    assert not model.fs.sb.flow_mol_phase_comp[("p2", "c1")].fixed
    assert model.fs.sb.flow_mol_phase_comp[("p2", "c1")].value == 3
    assert not model.fs.sb.flow_mol_phase_comp[("p2", "c2")].fixed
    assert model.fs.sb.flow_mol_phase_comp[("p2", "c2")].value == 4

    assert model.fs.sb.pressure.fixed
    assert model.fs.sb.pressure.value == 1.5e5
    assert not model.fs.sb.temperature.fixed
    assert model.fs.sb.temperature.value == 500
Exemplo n.º 2
0
def test_revert_state_vars_guesses(model):
    # Note that flow_mol_phase_comp is labled as compoennt_flow
    # in define_state_vars
    state_args = {
        "component_flow_phase": {
            ("p1", "c1"): 1,
            ("p1", "c2"): 2,
            ("p2", "c1"): 3,
            ("p2", "c2"): 4
        },
        "pressure": 2e5,
        "temperature": 500
    }

    flags = fix_state_vars(model.fs.sb, state_args)

    revert_state_vars(model.fs.sb, flags)

    assert not model.fs.sb.flow_mol_phase_comp[("p1", "c1")].fixed
    assert model.fs.sb.flow_mol_phase_comp[("p1", "c1")].value == 1
    assert not model.fs.sb.flow_mol_phase_comp[("p1", "c2")].fixed
    assert model.fs.sb.flow_mol_phase_comp[("p1", "c2")].value == 2
    assert not model.fs.sb.flow_mol_phase_comp[("p2", "c1")].fixed
    assert model.fs.sb.flow_mol_phase_comp[("p2", "c1")].value == 3
    assert not model.fs.sb.flow_mol_phase_comp[("p2", "c2")].fixed
    assert model.fs.sb.flow_mol_phase_comp[("p2", "c2")].value == 4

    assert not model.fs.sb.pressure.fixed
    assert model.fs.sb.pressure.value == 2e5
    assert not model.fs.sb.temperature.fixed
    assert model.fs.sb.temperature.value == 500
def calculate_chemical_scaling_factors(unit, thermo_params, rxn_params, state_args, output_jac=False):
    calculate_chemical_scaling_factors_for_equilibrium_log_reactions(unit, rxn_params)
    calculate_chemical_scaling_factors_for_energy_balances(unit)
    calculate_chemical_scaling_factors_for_material_balances(unit)

    flags = fix_state_vars(unit.control_volume.properties_out, state_args)
    revert_state_vars(unit.control_volume.properties_out, flags)
Exemplo n.º 4
0
    def release_state(blk, flags, outlvl=idaeslog.NOTSET):
        # Method to release states only if explicitly called

        if flags is None:
            return
        # Unfix state variables
        revert_state_vars(blk, flags)
        init_log.info('State Released.')
Exemplo n.º 5
0
def test_revert_state_vars_flag_mismatch(model):
    flags = {(None, 'component_flow_phase', ('p1', 'c1')): False,
             (None, 'component_flow_phase', ('p1', 'c2')): False,
             (None, 'component_flow_phase', ('p2', 'c1')): False,
             (None, 'pressure', None): False}

    with pytest.raises(ConfigurationError):
        revert_state_vars(model.fs.sb, flags)
Exemplo n.º 6
0
    def initialize(blk,
                   state_args_water_steam={},
                   outlvl=0,
                   solver='ipopt',
                   optarg={'tol': 1e-6}):
        '''
        Drum initialization routine.

        Keyword Arguments:
            state_args : a dict of arguments to be passed to the property
                           package(s) for the control_volume of the model to
                           provide an initial state for initialization
                           (see documentation of the specific property package)
                           (default = None).
            outlvl : sets output level of initialisation routine

                     * 0 = no output (default)
                     * 1 = return solver state for each step in routine
                     * 2 = return solver state for each step in subroutines
                     * 3 = include solver output infomation (tee=True)

            optarg : solver options dictionary object (default={'tol': 1e-6})
            solver : str indicating whcih solver to use during
                     initialization (default = 'ipopt')

        Returns:
            None
        '''
        init_log = idaeslog.getInitLogger(blk.name, outlvl, tag="unit")
        solve_log = idaeslog.getSolveLogger(blk.name, outlvl, tag="unit")

        opt = SolverFactory(solver)
        opt.options = optarg

        init_log.info_low("Starting initialization...")
        # fix FeedWater Inlet
        flags_fw = fix_state_vars(blk.mixed_state, state_args_water_steam)
        blk.mixed_state.initialize()
        # initialize outlet states
        for t in blk.flowsheet().config.time:
            blk.vap_state[t].flow_mol = value(blk.mixed_state[t].flow_mol *
                                              blk.mixed_state[t].vapor_frac)
            blk.vap_state[t].enth_mol = value(
                blk.mixed_state[t].enth_mol_phase["Vap"])
            blk.vap_state[t].pressure = value(blk.mixed_state[t].pressure)
            blk.vap_state[t].vapor_frac = 1
            blk.liq_state[t].flow_mol = value(
                blk.mixed_state[t].flow_mol *
                (1 - blk.mixed_state[t].vapor_frac))
            blk.liq_state[t].enth_mol = value(
                blk.mixed_state[t].enth_mol_phase["Liq"])
            blk.liq_state[t].pressure = value(blk.mixed_state[t].pressure)
            blk.liq_state[t].vapor_frac = 0
        # unfix variables
        revert_state_vars(blk.mixed_state, flags_fw)
        init_log.info_low("Initialization Complete.")
Exemplo n.º 7
0
def test_revert_state_vars_basic(model):
    flags = fix_state_vars(model.fs.sb)

    revert_state_vars(model.fs.sb, flags)

    for i in model.fs.sb.flow_mol_phase_comp:
        assert not model.fs.sb.flow_mol_phase_comp[i].fixed
        assert model.fs.sb.flow_mol_phase_comp[i].value == 2
    assert not model.fs.sb.pressure.fixed
    assert model.fs.sb.pressure.value == 1e5
    assert not model.fs.sb.temperature.fixed
    assert model.fs.sb.temperature.value == 300
Exemplo n.º 8
0
 def release_state(blk, flags, outlvl=idaeslog.NOTSET):
     '''
     Method to relase state variables fixed during initialization.
     Keyword Arguments:
         flags : dict containing information of which state variables
                 were fixed during initialization, and should now be
                 unfixed. This dict is returned by initialize if
                 hold_state=True.
         outlvl : sets output level of initialization routine
     '''
     revert_state_vars(blk, flags)
     init_log = idaeslog.getInitLogger(blk.name, outlvl, tag="properties")
     init_log.info_high("State released.")
Exemplo n.º 9
0
def initialize_system(m):
    prtrt = m.fs.pretreatment
    desal = m.fs.desalination
    psttrt = m.fs.posttreatment

    # initialize feed
    solve(m.fs.feed)

    # initialize pretreatment
    propagate_state(m.fs.s_feed)
    flags = fix_state_vars(prtrt.intake.properties)
    solve(prtrt)
    revert_state_vars(prtrt.intake.properties, flags)

    # initialize desalination
    propagate_state(m.fs.s_prtrt_tb)
    m.fs.tb_prtrt_desal.properties_out[0].flow_mass_phase_comp["Liq", "H2O"] = value(
        m.fs.tb_prtrt_desal.properties_in[0].flow_mass_comp["H2O"]
    )
    m.fs.tb_prtrt_desal.properties_out[0].flow_mass_phase_comp["Liq", "TDS"] = value(
        m.fs.tb_prtrt_desal.properties_in[0].flow_mass_comp["tds"]
    )

    desal.RO.feed_side.properties_in[0].flow_mass_phase_comp["Liq", "H2O"] = value(
        m.fs.feed.properties[0].flow_mass_comp["H2O"]
    )
    desal.RO.feed_side.properties_in[0].flow_mass_phase_comp["Liq", "TDS"] = value(
        m.fs.feed.properties[0].flow_mass_comp["tds"]
    )
    desal.RO.feed_side.properties_in[0].temperature = value(
        m.fs.tb_prtrt_desal.properties_out[0].temperature
    )
    desal.RO.feed_side.properties_in[0].pressure = value(
        desal.P1.control_volume.properties_out[0].pressure
    )
    desal.RO.initialize()

    propagate_state(m.fs.s_tb_desal)
    if m.erd_type == "pressure_exchanger":
        flags = fix_state_vars(desal.S1.mixed_state)
        solve(desal)
        revert_state_vars(desal.S1.mixed_state, flags)
    elif m.erd_type == "pump_as_turbine":
        flags = fix_state_vars(desal.P1.control_volume.properties_in)
        solve(desal)
        revert_state_vars(desal.P1.control_volume.properties_in, flags)

    # initialize posttreatment
    propagate_state(m.fs.s_desal_tb)
    m.fs.tb_desal_psttrt.properties_out[0].flow_mass_comp["H2O"] = value(
        m.fs.tb_desal_psttrt.properties_in[0].flow_mass_phase_comp["Liq", "H2O"]
    )
    m.fs.tb_desal_psttrt.properties_out[0].flow_mass_comp["tds"] = value(
        m.fs.tb_desal_psttrt.properties_in[0].flow_mass_phase_comp["Liq", "TDS"]
    )

    propagate_state(m.fs.s_tb_psttrt)
    flags = fix_state_vars(psttrt.storage_tank_2.properties)
    solve(psttrt)
    revert_state_vars(psttrt.storage_tank_2.properties, flags)
Exemplo n.º 10
0
    def release_state(self, flags, outlvl=idaeslog.NOTSET):
        """
        Method to release state variables fixed during initialisation.

        Keyword Arguments:
            flags : dict containing information of which state variables
                    were fixed during initialization, and should now be
                    unfixed. This dict is returned by initialize if
                    hold_state=True.
            outlvl : sets output level of of logging
        """
        # Unfix state variables
        init_log = idaeslog.getInitLogger(self.name, outlvl, tag="properties")
        revert_state_vars(self, flags)
        init_log.info_high("{} State Released.".format(self.name))
Exemplo n.º 11
0
    def initialize(blk,
                   state_args_water_steam=None,
                   outlvl=idaeslog.NOTSET,
                   solver=None,
                   optarg=None):
        '''
        Drum initialization routine.

        Keyword Arguments:
            state_args_water_steam : a dict of arguments to be passed to the
                           property package(s) for the control_volume of the
                           model to provide an initial state for initialization
                           (see documentation of the specific property package)
                           (default = None).
            outlvl : sets output level of initialisation routine
            optarg : solver options dictionary object (default=None, use
                     default solver options)
            solver : str indicating which solver to use during
                     initialization (default = None, use default solver)

        Returns:
            None
        '''
        init_log = idaeslog.getInitLogger(blk.name, outlvl, tag="unit")

        init_log.info_low("Starting initialization...")
        # fix FeedWater Inlet
        flags_fw = fix_state_vars(blk.mixed_state, state_args_water_steam)
        blk.mixed_state.initialize(solver=solver, optarg=optarg, outlvl=outlvl)
        # initialize outlet states
        for t in blk.flowsheet().time:
            blk.vap_state[t].flow_mol = value(blk.mixed_state[t].flow_mol *
                                              blk.mixed_state[t].vapor_frac)
            blk.vap_state[t].enth_mol = value(
                blk.mixed_state[t].enth_mol_phase["Vap"])
            blk.vap_state[t].pressure = value(blk.mixed_state[t].pressure)
            blk.vap_state[t].vapor_frac = 1
            blk.liq_state[t].flow_mol = value(
                blk.mixed_state[t].flow_mol *
                (1 - blk.mixed_state[t].vapor_frac))
            blk.liq_state[t].enth_mol = value(
                blk.mixed_state[t].enth_mol_phase["Liq"])
            blk.liq_state[t].pressure = value(blk.mixed_state[t].pressure)
            blk.liq_state[t].vapor_frac = 0
        # unfix variables
        revert_state_vars(blk.mixed_state, flags_fw)
        init_log.info_low("Initialization Complete.")
Exemplo n.º 12
0
    def release_state(blk, flags, outlvl=0):
        '''
        Method to relase state variables fixed during initialisation.

        Keyword Arguments:
            flags : dict containing information of which state variables
                    were fixed during initialization, and should now be
                    unfixed. This dict is returned by initialize if
                    hold_state=True.
            outlvl : sets output level of of logging
        '''
        # Unfix state variables
        revert_state_vars(blk, flags)

        if outlvl > 0:
            if outlvl > 0:
                _log.info('{} State Released.'.format(blk.name))
Exemplo n.º 13
0
    def release_state(blk, flags, outlvl=0):
        '''
        Method to relase state variables fixed during initialization.
        Keyword Arguments:
            flags : dict containing information of which state variables
                    were fixed during initialization, and should now be
                    unfixed. This dict is returned by initialize if
                    hold_state=True.
            outlvl : sets output level of of logging
        '''
        init_log = idaeslog.getInitLogger(blk.name, outlvl, tag="properties")
        if flags is None:
            init_log.debug("No flags passed to release_state().")
            return

        # Unfix state variables
        revert_state_vars(blk, flags)

        init_log.info_high("State Released.")
    def release_state(blk, flags, outlvl=idaeslog.NOTSET):
        '''
        Method to release state variables fixed during initialization.
        Keyword Arguments:
            flags : dict containing information of which state variables
                    were fixed during initialization, and should now be
                    unfixed. This dict is returned by initialize if
                    hold_state=True.
            outlvl : sets output level of of logging
        '''
        init_log = idaeslog.getInitLogger(blk.name, outlvl, tag="properties")

        # Reactivate sum of mole fractions constraint
        for k in blk.keys():
            if blk[k].config.defined_state is False:
                blk[k].mole_fraction_constraint.activate()

        if flags is not None:
            # Unfix state variables
            revert_state_vars(blk, flags)

        init_log.info_high("State Released.")
Exemplo n.º 15
0
def calculate_RO_area(unit=None, water_recovery=0.5, solver=None):
    """
    determine RO membrane area required to achieve the specified water recovery:
        unit:  the RO unit model, e.g. m.fs.RO, it should have its inlet feed state block
               initiated to the correct values (default=None)
        water_recovery: the mass-based fraction of inlet H2O that becomes permeate
                        (default=0.5)
        solver: solver object to be used (default=None)
    """
    # fix inlet conditions
    flags = fix_state_vars(unit.feed_side.properties_in)
    # fix unit water recovery
    unit.feed_side.properties_out[0].flow_mass_phase_comp['Liq', 'H2O'].fix(
        unit.feed_side.properties_in[0].flow_mass_phase_comp['Liq',
                                                             'H2O'].value *
        (1 - water_recovery))
    # solve for unit area
    check_dof(unit)
    solve(unit, solver=solver)
    # unfix variables
    revert_state_vars(unit.feed_side.properties_in, flags)
    unit.feed_side.properties_out[0].flow_mass_phase_comp['Liq', 'H2O'].unfix()
    return unit.area.value
Exemplo n.º 16
0
def test_revert_state_vars_fixed_no_guesses(model):
    # Note that flow_mol_phase_comp is labled as compoennt_flow
    # in define_state_vars
    model.fs.sb.flow_mol_phase_comp["p1", "c1"].fix(10)
    model.fs.sb.pressure.fix(1.5e5)

    flags = fix_state_vars(model.fs.sb)
    revert_state_vars(model.fs.sb, flags)

    # Pressure and componet_flow[p1, c1] should still be fixed
    assert model.fs.sb.flow_mol_phase_comp[("p1", "c1")].fixed
    assert model.fs.sb.flow_mol_phase_comp[("p1", "c1")].value == 10
    assert not model.fs.sb.flow_mol_phase_comp[("p1", "c2")].fixed
    assert model.fs.sb.flow_mol_phase_comp[("p1", "c2")].value == 2
    assert not model.fs.sb.flow_mol_phase_comp[("p2", "c1")].fixed
    assert model.fs.sb.flow_mol_phase_comp[("p2", "c1")].value == 2
    assert not model.fs.sb.flow_mol_phase_comp[("p2", "c2")].fixed
    assert model.fs.sb.flow_mol_phase_comp[("p2", "c2")].value == 2

    assert model.fs.sb.pressure.fixed
    assert model.fs.sb.pressure.value == 1.5e5
    assert not model.fs.sb.temperature.fixed
    assert model.fs.sb.temperature.value == 300
Exemplo n.º 17
0
    def release_state(blk, flags, outlvl=idaeslog.NOTSET):
        """
        Method to relase state variables fixed during initialization.
        Keyword Arguments:
            flags : dict containing information of which state variables
                    were fixed during initialization, and should now be
                    unfixed. This dict is returned by initialize if
                    hold_state=True.
            outlvl : sets output level of of logging
        """
        if flags is None:
            return

        # Unfix state variables
        revert_state_vars(blk, flags)

        # Activate state variable related constraints
        for k in blk.keys():
            if blk[k].config.defined_state is False:
                blk[k].sum_component_eqn.activate()

        init_log = idaeslog.getInitLogger(blk.name, outlvl, tag="properties")
        init_log.info_high('States released.')
Exemplo n.º 18
0
    def release_state(blk, flags, outlvl=idaeslog.NOTSET):
        '''
        Method to relase state variables fixed during initialization.

        Keyword Arguments:
            flags : dict containing information of which state variables
                    were fixed during initialization, and should now be
                    unfixed. This dict is returned by initialize if
                    hold_state=True.
            outlvl : sets output level of of logging
        '''
        init_log = idaeslog.getInitLogger(blk.name, outlvl, tag="properties")

        # Reactivate conc_water_eqn
        for k in blk.keys():
            if not blk[k].config.defined_state:
                blk[k].conc_water_eqn.activate()

        if flags is None:
            return
        # Unfix state variables
        revert_state_vars(blk, flags)
        init_log.info('State Released.')
Exemplo n.º 19
0
def run_case2(xA, xB, xAB=1e-25, scaling=True, rxn_config=None, state="FpcTP"):
    print("==========================================================================")
    print(
        "Case 2 (log form): A and B are aqueous, AB is solid that forms from reaction"
    )
    print("xA = " + str(xA))
    print("xB = " + str(xB))
    print("xAB = " + str(xAB))
    print("scaling = " + str(scaling))
    print("including water = " + str(True))
    print()
    model = ConcreteModel()
    model.fs = FlowsheetBlock(default={"dynamic": False})

    if state == "FpcTP":
        case1_thermo_config["state_definition"] = FpcTP
    elif state == "FTPx":
        case1_thermo_config["state_definition"] = FTPx
        case1_thermo_config["state_bounds"]["flow_mol"] = (0, 50, 100)
    else:
        print("Error! Undefined state...")
        assert False

    model.fs.thermo_params = GenericParameterBlock(default=case1_thermo_config)

    model.fs.rxn_params = GenericReactionParameterBlock(
        default={"property_package": model.fs.thermo_params, **rxn_config}
    )

    model.fs.unit = EquilibriumReactor(
        default={
            "property_package": model.fs.thermo_params,
            "reaction_package": model.fs.rxn_params,
            "has_rate_reactions": False,
            "has_equilibrium_reactions": True,
            "has_heat_transfer": False,
            "has_heat_of_reaction": False,
            "has_pressure_change": False,
            "energy_balance_type": EnergyBalanceType.none,
        }
    )

    total_flow_mol = 10

    # Set flow_mol_phase_comp
    if case1_thermo_config["state_definition"] == FpcTP:

        model.fs.unit.inlet.flow_mol_phase_comp[0, "Liq", "A"].fix(xA * total_flow_mol)
        model.fs.unit.inlet.flow_mol_phase_comp[0, "Liq", "B"].fix(xB * total_flow_mol)
        model.fs.unit.inlet.flow_mol_phase_comp[0, "Sol", "AB"].fix(
            xAB * total_flow_mol
        )
        model.fs.unit.inlet.flow_mol_phase_comp[0, "Liq", "H2O"].fix(
            (1 - xA - xB - xAB) * total_flow_mol
        )

    if case1_thermo_config["state_definition"] == FTPx:
        model.fs.unit.inlet.mole_frac_comp[0, "A"].fix(xA)
        model.fs.unit.inlet.mole_frac_comp[0, "B"].fix(xB)
        model.fs.unit.inlet.mole_frac_comp[0, "AB"].fix(xAB)
        model.fs.unit.inlet.mole_frac_comp[0, "H2O"].fix((1 - xA - xB - xAB))
        model.fs.unit.inlet.flow_mol.fix(total_flow_mol)

    model.fs.unit.inlet.pressure.fix(101325.0)
    model.fs.unit.inlet.temperature.fix(298.0)
    model.fs.unit.outlet.temperature.fix(298.0)

    assert degrees_of_freedom(model) == 0

    assert_units_consistent(model)

    # Scaling
    _set_eps_vals(model.fs.rxn_params, rxn_config)
    _set_equ_rxn_scaling(model.fs.unit, rxn_config)
    if case1_thermo_config["state_definition"] == FpcTP:
        _set_mat_bal_scaling_FpcTP(model.fs.unit)
    if case1_thermo_config["state_definition"] == FTPx:
        _set_mat_bal_scaling_FTPx(model.fs.unit)

    iscale.calculate_scaling_factors(model.fs.unit)
    assert isinstance(model.fs.unit.control_volume.scaling_factor, Suffix)

    # Initialize model

    if case1_thermo_config["state_definition"] == FpcTP:
        state_args = {
            "flow_mol_phase_comp": {
                ("Liq", "H2O"): model.fs.unit.inlet.flow_mol_phase_comp[
                    0, "Liq", "H2O"
                ].value,
                ("Liq", "A"): model.fs.unit.inlet.flow_mol_phase_comp[
                    0, "Liq", "A"
                ].value,
                ("Liq", "B"): model.fs.unit.inlet.flow_mol_phase_comp[
                    0, "Liq", "B"
                ].value,
                ("Sol", "AB"): model.fs.unit.inlet.flow_mol_phase_comp[
                    0, "Sol", "AB"
                ].value,
            },
            "pressure": 101325,
            "temperature": 298,
            "flow_mol": 10,
        }

    if case1_thermo_config["state_definition"] == FTPx:
        state_args = {
            "mole_frac_comp": {
                "H2O": model.fs.unit.inlet.mole_frac_comp[0, "H2O"].value,
                "A": model.fs.unit.inlet.mole_frac_comp[0, "A"].value,
                "B": model.fs.unit.inlet.mole_frac_comp[0, "B"].value,
                "AB": model.fs.unit.inlet.mole_frac_comp[0, "AB"].value,
            },
            "pressure": 101325,
            "temperature": 298,
            "flow_mol": 10,
        }

    flags = fix_state_vars(model.fs.unit.control_volume.properties_out, state_args)
    revert_state_vars(model.fs.unit.control_volume.properties_out, flags)

    model.fs.unit.initialize(optarg=solver.options, outlvl=idaeslog.DEBUG)

    assert degrees_of_freedom(model) == 0

    results = solver.solve(model, tee=True)

    assert results.solver.termination_condition == TerminationCondition.optimal
    assert results.solver.status == SolverStatus.ok

    print("comp\toutlet.tot_molfrac")
    for i in model.fs.unit.control_volume.properties_out[0.0].mole_frac_comp:
        print(
            str(i)
            + "\t"
            + str(
                value(
                    model.fs.unit.control_volume.properties_out[0.0].mole_frac_comp[i]
                )
            )
        )
    print()

    # NOTE: Changed all to mole fraction
    for i in model.fs.unit.control_volume.properties_out[0.0].mole_frac_phase_comp:
        print(
            str(i)
            + "\t"
            + str(
                value(
                    model.fs.unit.control_volume.properties_out[
                        0.0
                    ].mole_frac_phase_comp[i]
                )
            )
        )

    A = value(
        model.fs.unit.control_volume.properties_out[0.0].mole_frac_phase_comp[
            "Liq", "A"
        ]
    )
    B = value(
        model.fs.unit.control_volume.properties_out[0.0].mole_frac_phase_comp[
            "Liq", "B"
        ]
    )
    Ksp = value(model.fs.unit.control_volume.reactions[0.0].k_eq["AB_Ksp"].expr)

    print()
    if Ksp * 1.01 >= A * B:
        print("Constraint is satisfied!")
    else:
        print("Constraint is VIOLATED!")
        print("\tRelative error: " + str(Ksp / A / B) + ">=1")
        assert False
    print("Ksp =\t" + str(Ksp))
    print("A*B =\t" + str(A * B))

    print("==========================================================================")

    return model
Exemplo n.º 20
0
    def initialize(blk, state_args_feedwater={}, state_args_water_steam={},
                   outlvl=idaeslog.NOTSET, solver='ipopt', optarg={'tol': 1e-6}):
        '''
        Drum initialization routine.

        Keyword Arguments:
            state_args : a dict of arguments to be passed to the property
                           package(s) for the control_volume of the model to
                           provide an initial state for initialization
                           (see documentation of the specific property package)
                           (default = None).
            outlvl : sets output level of initialisation routine

                     * 0 = no output (default)
                     * 1 = return solver state for each step in routine
                     * 2 = return solver state for each step in subroutines
                     * 3 = include solver output infomation (tee=True)

            optarg : solver options dictionary object (default={'tol': 1e-6})
            solver : str indicating whcih solver to use during
                     initialization (default = 'ipopt')

        Returns:
            None
        '''
        init_log = idaeslog.getInitLogger(blk.name, outlvl, tag="unit")
        solve_log = idaeslog.getSolveLogger(blk.name, outlvl, tag="unit")

        opt = SolverFactory(solver)
        opt.options = optarg

        init_log.info_low("Starting initialization...")
        # fix FeedWater Inlet
        flags_fw = fix_state_vars(blk.mixer.FeedWater_state,
                                  state_args_feedwater)

        # expecting 2 DOF due to pressure driven constraint
        if degrees_of_freedom(blk) != 2:
            raise Exception(degrees_of_freedom(blk))

        blk.flash.initialize(state_args_water_steam=state_args_water_steam,
                             outlvl=outlvl,
                             optarg=optarg,
                             solver=solver)
        init_log.info("Initialization Step 1 Complete.")

        blk.mixer.SaturatedWater.flow_mol[:].fix(blk.flash.liq_outlet.
                                                 flow_mol[0].value)
        blk.mixer.SaturatedWater.pressure[:].fix(blk.flash.liq_outlet.
                                                 pressure[0].value)
        blk.mixer.SaturatedWater.enth_mol[:].fix(blk.flash.liq_outlet.
                                                 enth_mol[0].value)
        blk.mixer.initialize(outlvl=outlvl,
                             optarg=optarg,
                             solver=solver)
        init_log.info("Initialization Step 2 Complete.")

        blk.control_volume.initialize(outlvl=outlvl,
                                      optarg=optarg,
                                      solver=solver,
                                      hold_state=False)
        init_log.info("Initialization Step 3 Complete.")

        # fix flash Inlet
        flags_steam = fix_state_vars(blk.flash.mixed_state,
                                     state_args_water_steam)
        # unfix inlets (connected with arc)
        blk.mixer.SaturatedWater.flow_mol[:].unfix()
        blk.mixer.SaturatedWater.enth_mol[:].unfix()
        blk.mixer.SaturatedWater.pressure[:].unfix()
        blk.mixer.FeedWater.pressure[0].unfix()

        # solve model
        with idaeslog.solver_log(solve_log, idaeslog.DEBUG) as slc:
            res = opt.solve(blk, tee=slc.tee)
        init_log.info_high(
                "Initialization Step 4 {}.".format(idaeslog.condition(res))
            )
        revert_state_vars(blk.mixer.FeedWater_state, flags_fw)
        revert_state_vars(blk.flash.mixed_state, flags_steam)
        init_log.info("Initialization Complete.")
Exemplo n.º 21
0
    def initialize(blk, outlvl=idaeslog.NOTSET, optarg={}, solver=None):
        '''
        Initialisation routine for reaction package.

        Keyword Arguments:
            outlvl : sets output level of initialization routine
            optarg : solver options dictionary object (default={})
            solver : str indicating whcih solver to use during
                     initialization (default = None, use default solver)
        Returns:
            None
        '''
        init_log = idaeslog.getInitLogger(blk.name, outlvl, tag="reactions")
        solve_log = idaeslog.getSolveLogger(blk.name, outlvl, tag="reactions")

        init_log.info_high('Starting initialization')

        # TODO - Update in the future as needed
        # Get a single representative block for getting config arguments
        for k in blk.keys():
            break

        # Fix state variables if not already fixed
        # Fix state variables of the primary (solid) state block
        state_var_flags = fix_state_vars(blk[k].config.solid_state_block)

        # Fix values of secondary (gas) state block variables if not fixed,
        # as well as the solid density variable.
        # This is done to keep the initialization problem square
        Cflag = {}  # Gas concentration flag
        Dflag = {}  # Solid density flag

        for k in blk.keys():
            for j in blk[k]._params.gas_component_list:
                if blk[k].gas_state_ref.dens_mol_comp[j].fixed is True:
                    Cflag[k, j] = True
                else:
                    Cflag[k, j] = False
                    blk[k].gas_state_ref.dens_mol_comp[j].fix(
                        blk[k].gas_state_ref.dens_mol_comp[j].value)
            if blk[k].solid_state_ref.dens_mass_skeletal.fixed is True:
                Dflag[k] = True
            else:
                Dflag[k] = False
                blk[k].solid_state_ref.dens_mass_skeletal.fix(
                    blk[k].solid_state_ref.dens_mass_skeletal.value)

        # Create solver
        opt = get_solver(solver, optarg)

        # Initialise values
        for k in blk.keys():
            if hasattr(blk[k], "OC_conv_eqn"):
                calculate_variable_from_constraint(blk[k].OC_conv,
                                                   blk[k].OC_conv_eqn)

            if hasattr(blk[k], "OC_conv_temp_eqn"):
                calculate_variable_from_constraint(blk[k].OC_conv_temp,
                                                   blk[k].OC_conv_temp_eqn)

            for j in blk[k]._params.rate_reaction_idx:
                if hasattr(blk[k], "rate_constant_eqn"):
                    calculate_variable_from_constraint(
                        blk[k].k_rxn[j], blk[k].rate_constant_eqn[j])

                if hasattr(blk[k], "gen_rate_expression"):
                    calculate_variable_from_constraint(
                        blk[k].reaction_rate[j], blk[k].gen_rate_expression[j])

        # Solve property block if non-empty
        free_vars = 0
        for k in blk.keys():
            free_vars += number_unfixed_variables_in_activated_equalities(
                blk[k])

        if free_vars > 0:
            with idaeslog.solver_log(solve_log, idaeslog.DEBUG) as slc:
                res = solve_indexed_blocks(opt, [blk], tee=slc.tee)
        else:
            res = ""
        init_log.info_high("reactions initialization complete {}.".format(
            idaeslog.condition(res)))

        # ---------------------------------------------------------------------
        # Revert state vars and other variables to pre-initialization states
        # Revert state variables of the primary (solid) state block
        revert_state_vars(blk[k].config.solid_state_block, state_var_flags)

        for k in blk.keys():
            for j in blk[k]._params.gas_component_list:
                if Cflag[k, j] is False:
                    blk[k].gas_state_ref.dens_mol_comp[j].unfix()
            if Dflag[k] is False:
                blk[k].solid_state_ref.dens_mass_skeletal.unfix()

        init_log = idaeslog.getInitLogger(blk.name, outlvl, tag="reactions")
        init_log.info_high('States released.')