def main():
    """
    Make the flowsheet object and solve
    """
    flowsheet = Flowsheet(name='MB_Model')

    # Fix variables
    setInputs(flowsheet)

    ts = time.time()

    # Initialize fuel reactor
    flowsheet.MB_fuel._initialize(outlvl=1,
                                  optarg={
                                      "tol": 1e-8,
                                      "max_cpu_time": 600,
                                      "print_level": 5,
                                      "halt_on_ampl_error": 'yes'
                                  })

    # Set fuel and air inlet temperatures to 20 °C
    flowsheet.MB_fuel.Gas_In_Tg.fix(293.15)

    # Create a solver
    stee = True
    opt = SolverFactory('ipopt')
    opt.options = {
        'tol': 1e-8,
        'linear_solver': 'ma27',
        #                 'mu_init': 1e-8,
        'bound_push': 1e-8,
        'max_cpu_time': 600,
        'print_level': 5
    }

    results = opt.solve(flowsheet, tee=stee)

    print("\n")
    print("----------------------------------------------------------")
    print('Total simulation time: ', value(time.time() - ts), " s")
    print("----------------------------------------------------------")

    # Print some variables
    print_summary_fuel_reactor(flowsheet)

    # Plot some variables
    results_plot_fuel_reactor(flowsheet)

    # Store the flowsheet
    return flowsheet
예제 #2
0
def main():
    """
    Make the flowsheet object and solve
    """
    flowsheet = Flowsheet(name='MB_Model')

    # Fix variables
    setInputs(flowsheet)

    ts = time.time()

    # Initialize fuel reactor
    flowsheet.MB_fuel._initialize(outlvl=1,
                                  optarg={
                                      "tol": 1e-8,
                                      "max_cpu_time": 600,
                                      "print_level": 5,
                                      "halt_on_ampl_error": 'yes'
                                  })

    # Create a solver
    opt = SolverFactory('ipopt')
    opt.options = {
        'tol': 1e-8,
        'linear_solver': 'ma27',
        'bound_push': 1e-8,
        'max_cpu_time': 600,
        'print_level': 0
    }

    results = opt.solve(flowsheet,
                        tee=True,
                        symbolic_solver_labels=False,
                        keepfiles=False)

    print("\n")
    print("----------------------------------------------------------")
    print('Total simulation time: ', value(time.time() - ts), " s")
    print("----------------------------------------------------------")

    # Print some variables
    print_summary_fuel_reactor(flowsheet)

    # Plot some variables
    results_plot_fuel_reactor(flowsheet)

    # Store the flowsheet
    return flowsheet
예제 #3
0
    def initialize(blk,
                   state_args={},
                   state_vars_fixed=False,
                   hold_state=False,
                   outlvl=idaeslog.NOTSET,
                   solver='ipopt',
                   optarg={'tol': 1e-8}):
        """
        Initialization routine for property package.
        Keyword Arguments:
            state_args : Dictionary with initial guesses for the state vars
                         chosen. Note that if this method is triggered
                         through the control volume, and if initial guesses
                         were not provied at the unit model level, the
                         control volume passes the inlet values as initial
                         guess.The keys for the state_args dictionary are:

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

        init_log = idaeslog.getInitLogger(blk.name, outlvl, tag="properties")
        solve_log = idaeslog.getSolveLogger(blk.name, outlvl, tag="properties")

        # Fix state variables if not already fixed
        if state_vars_fixed is False:
            flags = fix_state_vars(blk, state_args)

        else:
            # Check when the state vars are fixed already result in dof 0
            for k in blk.keys():
                if degrees_of_freedom(blk[k]) != 0:
                    raise Exception("State vars fixed but degrees of freedom "
                                    "for state block is not zero during "
                                    "initialization.")
        # Set solver options
        if optarg is None:
            sopt = {"tol": 1e-8}
        else:
            sopt = optarg

        opt = SolverFactory('ipopt')
        opt.options = sopt

        # ---------------------------------------------------------------------
        # If present, initialize bubble and dew point calculations
        for k in blk.keys():
            if hasattr(blk[k], "eq_temperature_dew"):
                calculate_variable_from_constraint(blk[k].temperature_dew,
                                                   blk[k].eq_temperature_dew)

            if hasattr(blk[k], "eq_pressure_dew"):
                calculate_variable_from_constraint(blk[k].pressure_dew,
                                                   blk[k].eq_pressure_dew)

        init_log.info_high("Initialization Step 1 - Dew and bubble points "
                           "calculation completed.")

        # ---------------------------------------------------------------------
        # If flash, initialize T1 and Teq
        for k in blk.keys():
            if (blk[k].config.has_phase_equilibrium
                    and not blk[k].config.defined_state):
                blk[k]._t1.value = max(blk[k].temperature.value,
                                       blk[k].temperature_bubble.value)
                blk[k]._teq.value = min(blk[k]._t1.value,
                                        blk[k].temperature_dew.value)

        init_log.info_high("Initialization Step 2 - Equilibrium temperature "
                           " calculation completed.")

        # ---------------------------------------------------------------------
        # Initialize flow rates and compositions
        # TODO : This will need to be generalised more when we move to a
        # modular implementation
        for k in blk.keys():
            # Deactivate equilibrium constraints, as state is fixed
            if hasattr(blk[k], 'equilibrium_constraint'):
                blk[k].equilibrium_constraint.deactivate()

        free_vars = 0
        for k in blk.keys():
            free_vars += number_unfixed_variables(blk[k])
        if free_vars > 0:
            try:
                with idaeslog.solver_log(solve_log, idaeslog.DEBUG) as slc:
                    res = solve_indexed_blocks(opt, [blk], tee=slc.tee)
            except:
                res = None
        else:
            res = None

        for k in blk.keys():
            # Reactivate equilibrium constraints
            if hasattr(blk[k], 'equilibrium_constraint'):
                blk[k].equilibrium_constraint.activate()

        # ---------------------------------------------------------------------
        # Return state to initial conditions
        if state_vars_fixed is False:
            if hold_state is True:
                return flags
            else:
                blk.release_state(flags)

        init_log.info("Initialization Complete")
예제 #4
0
    def initialize(
            blk,
            state_args={
                "flow_component": {
                    "N2": 1.0,
                    "CO2": 1.0,
                    "NO": 1.0,
                    "O2": 1.0,
                    "H2O": 1.0,
                    "SO2": 1.0
                },
                "pressure": 1e5,
                "temperature": 495.0
            },
            hold_state=False,
            state_vars_fixed=False,
            outlvl=0,
            solver='ipopt',
            optarg={'tol': 1e-8}):
        '''
        Initialisation routine for property package.

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

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

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

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

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

        opt = SolverFactory(solver)
        opt.options = optarg

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

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

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

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

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

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

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

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

        if state_vars_fixed is False:
            if hold_state is True:
                return flags
            else:
                blk.release_state(flags)
예제 #5
0
def main():
    """
    Make the flowsheet object and solve
    """
    ss_flowsheet = ss_sim_reduced.main()

    flowsheet = Flowsheet(name='MB_Model')

    # fill in values of IC parameters from steady state solve
    setICs(flowsheet, ss_flowsheet)

    # Fix variables
    setInputs(flowsheet)

    # Initialize at steady state
    initialize_ss(flowsheet, ss_flowsheet)
    mb = flowsheet.MB_fuel

    #write_differential_equations(flowsheet)

    # Then perturb
    solid_x_ptb = {'Fe2O3': 0.25, 'Fe3O4': 0.01, 'Al2O3': 0.74}
    gas_y_ptb = {'CO2': 0.03999, 'H2O': 0.00001, 'CH4': 0.96}
    #perturbInputs(flowsheet,0,Solid_M=691.4,Solid_T=1283.15,Solid_x=solid_x_ptb,
    #        Gas_F=150,Gas_T=350,Gas_y=gas_y_ptb)
    for t in mb.t:
        perturbInputs(flowsheet, t, Solid_M=691.4)

    # should put this in a dedicated ~intialize~ function
    # that also intelligently initializes the model after perturbation
    mb.eq_d4.deactivate()
    mb.eq_d5.deactivate()
    mb.eq_d8.deactivate()
    mb.eq_d9.deactivate()
    mb.eq_d10.deactivate()
    mb.eq_g7.deactivate()
    mb.eq_g8.deactivate()
    mb.eq_g10.deactivate()
    mb.eq_g11.deactivate()
    mb.eq_g12.deactivate()
    mb.eq_g13.deactivate()
    mb.eq_g14.deactivate()
    mb.eq_g4.deactivate()
    mb.eq_g5.deactivate()
    mb.eq_g2.deactivate()
    mb.Tg_GW.fix(0.0)
    mb.Tw_GW.fix(0.0)
    mb.Tg_refractory.fix(0.0)
    mb.Tw_Wamb.fix()
    mb.Tw.fix()
    mb.Nuw.fix()
    mb.Nu_ext.fix()
    mb.hw.fix()
    mb.hext.fix()
    mb.hext2.fix()
    mb.U.fix()
    mb.Uw.fix()
    mb.Pr_ext.fix()
    mb.Ra.fix()
    mb.Re.fix()
    ###

    # other tentatively unused variables:
    mb.mFe_mAl.fix(0.0)
    mb.Solid_Out_M_Comp.fix()

    # choose how to calculate certain algebraic variables:
    mb.eq_c5.deactivate()

    #
    for index in mb.dGh_fluxdz:
        mb.dGh_fluxdz[index].fix(0)

    with open('dyn_fs_init.txt', 'w') as f:
        flowsheet.display(ostream=f)

    # Create a solver
    tol = 1e-8
    opt = SolverFactory('ipopt')
    opt.options = {
        'tol': tol,
        'linear_solver': 'ma57',
        'bound_push': 1e-8,
        'max_cpu_time': 600,
        'print_level': 5,
        'output_file': 'ipopt_out.txt',
        'linear_system_scaling': 'mc19',
        'linear_scaling_on_demand': 'no',
        'halt_on_ampl_error': 'yes'
    }
    flowsheet.write('fs_dyn.nl')

    # initialized at steady state, works regardless:
    flowsheet.strip_bounds()

    #fs_list = clc_integrate(mb)
    #for t in fs_list:
    #    load_fe(fs_list[t], flowsheet, t)

    #for z in mb.z:
    #    for t in mb.t:
    #        mb.Cg[z,'CH4',t].setlb(1e-8)
    print_violated_constraints(flowsheet, tol)

    for t in mb.t:
        alg_update(flowsheet, t)
        update_time_derivatives(flowsheet, t)

    with open('dyn_fs_init.txt', 'w') as f:
        flowsheet.display(ostream=f)

    print_violated_constraints(flowsheet, tol)

    #mb.input_objective = Objective(expr=sum((mb.Solid_In_M[t] -601.4)**2 for t in mb.t))

    for index in mb.dTgdt:
        mb.dTgdt[index].fix(0)
    for index in mb.dGh_fluxdz:
        mb.dGh_fluxdz[index].fix(0)
    mb.dTgdt_disc_eq.deactivate()
    mb.dGh_fluxdz_disc_eq.deactivate()

    #mb.cont_param.set_value(0)
    #mb.dCgdt_disc_eq.deactivate()
    #for index in mb.dCgdt: mb.dCgdt[index].fix(0)
    #mb.dqdt_disc_eq.deactivate()
    #for index in mb.dqdt: mb.dqdt[index].fix(0)
    #mb.dTsdt_disc_eq.deactivate()
    #for index in mb.dTsdt: mb.dTsdt[index].fix(0)
    #mb.dTgdt_disc_eq.deactivate()
    #for index in mb.dTgdt: mb.dTgdt[index].fix(0)
    #mb.eq_h1.deactivate()
    #mb.eq_h2.deactivate()
    #mb.eq_h3.deactivate()
    #mb.eq_h4.deactivate()
    #flowsheet.write('fs_dyn.nl')

    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #mb.dCgdt_disc_eq.activate()
    #for index in mb.dCgdt: mb.dCgdt[index].unfix()
    #mb.dqdt_disc_eq.activate()
    #for index in mb.dqdt: mb.dqdt[index].unfix()
    #mb.dTsdt_disc_eq.activate()
    #for index in mb.dTsdt: mb.dTsdt[index].unfix()
    #mb.dTgdt_disc_eq.activate()
    #for index in mb.dTsdt: mb.dTgdt[index].unfix()
    #mb.eq_h1.activate()
    #mb.eq_h2.activate()
    #mb.eq_h3.activate()
    #mb.eq_h4.activate()

    #print_violated_constraints(flowsheet,t)

    #print('\n-----------------')
    #print('#\epsilon = 1e-5#')
    #print('-----------------\n')
    #mb.cont_param.set_value(1e-5)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 1e-4#')
    #print('-----------------\n')
    #mb.cont_param.set_value(1e-4)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 1e-3#')
    #print('-----------------\n')
    #mb.cont_param.set_value(1e-3)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 1e-2#')
    #print('-----------------\n')
    #mb.cont_param.set_value(1e-2)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 2e-2#')
    #print('-----------------\n')
    #mb.cont_param.set_value(2e-2)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 5e-2#')
    #print('-----------------\n')
    #mb.cont_param.set_value(5e-2)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 8e-2#')
    #print('-----------------\n')
    #mb.cont_param.set_value(5e-2)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 1e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(1e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 2e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(2e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 4e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(4e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #
    #print('\n-----------------')
    #print('#\epsilon = 5e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(5e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 6e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(6e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 7e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(7e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 7.5e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(7.5e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 8e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(8e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #
    #print('\n-----------------')
    #print('#\epsilon = 8.5e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(8.5e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 8.8e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(8.8e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.1e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.1e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.2e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.2e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.3e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.3e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.4e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.4e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.5e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.5e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.6e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.6e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.7e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.7e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.8e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.8e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.9e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.9e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    print('\n-----------------')
    print('#\epsilon = 1#')
    print('-----------------\n')
    mb.cont_param.set_value(1)
    results = opt.solve(flowsheet,
                        tee=True,
                        symbolic_solver_labels=False,
                        keepfiles=False)
    results = opt.solve(flowsheet,
                        tee=True,
                        symbolic_solver_labels=False,
                        keepfiles=False)

    print_violated_constraints(flowsheet, tol)

    #for t in mb.t:
    #    alg_update(flowsheet,t)
    #    update_time_derivatives(flowsheet,t)
    #print_violated_constraints(flowsheet,t)

    #with open('dyn_fs_sol.txt','w') as f:
    #    flowsheet.display(ostream=f)
    '''
    print("\n")
    print("----------------------------------------------------------")
    print('Total simulation time: ', value(time.time() - ts), " s")
    print("----------------------------------------------------------")
    
    # Print some variables 
    print_summary_fuel_reactor(flowsheet) 

    # Plot some variables 
    #results_plot_fuel_reactor(flowsheet) 

    #with open('m_fs.txt','w') as f:
    #    flowsheet.display(ostream=f)

    # Store the flowsheet    
    '''
    return flowsheet
예제 #6
0
    def initialize(blk,
                   flow_mol_comp=None,
                   temperature=None,
                   pressure=None,
                   hold_state=False,
                   outlvl=0,
                   state_vars_fixed=False,
                   solver='ipopt',
                   optarg={'tol': 1e-8}):
        '''
        Initialisation routine for property package.

        Keyword Arguments:
            flow_mol_comp : value at which to initialize component flows
                             (default=None)
            pressure : value at which to initialize pressure (default=None)
            temperature : value at which to initialize temperature
                          (default=None)
            outlvl : sets output level of initialisation routine

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

        Returns:
            If hold_states is True, returns a dict containing flags for
            which states were fixed during initialization.
        '''
        if state_vars_fixed is False:
            # Fix state variables if not already fixed
            Fcflag = {}
            Pflag = {}
            Tflag = {}

            for k in blk.keys():
                for j in blk[k]._params.component_list:
                    if blk[k].flow_mol_comp[j].fixed is True:
                        Fcflag[k, j] = True
                    else:
                        Fcflag[k, j] = False
                        if flow_mol_comp is None:
                            blk[k].flow_mol_comp[j].fix(1.0)
                        else:
                            blk[k].flow_mol_comp[j].fix(flow_mol_comp[j])

                if blk[k].pressure.fixed is True:
                    Pflag[k] = True
                else:
                    Pflag[k] = False
                    if pressure is None:
                        blk[k].pressure.fix(101325.0)
                    else:
                        blk[k].pressure.fix(pressure)

                if blk[k].temperature.fixed is True:
                    Tflag[k] = True
                else:
                    Tflag[k] = False
                    if temperature is None:
                        blk[k].temperature.fix(1500.0)
                    else:
                        blk[k].temperature.fix(temperature)

                for j in blk[k]._params.component_list:
                    blk[k].mole_frac[j] = \
                        (value(blk[k].flow_mol_comp[j]) /
                         sum(value(blk[k].flow_mol_comp[i])
                             for i in blk[k]._params.component_list))

            # If input block, return flags, else release state
            flags = {"Fcflag": Fcflag, "Pflag": Pflag, "Tflag": Tflag}

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

        opt = SolverFactory(solver)
        opt.options = optarg

        # ---------------------------------------------------------------------
        # Initialise values
        for k in blk.keys():
            for j in blk[k]._params.component_list:

                if hasattr(blk[k], "cp_shomate_eqn"):
                    calculate_variable_from_constraint(
                        blk[k].cp_mol_comp[j], blk[k].cp_shomate_eqn[j])

                if hasattr(blk[k], "enthalpy_shomate_eqn"):
                    calculate_variable_from_constraint(
                        blk[k].enth_mol_phase_comp["Vap", j],
                        blk[k].enthalpy_shomate_eqn[j])

                if hasattr(blk[k], "entropy_shomate_eqn"):
                    calculate_variable_from_constraint(
                        blk[k].entr_mol_phase_comp["Vap", j],
                        blk[k].entropy_shomate_eqn[j])

                if hasattr(blk[k], "partial_gibbs_energy_eqn"):
                    calculate_variable_from_constraint(
                        blk[k].gibbs_mol_phase_comp["Vap", j],
                        blk[k].partial_gibbs_energy_eqn[j])

            if hasattr(blk[k], "ideal_gas"):
                calculate_variable_from_constraint(
                    blk[k].dens_mol_phase["Vap"], blk[k].ideal_gas)

            if hasattr(blk[k], "mixture_heat_capacity_eqn"):
                calculate_variable_from_constraint(
                    blk[k].cp_mol, blk[k].mixture_heat_capacity_eqn)

            if hasattr(blk[k], "mixture_enthalpy_eqn"):
                calculate_variable_from_constraint(blk[k].enth_mol,
                                                   blk[k].mixture_enthalpy_eqn)

            if hasattr(blk[k], "mixture_entropy_eqn"):
                calculate_variable_from_constraint(blk[k].entr_mol,
                                                   blk[k].mixture_entropy_eqn)

            if hasattr(blk[k], "total_flow_eqn"):
                calculate_variable_from_constraint(blk[k].flow_mol,
                                                   blk[k].total_flow_eqn)

            if hasattr(blk[k], "mixture_gibbs_eqn"):
                calculate_variable_from_constraint(blk[k].gibbs_mol,
                                                   blk[k].mixture_gibbs_eqn)

        results = solve_indexed_blocks(opt, blk, tee=stee)

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

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

        if state_vars_fixed is False:
            if hold_state is True:
                return flags
            else:
                blk.release_state(flags)
예제 #7
0
    def initialize(self,
                   state_args={},
                   state_vars_fixed=False,
                   hold_state=False,
                   outlvl=idaeslog.NOTSET,
                   solver=None,
                   optarg={}):
        """
        Initialization routine for property package.
        Keyword Arguments:
            state_args : Dictionary with initial guesses for the state vars
                         chosen. Note that if this method is triggered
                         through the control volume, and if initial guesses
                         were not provided at the unit model level, the
                         control volume passes the inlet values as initial
                         guess.The keys for the state_args dictionary are:

                         flow_mass_phase_comp : value at which to initialize
                                               phase component flows
                         pressure : value at which to initialize pressure
                         temperature : value at which to initialize temperature
            outlvl : sets output level of initialization routine
            optarg : solver options dictionary object (default={})
            state_vars_fixed: Flag to denote if state vars have already been
                              fixed.
                              - True - states have already been fixed by the
                                       control volume 1D. Control volume 0D
                                       does not fix the state vars, so will
                                       be False if this state block is used
                                       with 0D blocks.
                             - False - states have not been fixed. The state
                                       block will deal with fixing/unfixing.
            solver : Solver object to use during initialization if None is provided
                     it will use the default solver for IDAES (default = None)
            hold_state : flag indicating whether the initialization routine
                         should unfix any state variables fixed during
                         initialization (default=False).
                         - True - states variables are not unfixed, and
                                 a dict of returned containing flags for
                                 which states were fixed during
                                 initialization.
                        - False - state variables are unfixed after
                                 initialization by calling the
                                 release_state method
        Returns:
            If hold_states is True, returns a dict containing flags for
            which states were fixed during initialization.
        """
        # Get loggers
        init_log = idaeslog.getInitLogger(self.name, outlvl, tag="properties")
        solve_log = idaeslog.getSolveLogger(self.name,
                                            outlvl,
                                            tag="properties")

        # Set solver and options
        # TODO: clean up once IDAES new API for initialize solvers is released
        if isinstance(solver, str):
            opt = SolverFactory(solver)
            opt.options = optarg
        else:
            if solver is None:
                opt = get_default_solver()
            else:
                opt = solver
                opt.options = optarg

        # Fix state variables
        flags = fix_state_vars(self, state_args)
        # Check when the state vars are fixed already result in dof 0
        for k in self.keys():
            dof = degrees_of_freedom(self[k])
            if dof != 0:
                raise PropertyPackageError("State vars fixed but degrees of "
                                           "freedom for state block is not "
                                           "zero during initialization.")

        # ---------------------------------------------------------------------
        skip_solve = True  # skip solve if only state variables are present
        for k in self.keys():
            if number_unfixed_variables(self[k]) != 0:
                skip_solve = False

        if not skip_solve:
            # Initialize properties
            with idaeslog.solver_log(solve_log, idaeslog.DEBUG) as slc:
                results = solve_indexed_blocks(opt, [self], tee=slc.tee)
            init_log.info_high("Property initialization: {}.".format(
                idaeslog.condition(results)))

        # ---------------------------------------------------------------------
        # If input block, return flags, else release state
        if state_vars_fixed is False:
            if hold_state is True:
                return flags
            else:
                self.release_state(flags)
예제 #8
0
파일: ss_sim.py 프로젝트: Robbybp/IDAES-CLC
def main(**kwargs):
    """
    Make the flowsheet object and solve
    """
    flowsheet = Flowsheet(name='MB_Model')

    # Fix variables
    setInputs(flowsheet)

    ts = time.time()

    mb = flowsheet.MB_fuel

    # Initialize fuel reactor
    flowsheet.MB_fuel._initialize(outlvl=1,
                                  optarg={
                                      "tol": 1e-8,
                                      "max_cpu_time": 600,
                                      "print_level": 5,
                                      "halt_on_ampl_error": 'yes'
                                  })

    # Create a solver
    opt = SolverFactory('ipopt')
    opt.options = {
        'tol': 1e-8,
        'linear_solver': 'ma27',
        'bound_push': 1e-8,
        'max_cpu_time': 600,
        'print_level': 5
    }

    results = opt.solve(flowsheet,
                        tee=True,
                        symbolic_solver_labels=False,
                        keepfiles=False)

    #flowsheet.MB_fuel.Solid_In_M.fix(691.4)
    #flowsheet.MB_fuel.Gas_In_y['CO2'].fix(0.03999)
    #flowsheet.MB_fuel.Gas_In_y['H2O'].fix(0.00001)
    #flowsheet.MB_fuel.Gas_In_y['CH4'].fix(0.96)

    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    print("\n")
    print("----------------------------------------------------------")
    print('Total simulation time: ', value(time.time() - ts), " s")
    print("----------------------------------------------------------")

    # Print some variables
    #print_summary_fuel_reactor(flowsheet)

    # Plot some variables
    #results_plot_fuel_reactor(flowsheet)

    m = flowsheet.MB_fuel
    if 'Solid_M' in kwargs:
        m.Solid_In_M.fix(kwargs['Solid_M'])
    if 'Solid_T' in kwargs:
        m.Solid_In_Ts[t].fix(kwargs['Solid_T'])
    if 'Solid_x' in kwargs:
        m.Solid_In_x['Fe2O3'].fix(kwargs['Solid_x']['Fe2O3'])
        m.Solid_In_x['Fe3O4'].fix(kwargs['Solid_x']['Fe3O4'])
        m.Solid_In_x['Al2O3'].fix(kwargs['Solid_x']['Al2O3'])
    if 'Gas_F' in kwargs:
        m.Gas_In_F.fix(kwargs['Gas_F'])
    if 'Gas_P' in kwargs:
        m.Gas_In_P.fix(kwargs['Gas_P'])
    if 'Gas_T' in kwargs:
        m.Gas_In_T.fix(kwargs['Gas_T'])
    if 'Gas_y' in kwargs:
        m.Gas_In_y['CO2'].fix(kwargs['Gas_y']['CO2'])
        m.Gas_In_y['H2O'].fix(kwargs['Gas_y']['H2O'])
        m.Gas_In_y['CH4'].fix(kwargs['Gas_y']['CH4'])

    results = opt.solve(flowsheet, tee=True)

    with open('ss_fs.txt', 'w') as f:
        flowsheet.display(ostream=f)

    dt_Gflux_CO2 = []
    dt_Gflux_H2O = []
    dt_Gflux_CH4 = []
    dt_Sflux_Fe2O3 = []
    dt_Sflux_Fe3O4 = []
    dt_Sflux_Al2O3 = []
    dt_Ctrans_CO2 = []
    dt_Ctrans_H2O = []
    dt_Ctrans_CH4 = []
    dt_qtrans_Fe2O3 = []
    dt_qtrans_Fe3O4 = []
    dt_qtrans_Al2O3 = []
    dt_Ghflux = []
    dt_Ts = []
    dt_TgGS = []
    dt_TsGS = []
    dt_vg = []
    dt_vs = []

    #    for z in mb.z.get_finite_elements():
    #        if z != mb.z.first() and z != mb.z.last():
    #
    #            dt_Gflux_CO2.append( (mb.Cg[z,'CO2'].value-mb.Cg[prev,'CO2'].value)/\
    #                    (mb.G_flux[z,'CO2'].value-mb.G_flux[prev,'CO2'].value) \
    #                    *(z-prev)*mb.eps.value*mb.L.value /(z-prev))
    #
    #            dt_Gflux_H2O.append( (mb.Cg[z,'H2O'].value-mb.Cg[prev,'H2O'].value)/\
    #                    (mb.G_flux[z,'H2O'].value-mb.G_flux[prev,'H2O'].value) \
    #                    *(z-prev)*mb.eps.value*mb.L.value /(z-prev))
    #
    #            dt_Gflux_CH4.append( (mb.Cg[z,'CH4'].value-mb.Cg[prev,'CH4'].value)/\
    #                    (mb.G_flux[z,'CH4'].value-mb.G_flux[prev,'CH4'].value) \
    #                    *(z-prev)*mb.eps.value*mb.L.value /(z-prev))
    #
    #            dt_Ctrans_CO2.append( (mb.Cg[z,'CO2'].value-mb.Cg[prev,'CO2'].value)/\
    #                    (mb.Ctrans[z,'CO2'].value)* \
    #                    #-mv.Ctrans[prev,'CO2'].value)*\
    #                    mb.eps.value/(1-mb.eps.value) /(z-prev))
    #
    #            dt_Ctrans_H2O.append( (mb.Cg[z,'H2O'].value-mb.Cg[prev,'H2O'].value)/\
    #                    (mb.Ctrans[z,'H2O'].value)* \
    #                    #-mv.Ctrans[prev,'H2O'].value)*\
    #                    mb.eps.value/(1-mb.eps.value) /(z-prev))
    #
    #            dt_Ctrans_CH4.append( (mb.Cg[z,'CH4'].value-mb.Cg[prev,'CH4'].value)/\
    #                    (mb.Ctrans[z,'CH4'].value)* \
    #                    #-mv.Ctrans[prev,'CH4'].value)*\
    #                    mb.eps.value/(1-mb.eps.value) /(z-prev))
    #
    #            dt_Sflux_Fe2O3.append( (mb.q[z,'Fe2O3'].value-mb.q[prev,'Fe2O3'].value)/\
    #                    (mb.S_flux[z,'Fe2O3'].value-mb.S_flux[prev,'Fe2O3'].value)*\
    #                    (z-prev)/(1-mb.eps.value)*mb.L.value /(z-prev))
    #
    #            dt_Sflux_Fe3O4.append( (mb.q[z,'Fe3O4'].value-mb.q[prev,'Fe3O4'].value)/\
    #                    (mb.S_flux[z,'Fe3O4'].value-mb.S_flux[prev,'Fe3O4'].value)*\
    #                    (z-prev)/(1-mb.eps.value)*mb.L.value /(z-prev))
    #
    #            dt_Sflux_Al2O3.append( (mb.q[z,'Al2O3'].value-mb.q[prev,'Al2O3'].value)/\
    #                    (mb.S_flux[z,'Al2O3'].value-mb.S_flux[prev,'Al2O3'].value)*\
    #                    (z-prev)/(1-mb.eps.value)*mb.L.value /(z-prev))
    #
    #            dt_qtrans_Fe2O3.append( (mb.q[z,'Fe2O3'].value-mb.q[prev,'Fe2O3'].value)/\
    #                    (mb.qtrans[z,'Fe2O3'].value )/(z-prev))
    #                    #-mb.qtrans[prev,'Fe2O3'].value) )
    #
    #            dt_qtrans_Fe3O4.append( (mb.q[z,'Fe3O4'].value-mb.q[prev,'Fe3O4'].value)/\
    #                    (mb.qtrans[z,'Fe3O4'].value )/(z-prev))
    #                    #-mb.qtrans[prev,'Fe3O4'].value) )
    #
    #            dt_qtrans_Al2O3.append( (mb.q[z,'Fe3O4'].value-mb.q[prev,'Fe3O4'].value)/\
    #                    (mb.qtrans[z,'Fe3O4'].value )/(z-prev))
    #                    #-mb.qtrans[prev,'Fe3O4'].value) )
    #
    #            dt_Ghflux.append( (mb.Tg[z].value-mb.Tg[prev].value)/\
    #                (mb.Gh_flux[z].value-mb.Gh_flux[prev].value)* (z-prev)* mb.eps.value*\
    #                mb.L.value* mb.rho_vap[z].value* mb.cp_gas[z].value /(z-prev))
    #
    #            dt_Ts.append( (z-prev)*(1-mb.eps.value)*mb.L.value/mb.vs.value /(z-prev))
    #
    #            dt_TgGS.append( (mb.Tg[z].value - mb.Tg[prev].value)/\
    #                    mb.Tg_GS[z].value* mb.eps.value* mb.rho_vap[z].value* mb.cp_gas[z].value
    #                    /(z-prev))
    #
    #            dt_TsGS.append( (mb.Ts[z].value - mb.Ts[prev].value)/\
    #                    mb.Tg_GS[z].value* (1-mb.eps.value)* mb.rho_sol.value* mb.cp_sol[z].value*1e-3
    #                    /(z-prev))
    #
    #            dt_vg.append( mb.L.value*(z-prev)/mb.vg[z].value /(z-prev))
    #
    #            dt_vs.append( mb.L.value*(z-prev)/mb.vs.value /(z-prev))
    #
    #        prev = z
    #
    #    with open('dt.txt','w') as f:
    #        f.write('dt_Gflux_CO2\t')
    #        for t in dt_Gflux_CO2:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_Gflux_H2O\t')
    #        for t in dt_Gflux_H2O:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_Gflux_CH4\t')
    #        for t in dt_Gflux_CH4:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_Sflux_Fe2O3\t')
    #        for t in dt_Sflux_Fe2O3:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_Sflux_Fe3O4\t')
    #        for t in dt_Sflux_Fe3O4:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_Sflux_Al2O3\t')
    #        for t in dt_Sflux_Al2O3:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_Ctrans_CO2\t')
    #        for t in dt_Ctrans_CO2:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_Ctrans_H2O\t')
    #        for t in dt_Ctrans_H2O:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_Ctrans_CH4\t')
    #        for t in dt_Ctrans_CH4:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_qtrans_Fe2O3\t')
    #        for t in dt_qtrans_Fe2O3:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_qtrans_Fe3O4\t')
    #        for t in dt_qtrans_Fe3O4:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_qtrans_Al2O3\t')
    #        for t in dt_qtrans_Al2O3:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_Ghflux\t')
    #        for t in dt_Ghflux:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_Ts\t\t')
    #        for t in dt_Ts:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_TgGS\t\t')
    #        for t in dt_TgGS:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_TsGS\t\t')
    #        for t in dt_TsGS:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_vg\t\t')
    #        for t in dt_vg:
    #            f.write('%1.3f'%t +'\t')
    #
    #        f.write('\ndt_vs\t\t')
    #        for t in dt_vs:
    #            f.write('%1.3f'%t +'\t')

    # Store the flowsheet
    return flowsheet
예제 #9
0
파일: sens.py 프로젝트: jmorgan29/idaes-pse
def get_dfds_dcds(model, theta_names, tee=False, solver_options=None):
    """This function calculates gradient vector of the objective function
       and constraints with respect to the variables in theta_names.

    e.g) min f:  p1*x1+ p2*(x2^2) + p1*p2
         s.t  c1: x1 + x2 = p1
              c2: x2 + x3 = p2
              0 <= x1, x2, x3 <= 10
              p1 = 10
              p2 = 5
    - Variables = (x1, x2, x3, p1, p2)
    - Fix p1 and p2 with estimated values

    The following terms are used to define the output dimensions:
    Ncon   = number of constraints
    Nvar   = number of variables (Nx + Ntheta)
    Nx     = the numer of decision (primal) variables
    Ntheta = number of uncertain parameters.

    Parameters
    ----------
    model: Pyomo ConcreteModel
        model should includes an objective function
    theta_names: list of strings
        List of Var names
    tee: bool, optional
        Indicates that ef solver output should be teed
    solver_options: dict, optional
        Provides options to the solver (also the name of an attribute)

    Returns
    -------
    gradient_f: numpy.ndarray
        Length Nvar array. A gradient vector of the objective function
        with respect to the (decision variables, parameters)
        at the optimal solution
    gradient_c: scipy.sparse.csr.csr_matrix
        Ncon by Nvar size sparse matrix. A Jacobian matrix of the constraints
        with respect to the (decision variables, parameters) at the optimal
        solution. Each row contains [column number, row number, and value],
        colum order follows variable order in col and index starts from 1.
        Note that it follows k_aug. If no constraint exists, return []
    col: list
        Size Nvar. list of variable names
    row: list
        Size Ncon+1. List of constraints and objective function names
        The final element is the objective function name.
    line_dic: dict
        column numbers of the theta_names in the model. Index starts from 1

    Raises
    ------
    RuntimeError
        When ipopt or kaug or dotsens is not available
    Exception
        When ipopt fails
    """
    #Create the solver plugin using the ASL interface
    ipopt = SolverFactory('ipopt', solver_io='nl')
    if solver_options is not None:
        ipopt.options = solver_options
    kaug = SolverFactory('k_aug', solver_io='nl')
    dotsens = SolverFactory('dot_sens', solver_io='nl')
    if not ipopt.available(False):
        raise RuntimeError('ipopt is not available')
    if not kaug.available(False):
        raise RuntimeError('k_aug is not available')
    if not dotsens.available(False):
        raise RuntimeError('dotsens is not available')

    # Declare Suffixes
    _add_sensitivity_suffixes(model)

    # K_AUG SUFFIXES
    model.dof_v = Suffix(direction=Suffix.EXPORT)  #: SUFFIX FOR K_AUG
    model.rh_name = Suffix(
        direction=Suffix.IMPORT)  #: SUFFIX FOR K_AUG AS WELL
    kaug.options["print_kkt"] = ""
    results = ipopt.solve(model, tee=tee)

    # Raise Exception if ipopt fails
    if (results.solver.status == SolverStatus.warning):
        raise Exception(results.solver.Message)

    for o in model.component_objects(Objective, active=True):
        f_mean = value(o)
    model.ipopt_zL_in.update(model.ipopt_zL_out)
    model.ipopt_zU_in.update(model.ipopt_zU_out)
    #: run k_aug
    kaug.solve(model, tee=tee)  #: always call k_aug AFTER ipopt.
    model.write('col_row.nl',
                format='nl',
                io_options={'symbolic_solver_labels': True})
    # get the column numbers of theta
    line_dic = {}
    try:
        for v in theta_names:
            line_dic[v] = line_num('col_row.col', v)
        # load gradient of the objective function
        gradient_f = np.loadtxt("./GJH/gradient_f_print.txt")
        with open("col_row.col", "r") as myfile:
            col = myfile.read().splitlines()
        col = [
            i for i in col
            if SensitivityInterface.get_default_block_name() not in i
        ]
        with open("col_row.row", "r") as myfile:
            row = myfile.read().splitlines()
    except Exception as e:
        print('File not found.')
        raise e
    # load gradient of all constraints (sparse)
    # If no constraint exists, return []
    num_constraints = len(
        list(
            model.component_data_objects(Constraint,
                                         active=True,
                                         descend_into=True)))
    if num_constraints > 0:
        try:
            # load text file from kaug
            gradient_c = np.loadtxt("./GJH/A_print.txt")
            # This is a sparse matrix
            # gradient_c[:,0] are column index
            # gradient_c[:,1] are data index
            # gradient_c[:,1] are the matrix values
        except Exception as e:
            print('kaug file ./GJH/A_print.txt not found.')

        # Subtract 1 from row and column indices to convert from
        # start at 1 (kaug) to start at 0 (numpy)
        row_idx = gradient_c[:, 1] - 1
        col_idx = gradient_c[:, 0] - 1
        data = gradient_c[:, 2]
        gradient_c = sparse.csr_matrix((data, (row_idx, col_idx)),
                                       shape=(len(row) - 1, len(col)))
    else:
        gradient_c = np.array([])
    # remove all generated files

    shutil.move("col_row.nl", "./GJH/")
    shutil.move("col_row.col", "./GJH/")
    shutil.move("col_row.row", "./GJH/")
    shutil.rmtree('GJH', ignore_errors=True)

    return gradient_f, gradient_c, col, row, line_dic
예제 #10
0
def get_dfds_dcds(model, theta_names, tee=False, solver_options=None):
    """This function calculates gradient vector of the objective function 
       and constraints with respect to the variables and parameters.

    e.g) min f:  p1*x1+ p2*(x2^2) + p1*p2
         s.t  c1: x1 + x2 = p1
              c2: x2 + x3 = p2
              0 <= x1, x2, x3 <= 10
              p1 = 10
              p2 = 5
    - Variables = (x1, x2, x3, p1, p2)
    - Fix p1 and p2 with estimated values

    The following terms are used to define the output dimensions:
    Ncon   = number of constraints
    Nvar   = number of variables (Nx + Ntheta)
    Nx     = number of decision (primal) variables
    Ntheta = number of uncertain parameters.

    Parameters
    ----------
    model: Pyomo ConcreteModel
        model should include an objective function
    theta_names: list of strings
        List of Var names
    tee: bool, optional
        Indicates that ef solver output should be teed
    solver_options: dict, optional
        Provides options to the solver (also the name of an attribute)

    Returns
    -------
    gradient_f: numpy.ndarray
        Length Nvar array. A gradient vector of the objective function
        with respect to the (decision variables, parameters) at the optimal
        solution
    gradient_c: scipy.sparse.csr.csr_matrix
        Ncon by Nvar size sparse matrix. A Jacobian matrix of the
        constraints with respect to the (decision variables, parameters)
        at the optimal solution. Each row contains [column number,
        row number, and value], column order follows variable order in col
        and index starts from 1. Note that it follows k_aug.
        If no constraint exists, return []
    col: list
        Size Nvar list of variable names
    row: list
        Size Ncon+1 list of constraints and objective function names.
        The final element is the objective function name.
    line_dic: dict
        column numbers of the theta_names in the model. Index starts from 1

    Raises
    ------
    RuntimeError
        When ipopt or k_aug or dotsens is not available
    Exception
        When ipopt fails 
    """
    # Create the solver plugin using the ASL interface
    ipopt = SolverFactory('ipopt', solver_io='nl')
    if solver_options is not None:
        ipopt.options = solver_options
    k_aug = SolverFactory('k_aug', solver_io='nl')
    if not ipopt.available(False):
        raise RuntimeError('ipopt is not available')
    if not k_aug.available(False):
        raise RuntimeError('k_aug is not available')

    # Declare Suffixes
    _add_sensitivity_suffixes(model)

    # K_AUG SUFFIXES
    model.dof_v = Suffix(direction=Suffix.EXPORT)  #: SUFFIX FOR K_AUG
    model.rh_name = Suffix(
        direction=Suffix.IMPORT)  #: SUFFIX FOR K_AUG AS WELL
    k_aug.options["print_kkt"] = ""

    results = ipopt.solve(model, tee=tee)

    # Raise exception if ipopt fails
    if (results.solver.status == SolverStatus.warning):
        raise Exception(results.solver.Message)

    for o in model.component_objects(Objective, active=True):
        f_mean = value(o)
    model.ipopt_zL_in.update(model.ipopt_zL_out)
    model.ipopt_zU_in.update(model.ipopt_zU_out)

    # run k_aug
    k_aug_interface = K_augInterface(k_aug=k_aug)
    k_aug_interface.k_aug(model, tee=tee)  #: always call k_aug AFTER ipopt.

    nl_data = {}
    with InTempDir():
        base_fname = "col_row"
        nl_file = ".".join((base_fname, "nl"))
        row_file = ".".join((base_fname, "row"))
        col_file = ".".join((base_fname, "col"))
        model.write(nl_file, io_options={"symbolic_solver_labels": True})
        for fname in [nl_file, row_file, col_file]:
            with open(fname, "r") as fp:
                nl_data[fname] = fp.read()

    col = nl_data[col_file].strip("\n").split("\n")
    row = nl_data[row_file].strip("\n").split("\n")

    # get the column numbers of "parameters"
    line_dic = {name: col.index(name) for name in theta_names}

    grad_f_file = os.path.join("GJH", "gradient_f_print.txt")
    grad_f_string = k_aug_interface.data[grad_f_file]
    gradient_f = np.fromstring(grad_f_string, sep="\n\t")
    col = [
        i for i in col
        if SensitivityInterface.get_default_block_name() not in i
    ]

    grad_c_file = os.path.join("GJH", "A_print.txt")
    grad_c_string = k_aug_interface.data[grad_c_file]
    gradient_c = np.fromstring(grad_c_string, sep="\n\t")

    # Jacobian file is in "COO format," i.e. an nnz-by-3 array.
    # Reshape to a numpy array that matches this format.
    gradient_c = gradient_c.reshape((-1, 3))

    num_constraints = len(row) - 1  # Objective is included as a row
    if num_constraints > 0:
        row_idx = gradient_c[:, 1] - 1
        col_idx = gradient_c[:, 0] - 1
        data = gradient_c[:, 2]
        gradient_c = scipy.sparse.csr_matrix((data, (row_idx, col_idx)),
                                             shape=(num_constraints, len(col)))
    else:
        gradient_c = np.array([])

    return gradient_f, gradient_c, col, row, line_dic
예제 #11
0
def main():
    """
    Make the flowsheet object and solve
    """
    ss_flowsheet = ss_sim.main()

    flowsheet = Flowsheet(name='MB_Model')

    # fill in values of IC parameters from steady state solve
    setICs(flowsheet, ss_flowsheet)

    # Fix variables
    setInputs(flowsheet)

    # Initialize at steady state
    initialize_ss(flowsheet, ss_flowsheet)
    mb = flowsheet.MB_fuel

    # Then perturb
    solid_x_ptb = {'Fe2O3': 0.25, 'Fe3O4': 0.01, 'Al2O3': 0.74}
    gas_y_ptb = {'CO2': 0.03999, 'H2O': 0.00001, 'CH4': 0.96}
    #perturbInputs(flowsheet,0,Solid_M=691.4,Solid_T=1283,Solid_x=solid_x_ptb,
    #        Gas_F=150,Gas_T=350,Gas_y=gas_y_ptb)
    for t in mb.t:
        perturbInputs(flowsheet, t, Solid_M=691.4)

    # should put this in a dedicated ~intialize~ function
    # that also intelligently initializes the model after perturbation
    mb.eq_d4.deactivate()
    mb.eq_d5.deactivate()
    mb.eq_d8.deactivate()
    mb.eq_d9.deactivate()
    mb.eq_d10.deactivate()
    mb.eq_g7.deactivate()
    mb.eq_g8.deactivate()
    mb.eq_g10.deactivate()
    mb.eq_g11.deactivate()
    mb.eq_g12.deactivate()
    mb.eq_g13.deactivate()
    mb.eq_g14.deactivate()
    mb.eq_g4.deactivate()
    mb.eq_g5.deactivate()
    mb.eq_g2.deactivate()
    mb.Tg_GW.fix(0.0)
    mb.Tw_GW.fix(0.0)
    mb.Tg_refractory.fix(0.0)
    mb.Tw_Wamb.fix()
    mb.Tw.fix()
    mb.Nuw.fix()
    mb.Nu_ext.fix()
    mb.hw.fix()
    mb.hext.fix()
    mb.hext2.fix()
    mb.U.fix()
    mb.Uw.fix()
    mb.Pr_ext.fix()
    mb.Ra.fix()
    mb.Re.fix()
    ###

    # other tentatively unused variables:
    mb.mFe_mAl.fix(0.0)
    mb.Solid_Out_M_Comp.fix()

    for z in mb.z:
        mb.dldz[z].fix()
        mb.l[z].fix()
    mb.dldz_disc_eq.deactivate()
    mb.eq_a1.deactivate()

    mb.eq_c5.deactivate()

    # initialized at steady state, works regardless:
    flowsheet.strip_bounds()

    #for z in mb.z:
    #    for t in mb.t:
    #        mb.Cg[z,'CH4',t].setlb(1e-8)

    diff_vars = [mb.Cg.name, mb.q.name, mb.Tg.name, mb.Ts.name]
    time_derivatives = [
        mb.dCgdt.name, mb.dqdt.name, mb.dTgdt.name, mb.dTsdt.name
    ]
    inputs = [
        mb.Gas_In_F.name, mb.Gas_In_y.name, mb.Solid_In_M.name,
        mb.Solid_In_x.name, mb.Gas_In_Tg.name, mb.Solid_In_Ts.name,
        mb.Gas_In_P.name
    ]
    disturbances = []
    # ^ appears there are no disturbance variables (Ta is not a variable)
    geometry = [mb.l.name, mb.L.name, mb.Dr.name, mb.A_bed.name, mb.eps.name]
    # ^ will be fixed; really should not even be variables (should be parameters), but w/e
    #   (are these the only variables that aren't indexed by time?)

    alg_vars = find_algebraic_variables(flowsheet, diff_vars, time_derivatives,
                                        inputs, disturbances, geometry)
    for var in alg_vars:
        print(var.name)

    for t in mb.t:
        fix_inlet_conditions(flowsheet, t)

    fix_z0(flowsheet)
    alg_var_data = get_alg_var_data(alg_vars)
    print('Generating map')
    avc_map = make_alg_var_const_map(flowsheet)
    print('\nNot in avc_map:')
    for var in alg_var_data:
        if var.name not in avc_map:
            print(var)
    print('- - -')

    for var in alg_var_data:
        var.fix()
        if not avc_map[var.name].active:
            print(avc_map[var.name].name, 'already deactivated')
        avc_map[var.name].deactivate()

    tol = 1e-8
    opt = SolverFactory('ipopt')
    opt.options = {
        'tol': tol,
        'linear_solver': 'ma57',
        'bound_push': 1e-8,
        'max_cpu_time': 600,
        'print_level': 5,
        'output_file': 'ipopt_out.txt',
        'linear_system_scaling': 'mc19',
        'linear_scaling_on_demand': 'no',
        'halt_on_ampl_error': 'yes'
    }
    flowsheet.write('sm_init.nl')

    with open('sm_init.txt', 'w') as f:
        flowsheet.display(ostream=f)

    print_violated_constraints(flowsheet)

    results = opt.solve(flowsheet,
                        tee=True,
                        symbolic_solver_labels=False,
                        keepfiles=False)

    ### unfix z-derivatives ###
    for index in mb.dG_fluxdz_disc_eq:
        mb.dG_fluxdz[index].unfix()
        mb.dG_fluxdz_disc_eq[index].activate()
    for index in mb.dS_fluxdz_disc_eq:
        mb.dS_fluxdz[index].unfix()
        mb.dS_fluxdz_disc_eq[index].activate()
    for index in mb.dGh_fluxdz_disc_eq:
        mb.dGh_fluxdz[index].unfix()
        mb.dGh_fluxdz_disc_eq[index].activate()
    for index in mb.dSh_fluxdz_disc_eq:
        mb.dSh_fluxdz[index].unfix()
        mb.dSh_fluxdz_disc_eq[index].activate()

    for index in mb.S_flux:
        mb.S_flux[index].unfix()
        avc_map[mb.S_flux[index].name].activate()

    print_violated_constraints(flowsheet)

    results = opt.solve(flowsheet,
                        tee=True,
                        symbolic_solver_labels=False,
                        keepfiles=False)
    # ^ this converges (quickly) to an infeasible point

    print_violated_constraints(flowsheet)

    with open('sm_sol.txt', 'w') as f:
        flowsheet.display(ostream=f)

    return flowsheet
    def initialize(blk,
                   state_args={},
                   state_vars_fixed=False,
                   hold_state=False,
                   outlvl=1,
                   solver='ipopt',
                   optarg={'tol': 1e-8}):
        """
        Initialization routine for property package.
        Keyword Arguments:
            state_args : Dictionary with initial guesses for the state vars
                         chosen. Note that if this method is triggered
                         through the control volume, and if initial guesses
                         were not provied at the unit model level, the
                         control volume passes the inlet values as initial
                         guess.The keys for the state_args dictionary are:

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

        _log.info('Starting {} initialization'.format(blk.name))

        # Fix state variables if not already fixed
        if state_vars_fixed is False:
            flags = fix_state_vars(blk, state_args)

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

        if optarg is None:
            sopt = {'tol': 1e-8}
        else:
            sopt = optarg

        opt = SolverFactory('ipopt')
        opt.options = sopt
        # ---------------------------------------------------------------------
        # Initialize flow rates and compositions

        free_vars = 0
        for k in blk.keys():
            free_vars += number_unfixed_variables(blk[k])
        if free_vars > 0:
            try:
                results = solve_indexed_blocks(opt, [blk], tee=stee)
            except:
                results = None
        else:
            results = None

        if outlvl > 0:
            if results is None or results.solver.termination_condition \
                    == TerminationCondition.optimal:
                _log.info("Property initialization for "
                          "{} completed".format(blk.name))
            else:
                _log.warning("Property initialization for "
                             "{} failed".format(blk.name))

        # ---------------------------------------------------------------------
        # Return state to initial conditions
        if state_vars_fixed is False:
            if hold_state is True:
                return flags
            else:
                blk.release_state(flags)

        if outlvl > 0:
            _log.info("Initialization completed for {}".format(blk.name))
예제 #13
0
def main():
    """
    Make the flowsheet object and solve
    """
    ss_flowsheet = ss_sim.main()
    flowsheet = Flowsheet(name='MB_Model')

    # fill in values of IC parameters from steady state solve
    setICs(flowsheet, ss_flowsheet)

    # Fix variables
    setInputs(flowsheet)

    # Initialize at steady state
    initialize_ss(flowsheet, ss_flowsheet)

    mb = flowsheet.MB_fuel

    # Then perturb
    # ^ that function should go in this file, probably
    # input: dict mapping state names (strings) to new values

    # this seems like as much work as doing the perturbation...
    # maybe just make a self contained function
    #input_perturbation = { ('Solid_In_x',mb.t) : { ['Fe2O3'] : 0.25 },
    #                       ('Solid_In_x',mb.t) : { ['Al2O3'] : 0.75 } }

    perturbInputs(flowsheet)

    # perturb states

    # should put this in a dedicated ~intialize~ function
    # that also intelligently initializes the model after perturbation
    mb.eq_d4.deactivate()
    mb.eq_d5.deactivate()
    mb.eq_d8.deactivate()
    mb.eq_d9.deactivate()
    mb.eq_d10.deactivate()
    mb.eq_g7.deactivate()
    mb.eq_g8.deactivate()
    mb.eq_g10.deactivate()
    mb.eq_g11.deactivate()
    mb.eq_g12.deactivate()
    mb.eq_g13.deactivate()
    mb.eq_g14.deactivate()
    mb.eq_g4.deactivate()
    mb.eq_g5.deactivate()
    mb.eq_g2.deactivate()
    mb.Tg_GW.fix(0.0)
    mb.Tg_refractory.fix(0.0)
    mb.Tw_Wamb.fix()
    mb.Tw.fix()
    mb.Nuw.fix()
    mb.Nu_ext.fix()
    mb.hw.fix()
    mb.hext.fix()
    mb.hext2.fix()
    mb.U.fix()
    mb.Uw.fix()
    mb.Pr_ext.fix()
    mb.Ra.fix()
    mb.Re.fix()
    ###
    '''
    ts = time.time() 
    # Initialize fuel reactor
    flowsheet.MB_fuel._initialize(outlvl=1,
                              optarg={"tol"            : 1e-8,
                                      "max_cpu_time"   : 600,
                                      "print_level"    : 5,
                                      "halt_on_ampl_error": 'yes'})        
    '''

    # Create a solver
    opt = SolverFactory('ipopt')
    opt.options = {
        'tol': 1e-8,
        'linear_solver': 'ma27',
        'bound_push': 1e-8,
        'max_cpu_time': 600,
        'print_level': 5,
        'halt_on_ampl_error': 'yes'
    }
    flowsheet.write('fs.nl')

    with open('dyn_fs.txt', 'w') as f:
        flowsheet.display(ostream=f)

    print('Constraints violated pre-solve:')
    for const in flowsheet.MB_fuel.component_objects(Constraint, active=True):
        if not isinstance(const, SimpleConstraint):
            for idx in const:
                if (value(const[idx].body) > value(const[idx].upper) + 1.0e-7) or \
                        (value(const[idx].body) < value(const[idx].lower) - 1.0e-7):
                    print(const.name, idx)
        else:
            if (value(const.body) > value(const.upper) + 1.0e-7) or \
                    (value(const.body) < value(const.lower) - 1.0e-7):
                print(const.name)
    print('- - -\n')

    print('Variable bounds violated pre-solve:')
    for var in flowsheet.MB_fuel.component_objects(Var, active=True):
        # don't use IndexedComponent here, variables are always indexed components
        # could also do this by iterating over component_objects(SimpleVar)...?
        if not isinstance(var, SimpleVar):
            for idx in var:
                if not (var[idx].lb is None):
                    if (var[idx].value < var[idx].lb - 1.0e-7):
                        pdb.set_trace()
                        print(var.name, idx)
                if not (var[idx].ub is None):
                    if (var[idx].value > var[idx].ub + 1.0e-7):
                        pdb.set_trace()
                        print(var.name, idx)
        else:
            if (var.value > var.ub + 1.0e-7) or \
                    (var.value < var.lb - 1.0e-7):
                print(var.name)
    print('- - -\n')

    # initialized at steady state, works regardless:
    flowsheet.strip_bounds()

    for z in mb.z:
        for t in mb.t:
            mb.Cg[z, 'CH4', t].setlb(1e-6)

    # want a function to integrate the model one step from a specified time point
    # will call for all t
    integrate(flowsheet, 0)

    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #with open('dyn_fs_sol.txt','w') as f:
    #    flowsheet.display(ostream=f)
    '''
    
    print("\n")
    print("----------------------------------------------------------")
    print('Total simulation time: ', value(time.time() - ts), " s")
    print("----------------------------------------------------------")

    
    # Print some variables 
    print_summary_fuel_reactor(flowsheet) 

    # Plot some variables 
    #results_plot_fuel_reactor(flowsheet) 

    #with open('m_fs.txt','w') as f:
    #    flowsheet.display(ostream=f)

    # Store the flowsheet    
    '''
    return flowsheet
예제 #14
0
    def initialize(blk,
                   flow_mol=None,
                   temperature=None,
                   pressure=None,
                   vapor_frac=None,
                   outlvl=0,
                   hold_state=False,
                   state_vars_fixed=False,
                   solver='ipopt',
                   optarg={'tol': 1e-8}):
        """
        Declare initialisation routine.

        Keyword Arguments:
            state_args = to be used if state block initialized independent of
                         control volume initialize
            outlvl : sets output level of initialisation routine

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

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

        Returns:
            If hold_states is True, returns a dict containing flags for
            which states were fixed during initialization.
        """
        # Fix state variables if not already fixed by the control volume block
        if state_vars_fixed is False:
            Fflag = {}
            Pflag = {}
            Tflag = {}
            vfflag = {}

            for k in blk.keys():
                if blk[k].flow_mol.fixed is True:
                    Fflag[k] = True
                else:
                    Fflag[k] = False
                    if flow_mol is None:
                        blk[k].flow_mol.fix(1.0)
                    else:
                        blk[k].flow_mol.fix(flow_mol)
                if blk[k].pressure.fixed is True:
                    Pflag[k] = True
                else:
                    Pflag[k] = False
                    if pressure is None:
                        blk[k].pressure.fix(101325.0)
                    else:
                        blk[k].pressure.fix(pressure)

                if blk[k].temperature.fixed is True:
                    Tflag[k] = True
                else:
                    Tflag[k] = False
                    if temperature is None:
                        blk[k].temperature.fix(300.0)
                    else:
                        blk[k].temperature.fix(temperature)

                if blk[k].vapor_frac.fixed is True:
                    vfflag[k] = True
                else:
                    vfflag[k] = False
                    if vapor_frac is None:
                        blk[k].vapor_frac.fix(300.0)
                    else:
                        blk[k].vapor_frac.fix(temperature)

            flags = {
                "Fflag": Fflag,
                "Pflag": Pflag,
                "Tflag": Tflag,
                "vfflag": vfflag
            }

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

        # Set solver options
        if outlvl > 1:
            stee = True
        else:
            stee = False

        opt = SolverFactory(solver)
        opt.options = optarg

        # ---------------------------------------------------------------------
        # Solve property correlation
        results = solve_indexed_blocks(opt, [blk], tee=stee)

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

        # ---------------------------------------------------------------------
        if state_vars_fixed is False:
            # release state vars fixed during initialization if control
            # volume didn't fix the state vars
            if hold_state is True:
                return flags
            else:
                blk.release_state(flags)

        if outlvl > 0:
            if outlvl > 0:
                _log.info('{} Initialisation Complete.'.format(blk.name))
예제 #15
0
    def initialize(blk,
                   outlvl=idaeslog.NOTSET,
                   optarg={'tol': 1e-8},
                   solver='ipopt'):
        '''
        Initialisation routine for reaction package.

        Keyword Arguments:
            outlvl : sets output level of initialization routine
                 * 0 = Use default idaes.init logger setting
                 * 1 = Maximum output
                 * 2 = Include solver output
                 * 3 = Return solver state for each step in subroutines
                 * 4 = Return solver state for each step in routine
                 * 5 = Final initialization status and exceptions
                 * 6 = No output
            optarg : solver options dictionary object (default=None)
            solver : str indicating whcih solver to use during
                     initialization (default = "ipopt")
        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)

        # Set solver options
        opt = SolverFactory(solver)
        opt.options = 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.')
예제 #16
0
    def _generate_cuttingplanes( self, instance_rBigM, cuts_obj, instance_rHull,
                                 var_info, transBlockName):

        opt = SolverFactory(self._config.solver)
        stream_solver = self._config.stream_solver
        opt.options = dict(self._config.solver_options)

        improving = True
        prev_obj = None
        epsilon = self._config.minimum_improvement_threshold
        cuts = None

        transBlock_rHull = instance_rHull.component(transBlockName)

        rBigM_obj, rBigM_linear_constraints = self.\
                                              _get_rBigM_obj_and_constraints(
                                                  instance_rBigM)

        # Get list of all variables in the rHull model which we will use when
        # calculating the composite normal vector.
        rHull_vars = [i for i in instance_rHull.component_data_objects(
            Var,
            descend_into=Block,
            sort=SortComponents.deterministic)]

        # collect a list of disaggregated variables.
        disaggregated_vars = self._get_disaggregated_vars( instance_rHull)

        hull_to_bigm_map = self._create_hull_to_bigm_substitution_map(var_info)
        bigm_to_hull_map = self._create_bigm_to_hull_substition_map(var_info)

        while (improving):
            # solve rBigM, solution is xstar
            results = opt.solve(instance_rBigM, tee=stream_solver)
            if verify_successful_solve(results) is not NORMAL:
                logger.warning("Relaxed BigM subproblem "
                               "did not solve normally. Stopping cutting "
                               "plane generation.\n\n%s" % (results,))
                return

            rBigM_objVal = value(rBigM_obj)
            logger.warning("rBigM objective = %s" % (rBigM_objVal,))

            #
            # Add the separation objective to the hull subproblem if it's not
            # there already (so in the first iteration). We're waiting until now
            # to avoid it including variables that came back stale from the
            # rbigm solve.
            #
            if transBlock_rHull.component("separation_objective") is None:
                self._add_separation_objective(var_info, transBlock_rHull)
            
            # copy over xstar
            logger.info("x* is:")
            for x_rbigm, x_hull, x_star in var_info:
                if not x_rbigm.stale:
                    x_star.value = x_rbigm.value
                    # initialize the X values
                    x_hull.value = x_rbigm.value    
                if self.verbose:
                    logger.info("\t%s = %s" % 
                                (x_rbigm.getname(fully_qualified=True,
                                                 name_buffer=NAME_BUFFER),
                                 x_rbigm.value))

            # compare objectives: check absolute difference close to 0, relative
            # difference further from 0.
            if prev_obj is None:
                improving = True
            else:
                obj_diff = prev_obj - rBigM_objVal
                improving = ( abs(obj_diff) > epsilon if abs(rBigM_objVal) < 1
                             else abs(obj_diff/prev_obj) > epsilon )

            # solve separation problem to get xhat.
            opt.solve(instance_rHull, tee=stream_solver)
            if verify_successful_solve(results) is not NORMAL:
                logger.warning("Hull separation subproblem "
                               "did not solve normally. Stopping cutting "
                               "plane generation.\n\n%s" % (results,))
                return
            logger.warning("separation problem objective value: %s" %
                           value(transBlock_rHull.separation_objective))
            if self.verbose:
                logger.info("xhat is: ")
                for x_rbigm, x_hull, x_star in var_info:
                    logger.info("\t%s = %s" % 
                                (x_hull.getname(fully_qualified=True,
                                                name_buffer=NAME_BUFFER), 
                                 x_hull.value))

            # [JDS 19 Dec 18] Note: we check that the separation objective was
            # significantly nonzero.  If it is too close to zero, either the
            # rBigM solution was in the convex hull, or the separation vector is
            # so close to zero that the resulting cut is likely to have
            # numerical issues.
            if value(transBlock_rHull.separation_objective) < \
               self._config.separation_objective_threhold:
                break

            cuts = self._config.create_cuts(transBlock_rHull, var_info,
                                            hull_to_bigm_map,
                                            rBigM_linear_constraints,
                                            rHull_vars, disaggregated_vars,
                                            self._config.norm,
                                            self._config.cut_filtering_threshold,
                                            self._config.zero_tolerance,
                                            self._config.do_integer_arithmetic)
           
            # We are done if the cut generator couldn't return a valid cut
            if cuts is None or not improving:
                break

            for cut in cuts:
                # we add the cut to the model and then post-process it in place.
                cut_number = len(cuts_obj)
                logger.warning("Adding cut %s to BigM model." % (cut_number,))
                cuts_obj.add(cut_number, cut)
                if self._config.post_process_cut is not None:
                    self._config.post_process_cut(
                        cuts_obj[cut_number], transBlock_rHull,
                        bigm_to_hull_map, opt, stream_solver,
                        self._config.back_off_problem_tolerance)

            if cut_number + 1 == self._config.max_number_of_cuts:
                logger.warning("Reached maximum number of cuts.")
                break
                
            prev_obj = rBigM_objVal
예제 #17
0
    def initialize(blk,
                   state_args={},
                   state_vars_fixed=False,
                   hold_state=False,
                   outlvl=0,
                   solver='ipopt',
                   optarg={'tol': 1e-8}):
        '''
        Initialisation routine for property package.

        Keyword Arguments:
        state_args : Dictionary with initial guesses for the state vars
                     chosen. Note that if this method is triggered
                     through the control volume, and if initial guesses
                     were not provied at the unit model level, the
                     control volume passes the inlet values as initial
                     guess.The keys for the state_args dictionary are:

                     flow_mol_comp : value at which to initialize component
                                     flows (default=None)
                     pressure : value at which to initialize pressure
                                (default=None)
                     temperature : value at which to initialize temperature
                                  (default=None)
            outlvl : sets output level of initialisation routine

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

        Returns:
            If hold_states is True, returns a dict containing flags for
            which states were fixed during initialization.
        '''
        # Deactivate the constraints specific for outlet block i.e.
        # when defined state is False
        for k in blk.keys():
            if blk[k].config.defined_state is False:
                blk[k].conc_water_eqn.deactivate()

        if state_vars_fixed is False:
            # Fix state variables if not already fixed
            flags = fix_state_vars(blk, state_args)

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

        opt = SolverFactory(solver)
        opt.options = optarg

        # Post initialization reactivate constraints specific for
        # all blocks other than the inlet
        for k in blk.keys():
            if not blk[k].config.defined_state:
                blk[k].conc_water_eqn.activate()

        if state_vars_fixed is False:
            if hold_state is True:
                return flags
            else:
                blk.release_state(flags)

        if outlvl > 0:
            if outlvl > 0:
                _log.info('{} Initialisation Complete.'.format(blk.name))
예제 #18
0
    def initialize(
            self,
            state_args={
                "flow_mol_comp": {
                    "N2": 1.0,
                    "CO2": 1.0,
                    "NO": 1.0,
                    "O2": 1.0,
                    "H2O": 1.0,
                    "SO2": 1.0
                },
                "pressure": 1e5,
                "temperature": 495.0
            },
            hold_state=False,
            state_vars_fixed=False,
            outlvl=0,
            solver='ipopt',
            optarg={'tol': 1e-8}):
        """Initialisation routine for property package.

        Key values for the state_args dict:
            flow_mol_comp : value at which to initialize component flows
                (default=27.5e3 mol/s)
            pressure : value at which to initialize pressure (default=2.97e7 Pa)
            temperature : value at which to initialize temperature
                (default=866.5 K)

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

            Returns:
                If hold_states is True, returns a dict containing flags for
                which states were fixed during initialization.
        """
        init_log = idaeslog.getInitLogger(self.name, outlvl, tag="properties")
        solve_log = idaeslog.getSolveLogger(self.name,
                                            outlvl,
                                            tag="properties")

        opt = SolverFactory(solver)
        opt.options = optarg

        if state_vars_fixed is False:
            flags = fix_state_vars(self, state_args)
        # Check when the state vars are fixed already result in dof 0
        for b in self.values():
            if degrees_of_freedom(b) != 0:
                raise Exception(f"{self.name} initializtion error: State vars "
                                "fixed but degrees of freedom not equal to 0")
        # ---------------------------------------------------------------------
        # Solve 1st stage
        for k, b in self.items():
            if b.is_property_constructed("pressure_sat"):
                b.pressure_sat.value = value(
                    exp(b.vapor_pressure_coeff[1] +
                        b.vapor_pressure_coeff[2] / b.temperature +
                        b.vapor_pressure_coeff[3] * blk.temperature +
                        b.vapor_pressure_coeff[4] * log(blk.temperature) +
                        b.vapor_pressure_coeff[5].value * blk.temperature**2))

            deactivate_list = []
            if hasattr(b, 'enthalpy_correlation'):
                deactivate_list.append(b.enthalpy_correlation)
            if hasattr(b, "volumetric_flow_calculation"):
                deactivate_list.append(b.volumetric_flow_calculation)
            if hasattr(b, "entropy_correlation"):
                deactivate_list.append(b.entropy_correlation)
            for c in deactivate_list:
                c.deactivate()

            if number_activated_constraints(b) > 0:
                with idaeslog.solver_log(solve_log, idaeslog.DEBUG) as slc:
                    res = opt.solve(b, tee=slc.tee)
            else:
                res = "skipped"
            init_log.info_high("Initialization Step 1 {}.".format(
                idaeslog.condition(res)))

            for c in deactivate_list:
                c.activate()

            if number_activated_constraints(b) > 0:
                with idaeslog.solver_log(solve_log, idaeslog.DEBUG) as slc:
                    res = opt.solve(b, tee=slc.tee)
            else:
                res = "skipped"
            init_log.info_high("Initialization Step 2 {}.".format(
                idaeslog.condition(res)))

        init_log.info('Initialisation Complete, {}.'.format(
            idaeslog.condition(res)))
        # ---------------------------------------------------------------------
        # If input block, return flags, else release state
        if state_vars_fixed is False:
            if hold_state is True:
                return flags
            else:
                self.release_state(flags)
    def initialize(blk,
                   flow_mol=None,
                   mole_frac=None,
                   temperature=None,
                   pressure=None,
                   hold_state=False,
                   outlvl=0,
                   solver='ipopt',
                   optarg={'tol': 1e-8}):
        """
        Initialisation routine for property package.

        Keyword Arguments:
            flow_mol_comp : value at which to initialize component flows
                             (default=None)
            pressure : value at which to initialize pressure (default=None)
            temperature : value at which to initialize temperature
                          (default=None)
            outlvl : sets output level of initialisation routine

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

            optarg : solver options dictionary object (default=None)
            solver : str indicating whcih solver to use during
                     initialization (default = 'ipopt')
            hold_state : flag indicating whether the initialization routine
                         should unfix any state variables fixed during
                         initialization (default=False).
                         - True - states varaibles are not unfixed, and
                                 a dict of returned containing flags for
                                 which states were fixed during
                                 initialization.
                        - False - state variables are unfixed after
                                 initialization by calling the
                                 relase_state method

        Returns:
            If hold_states is True, returns a dict containing flags for
            which states were fixed during initialization.
        """
        # Fix state variables if not already fixed
        Fflag = {}
        Xflag = {}
        Pflag = {}
        Tflag = {}

        for k in blk.keys():
            if blk[k].flow_mol.fixed is True:
                Fflag[k] = True
            else:
                Fflag[k] = False
                if flow_mol is None:
                    blk[k].flow_mol.fix(1.0)
                else:
                    blk[k].flow_mol.fix(flow_mol)

            for j in blk[k]._params.component_list:
                if blk[k].mole_frac[j].fixed is True:
                    Xflag[k, j] = True
                else:
                    Xflag[k, j] = False
                    if mole_frac is None:
                        blk[k].mole_frac[j].fix(
                            1 / len(blk[k]._params.component_list))
                    else:
                        blk[k].mole_frac[j].fix(mole_frac[j])

            if blk[k].pressure.fixed is True:
                Pflag[k] = True
            else:
                Pflag[k] = False
                if pressure is None:
                    blk[k].pressure.fix(0.101325)
                else:
                    blk[k].pressure.fix(pressure)

            if blk[k].temperature.fixed is True:
                Tflag[k] = True
            else:
                Tflag[k] = False
                if temperature is None:
                    blk[k].temperature.fix(3.25)
                else:
                    blk[k].temperature.fix(temperature)

        # Set solver options
        if outlvl > 1:
            stee = True
        else:
            stee = False

        if optarg is None:
            sopt = {'tol': 1e-8}
        else:
            sopt = optarg

        opt = SolverFactory('ipopt')
        opt.options = sopt

        # ---------------------------------------------------------------------
        for k in blk.keys():

            blk[k].eq_total.deactivate()
            blk[k].eq_comp.deactivate()
            if (blk[k].config.defined_state is False):
                blk[k].eq_mol_frac_out.deactivate()
            if (blk[k].config.has_phase_equilibrium) or \
                    (blk[k].config.parameters.config.valid_phase ==
                        ('Liq', 'Vap')) or \
                    (blk[k].config.parameters.config.valid_phase ==
                        ('Vap', 'Liq')):
                blk[k].eq_Keq.deactivate()
                blk[k].eq_sum_mol_frac.deactivate()

        if (blk[k].config.has_phase_equilibrium) or \
                (blk[k].config.parameters.config.valid_phase ==
                    ('Liq', 'Vap')) or \
                (blk[k].config.parameters.config.valid_phase ==
                    ('Vap', 'Liq')):
            results = solve_indexed_blocks(opt, [blk], tee=stee)

            if outlvl > 0:
                if results.solver.termination_condition \
                        == TerminationCondition.optimal:
                    _log.info("Initialisation step 1 for "
                              "{} completed".format(blk.name))
                else:
                    _log.warning("Initialisation step 1 for "
                                 "{} failed".format(blk.name))

        else:
            if outlvl > 0:
                _log.info("Initialisation step 1 for "
                          "{} skipped".format(blk.name))

        for k in blk.keys():
            blk[k].eq_total.activate()
            blk[k].eq_comp.activate()
            if (blk[k].config.has_phase_equilibrium) or \
                    (blk[k].config.parameters.config.valid_phase ==
                        ('Liq', 'Vap')) or \
                    (blk[k].config.parameters.config.valid_phase ==
                        ('Vap', 'Liq')):
                blk[k].eq_Keq.activate()
                blk[k].eq_sum_mol_frac.activate()

        results = solve_indexed_blocks(opt, [blk], tee=stee)

        if outlvl > 0:
            if results.solver.termination_condition \
                    == TerminationCondition.optimal:
                _log.info("Initialisation step 2 for "
                          "{} completed".format(blk.name))
            else:
                _log.warning("Initialisation step 2 for "
                             "{} failed".format(blk.name))

        for k in blk.keys():
            if (blk[k].config.defined_state is False):
                blk[k].eq_mol_frac_out.activate()
        # ---------------------------------------------------------------------
        # If input block, return flags, else release state
        flags = {
            "Fflag": Fflag,
            "Xflag": Xflag,
            "Pflag": Pflag,
            "Tflag": Tflag
        }

        if hold_state is True:
            return flags
        else:
            blk.release_state(flags)

        if outlvl > 0:
            if outlvl > 0:
                _log.info('{} Initialisation Complete.'.format(blk.name))
예제 #20
0
def main():
    """
    Make the flowsheet object and solve
    """
    ss_flowsheet = ss_sim.main()

    flowsheet = Flowsheet(name='MB_Model') 

    # fill in values of IC parameters from steady state solve
    setICs(flowsheet,ss_flowsheet)
    
    # Fix variables
    setInputs(flowsheet) 

    # Initialize at steady state
    initialize_ss(flowsheet,ss_flowsheet)
    mb = flowsheet.MB_fuel

    #write_differential_equations(flowsheet)

    # Then perturb
    ptb = {}
    solid_x_ptb = {'Fe2O3':0.25, 'Fe3O4':0.01, 'Al2O3':0.74}
    gas_y_ptb = {'CO2':0.04999, 'H2O':0.00001, 'CH4':0.95}
    #perturbInputs(flowsheet,0,Solid_M=691.4,Solid_T=1283.15,Solid_x=solid_x_ptb,
    #        Gas_F=150,Gas_T=350,Gas_y=gas_y_ptb)
    for t in mb.t:
        ptb_inputs(flowsheet, t, Gas_T=350)

    # should put this in a dedicated ~intialize~ function
    # that also intelligently initializes the model after perturbation
    mb.eq_d4.deactivate()
    mb.eq_d5.deactivate()
    mb.eq_d8.deactivate()
    mb.eq_d9.deactivate()
    mb.eq_d10.deactivate()
    mb.eq_g7.deactivate()
    mb.eq_g8.deactivate()
    mb.eq_g10.deactivate()
    mb.eq_g11.deactivate()
    mb.eq_g12.deactivate()
    mb.eq_g13.deactivate()
    mb.eq_g14.deactivate()
    mb.eq_g4.deactivate()
    mb.eq_g5.deactivate()
    mb.eq_g2.deactivate()
    mb.Tg_GW.fix(0.0)
    mb.Tw_GW.fix(0.0)
    mb.Tg_refractory.fix(0.0)
    mb.Tw_Wamb.fix()
    mb.Tw.fix()
    mb.Nuw.fix()
    mb.Nu_ext.fix()
    mb.hw.fix()
    mb.hext.fix()
    mb.hext2.fix()
    mb.U.fix()
    mb.Uw.fix()
    mb.Pr_ext.fix()
    mb.Ra.fix()
    mb.Re.fix()
    ###

    # other tentatively unused variables:
    mb.mFe_mAl.fix(0.0)
    mb.Solid_Out_M_Comp.fix()

    # choose how to calculate certain algebraic variables:
    mb.eq_c5.deactivate()

    with open('dyn_fs_init.txt','w') as f:
        flowsheet.display(ostream=f)

    # Create a solver
    tol = 1e-8
    opt = SolverFactory('ipopt')
    opt.options = {'tol': tol,
                   'linear_solver' : 'ma57',
                   'bound_push': 1e-8,
                   'max_cpu_time': 600,
                   'print_level': 5,
                   'output_file': 'ipopt_out.txt',
                   'linear_system_scaling': 'mc19',
                   'linear_scaling_on_demand' : 'no',
                   'halt_on_ampl_error': 'yes'}
    flowsheet.write('fs_dyn.nl')

    # initialized at steady state, works regardless:
    flowsheet.strip_bounds()

    print_violated_constraints(flowsheet,tol)

    fs_list = clc_integrate(mb)
    for t in fs_list:
        load_fe(fs_list[t], flowsheet, t)
    

    #for z in mb.z:
    #    for t in mb.t:
    #        mb.Cg[z,'CH4',t].setlb(1e-8)

    #for t in mb.t:
    #    alg_update(flowsheet,t)
    #    update_time_derivatives(flowsheet,t)

    with open('dyn_fs_init.txt','w') as f:
        flowsheet.display(ostream=f)

    print_violated_constraints(flowsheet,tol)

    #mb.input_objective = Objective(expr=sum((mb.Solid_In_M[t] -601.4)**2 for t in mb.t))


    #mb.cont_param.set_value(0)
    #mb.dCgdt_disc_eq.deactivate()
    #for index in mb.dCgdt: mb.dCgdt[index].fix(0)
    #mb.dqdt_disc_eq.deactivate()
    #for index in mb.dqdt: mb.dqdt[index].fix(0)
    #mb.dTsdt_disc_eq.deactivate()
    #for index in mb.dTsdt: mb.dTsdt[index].fix(0)
    #mb.dTgdt_disc_eq.deactivate()
    #for index in mb.dTgdt: mb.dTgdt[index].fix(0)
    #mb.eq_h1.deactivate()
    #mb.eq_h2.deactivate()
    #mb.eq_h3.deactivate()
    #mb.eq_h4.deactivate()
    #flowsheet.write('fs_dyn.nl')

    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #mb.dCgdt_disc_eq.activate()
    #for index in mb.dCgdt: mb.dCgdt[index].unfix()
    #mb.dqdt_disc_eq.activate()
    #for index in mb.dqdt: mb.dqdt[index].unfix()
    #mb.dTsdt_disc_eq.activate()
    #for index in mb.dTsdt: mb.dTsdt[index].unfix()
    #mb.dTgdt_disc_eq.activate()
    #for index in mb.dTsdt: mb.dTgdt[index].unfix()
    #mb.eq_h1.activate()
    #mb.eq_h2.activate()
    #mb.eq_h3.activate()
    #mb.eq_h4.activate()

    #print_violated_constraints(flowsheet,t)

    #print('\n-----------------')
    #print('#\epsilon = 1e-5#')
    #print('-----------------\n')
    #mb.cont_param.set_value(1e-5)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 1e-4#')
    #print('-----------------\n')
    #mb.cont_param.set_value(1e-4)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 1e-3#')
    #print('-----------------\n')
    #mb.cont_param.set_value(1e-3)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 1e-2#')
    #print('-----------------\n')
    #mb.cont_param.set_value(1e-2)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 2e-2#')
    #print('-----------------\n')
    #mb.cont_param.set_value(2e-2)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 5e-2#')
    #print('-----------------\n')
    #mb.cont_param.set_value(5e-2)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 8e-2#')
    #print('-----------------\n')
    #mb.cont_param.set_value(5e-2)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 1e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(1e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 2e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(2e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 4e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(4e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #
    #print('\n-----------------')
    #print('#\epsilon = 5e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(5e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 6e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(6e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 7e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(7e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 7.5e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(7.5e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 8e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(8e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #
    #print('\n-----------------')
    #print('#\epsilon = 8.5e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(8.5e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 8.8e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(8.8e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.1e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.1e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.2e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.2e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.3e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.3e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.4e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.4e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.5e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.5e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.6e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.6e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.7e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.7e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.8e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.8e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    #print('\n-----------------')
    #print('#\epsilon = 9.9e-1#')
    #print('-----------------\n')
    #mb.cont_param.set_value(9.9e-1)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)
    #results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
    #                        keepfiles=False)

    print('\n-----------------')
    print('#\epsilon = 1#')
    print('-----------------\n')
    mb.cont_param.set_value(1)
    results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
                            keepfiles=False)
    results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
                            keepfiles=False)

    
    print_violated_constraints(flowsheet,tol)

    diff_vars = [mb.Cg, mb.q, mb.Tg, mb.Ts]

    write_results(flowsheet, 'gas_T.csv', diff_vars)

    #wd = os.getcwd()
    #
    #if not os.path.isdir(wd+'/results'):
    #    os.mkdir(wd+'/results')
    #else:
    #    print('results directory already exists')

    #with open('results/solid_m.csv', 'w', newline='') as f:
    #    writer = csv.writer(f, delimiter=',')
    #    row0 = []
    #    row0.append('name')
    #    # should really do this systematically, finding some 'max no. indices'
    #    max_n_idx = 3
    #    row0.append('idx1')
    #    row0.append('idx2')
    #    for t in mb.t:
    #        row0.append(str(t))
    #    writer.writerow(row0)

    #    for v in diff_vars:
    #        name = v.getname()
    #        if isinstance(v,SimpleVar):
    #            continue
    #        n_idx = v.index_set().dimen
    #        print(v.index_set().set_tuple)
    #        if mb.t not in v.index_set().set_tuple:
    #            continue
    #        idx_list = []
    #        if v.index_set() == mb.t:
    #            row = []
    #            row.append(name)
    #            idx_list.append('')
    #            idx_list.append('')
    #            for idx in idx_list:
    #                row.append(idx)
    #            for t in mb.t:
    #               row.append(v[t].value)
    #            writer.writerow(row)
    #            continue

    #        elif n_idx >= 2:
    #            if v.index_set().set_tuple[0] != mb.t:
    #                product = v.index_set().set_tuple[0]
    #            else:
    #                raise ValueError('Inconsistency, fix code')
    #            # now product is a generator:
    #            # either a set or a set product

    #            for s in v.index_set().set_tuple:
    #                if s != mb.t and s != product:
    #                    product = product *s
    #            #for index in product:
    #            #    print(index)

    #            for index in product:
    #                # index is either a hashable value or a tuple
    #                row = [] 
    #                row.append(name)
    #                if isinstance(index,tuple):
    #                    for i in range(0,max_n_idx-1):
    #                        try:
    #                            row.append(index[i])
    #                        except IndexError:
    #                            row.append('')
    #                else:
    #                    row.append(index)
    #                    for i in range(1, max_n_idx-1):
    #                        row.append('')
    #                
    #                for t in mb.t:
    #                    if isinstance(index, tuple):
    #                        full_index = index + (t,) 
    #                    else:
    #                        full_index = (index,t)
    #                    val = v[full_index].value 
    #                    row.append(val)
    #                writer.writerow(row)

#                for index in v:
#                    row = []
#                    row.append(v.getname())
#                    idx_list = []
#                    for i in range(0,n_idx-1):
#                        # append the non-time indices of the variable
#                        idx_list.append(index[i])
#                    if n_idx < 3:
#                        # ^3 should be replaced with n_max, or something
#                        for i in range(0,3-n_index):
#                            # fill in the remaning indices
#                            idx_list.append('')
#                    # better way to do this, maybe:
#                    #    for i in range(0,max):
#                    #        try row.append(idx_list[i])
#                    #        except oob error: row.append('')
#                    for idx in idx_list:
#                        row.append(idx)
#                    for t in m.t:

    #for t in mb.t:
    #    alg_update(flowsheet,t)
    #    update_time_derivatives(flowsheet,t)
    #print_violated_constraints(flowsheet,t)

    #with open('dyn_fs_sol.txt','w') as f:
    #    flowsheet.display(ostream=f)

    
    '''
    print("\n")
    print("----------------------------------------------------------")
    print('Total simulation time: ', value(time.time() - ts), " s")
    print("----------------------------------------------------------")
    
    # Print some variables 
    print_summary_fuel_reactor(flowsheet) 

    # Plot some variables 
    #results_plot_fuel_reactor(flowsheet) 

    #with open('m_fs.txt','w') as f:
    #    flowsheet.display(ostream=f)

    # Store the flowsheet    
    '''
    return flowsheet
예제 #21
0
    def initialize(blk,
                   flow_vol=None,
                   temperature=None,
                   pressure=None,
                   conc_mol_comp=None,
                   state_vars_fixed=False,
                   hold_state=False,
                   outlvl=0,
                   solver='ipopt',
                   optarg={'tol': 1e-8}):
        '''
        Initialisation routine for property package.

        Keyword Arguments:
            flow_mol_comp : value at which to initialize component flows
                             (default=None)
            pressure : value at which to initialize pressure (default=None)
            temperature : value at which to initialize temperature
                          (default=None)
            outlvl : sets output level of initialisation routine

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

        Returns:
            If hold_states is True, returns a dict containing flags for
            which states were fixed during initialization.
        '''
        # Deactivate the constraints specific for outlet block i.e.
        # when defined state is False
        for k in blk.keys():
            if blk[k].config.defined_state is False:
                blk[k].conc_water_eqn.deactivate()

        if state_vars_fixed is False:
            # Fix state variables if not already fixed
            Fflag = {}
            Pflag = {}
            Tflag = {}
            Cflag = {}

            for k in blk.keys():
                # Fix state vars if not already fixed
                if blk[k].flow_vol.fixed is True:
                    Fflag[k] = True
                else:
                    Fflag[k] = False
                    if flow_vol is None:
                        blk[k].flow_vol.fix(1.0)
                    else:
                        blk[k].flow_vol.fix(flow_vol)

                for j in blk[k]._params.component_list:
                    if blk[k].conc_mol_comp[j].fixed is True:
                        Cflag[k, j] = True
                    else:
                        Cflag[k, j] = False
                        if conc_mol_comp is None:
                            if j == "H2O":
                                blk[k].conc_mol_comp[j].fix(55388.0)
                            else:
                                blk[k].conc_mol_comp[j].fix(100.0)
                        else:
                            blk[k].conc_mol_comp[j].fix(conc_mol_comp[j])

                if blk[k].pressure.fixed is True:
                    Pflag[k] = True
                else:
                    Pflag[k] = False
                    if pressure is None:
                        blk[k].pressure.fix(101325.0)
                    else:
                        blk[k].pressure.fix(pressure)

                if blk[k].temperature.fixed is True:
                    Tflag[k] = True
                else:
                    Tflag[k] = False
                    if temperature is None:
                        blk[k].temperature.fix(298.15)
                    else:
                        blk[k].temperature.fix(temperature)

            # If input block, return flags, else release state
            flags = {
                "Fflag": Fflag,
                "Pflag": Pflag,
                "Tflag": Tflag,
                "Cflag": Cflag
            }

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

        opt = SolverFactory(solver)
        opt.options = optarg

        # Post initialization reactivate constraints specific for
        # all blocks other than the inlet
        for k in blk.keys():
            if not blk[k].config.defined_state:
                blk[k].conc_water_eqn.activate()

        if state_vars_fixed is False:
            if hold_state is True:
                return flags
            else:
                blk.release_state(flags)

        if outlvl > 0:
            if outlvl > 0:
                _log.info('{} Initialisation Complete.'.format(blk.name))
예제 #22
0
def main():
    """
    Make the flowsheet object and solve
    """
    ss_flowsheet = ss_sim.main()

    flowsheet = Flowsheet(name='MB_Model')

    # fill in values of IC parameters from steady state solve
    setICs(flowsheet, ss_flowsheet)

    # Fix variables
    setInputs(flowsheet)

    # Initialize at steady state
    initialize_ss(flowsheet, ss_flowsheet)
    mb = flowsheet.MB_fuel

    write_differential_equations(flowsheet)

    # Then perturb
    solid_x_ptb = {'Fe2O3': 0.25, 'Fe3O4': 0.01, 'Al2O3': 0.74}
    gas_y_ptb = {'CO2': 0.03999, 'H2O': 0.00001, 'CH4': 0.96}
    #perturbInputs(flowsheet,0,Solid_M=691.4,Solid_T=1283,Solid_x=solid_x_ptb,
    #        Gas_F=150,Gas_T=350,Gas_y=gas_y_ptb)
    for t in mb.t:
        perturbInputs(flowsheet, t, Solid_M=691.4)

    # should put this in a dedicated ~intialize~ function
    # that also intelligently initializes the model after perturbation
    mb.eq_d4.deactivate()
    mb.eq_d5.deactivate()
    mb.eq_d8.deactivate()
    mb.eq_d9.deactivate()
    mb.eq_d10.deactivate()
    mb.eq_g7.deactivate()
    mb.eq_g8.deactivate()
    mb.eq_g10.deactivate()
    mb.eq_g11.deactivate()
    mb.eq_g12.deactivate()
    mb.eq_g13.deactivate()
    mb.eq_g14.deactivate()
    mb.eq_g4.deactivate()
    mb.eq_g5.deactivate()
    mb.eq_g2.deactivate()
    mb.Tg_GW.fix(0.0)
    mb.Tw_GW.fix(0.0)
    mb.Tg_refractory.fix(0.0)
    mb.Tw_Wamb.fix()
    mb.Tw.fix()
    mb.Nuw.fix()
    mb.Nu_ext.fix()
    mb.hw.fix()
    mb.hext.fix()
    mb.hext2.fix()
    mb.U.fix()
    mb.Uw.fix()
    mb.Pr_ext.fix()
    mb.Ra.fix()
    mb.Re.fix()
    ###

    # other tentatively unused variables:
    mb.mFe_mAl.fix(0.0)
    mb.Solid_Out_M_Comp.fix()

    mb.eq_c5.deactivate()

    # Create a solver
    tol = 1e-8
    opt = SolverFactory('ipopt')
    opt.options = {
        'tol': tol,
        'linear_solver': 'ma57',
        'bound_push': 1e-8,
        'max_cpu_time': 600,
        'print_level': 5
    }
    #'halt_on_ampl_error': 'yes'}

    # initialized at steady state, works regardless:
    flowsheet.strip_bounds()

    #for z in mb.z:
    #    for t in mb.t:
    #        mb.Cg[z,'CH4',t].setlb(1e-8)

    for t in mb.t:
        alg_update(flowsheet, t)
        update_time_derivatives(flowsheet, t)

    print_violated_constraints(flowsheet, tol)

    nlp_ss = PyomoNLP(ss_flowsheet)
    x_ss = get_vector_from_flowsheet(nlp_ss, ss_flowsheet)
    jac_ss = nlp_ss.jacobian_g(x_ss)

    print('calculating steady state condition number...')
    ss_condition = np.linalg.cond(jac_ss.toarray())
    print('steady state condition number: ', ss_condition)

    fig1, ax1 = plt.subplots()
    ax1.jac_ss = plt.spy(jac_ss)
    ax1.set_facecolor('none')
    fig1.savefig('jac_ss.png', facecolor='none',
                 edgecolor='none')  #'#f2f2f2',edgecolor='none')

    nlp = PyomoNLP(flowsheet)
    v_order = nlp.variable_order()
    c_order = nlp.constraint_order()
    x = get_vector_from_flowsheet(nlp, flowsheet)
    lam = nlp.create_vector_y()

    jac_c = nlp.jacobian_g(x)
    hess_lag = nlp.hessian_lag(x, lam)
    kkt = BlockSymMatrix(2)
    kkt[0, 0] = hess_lag
    kkt[1, 0] = jac_c

    fig2, ax2 = plt.subplots()
    ax2.jac_c = plt.spy(jac_c)
    ax2.set_facecolor('none')
    fig2.savefig('jac_c.png', facecolor='none', edgecolor='none')

    #MA27 = hsl.MA27_LinearSolver()
    #jac_row_fortran = np.zeros(jac_c.nnz,dtype=np.intc)
    #jac_col_fortran = np.zeros(jac_c.nnz,dtype=np.intc)
    #values = jac_c.data
    #for i in range(0,jac_c.nnz):
    #    jac_row_fortran[i] = int(jac_c.row[i] + 1)
    #    jac_col_fortran[i] = int(jac_c.col[i] + 1)
    #print('Doing symbolic factorization...')
    #MA27.DoSymbolicFactorization(nlp.nx,jac_row_fortran,jac_col_fortran)

    #print(jac_row_fortran)
    #print(jac_col_fortran)
    #print('Doing numeric factorization...')
    #num_status = MA27.DoNumericFactorization(nlp.nx,values)
    #print('Status: ',num_status)

    #jac_indices = range(0,jac_c.nnz)
    #for i in range(0,jac_c.nnz):
    #    if np.abs(values[i]) <= 1e-6:
    #        print('%0.2e'%values[i],str(jac_indices[i])+'-th nonzero.',jac_c.row[i],jac_c.col[i],
    #                c_order[jac_c.row[i]],v_order[jac_c.col[i]])

    #plot_switch = 0
    #if plot_switch == 1:
    #    fig,ax = plt.subplots()
    #    jac_value_plot = ax.bar(jac_indices,values)
    #    ax.set_yscale('log')
    #    fig.savefig('plots/jac_values.png')

    print('calculating condition number...')
    condition = np.linalg.cond(jac_c.toarray())
    print('condition number: ', condition)

    #mb.input_objective = Objective(expr=sum((mb.Solid_In_M[t] -601.4)**2 for t in mb.t))

    flowsheet.write('fs_dyn.nl')

    #with open('factorized_fs.txt','w') as f:
    #    flowsheet.display(ostream=f)

    return flowsheet
예제 #23
0
파일: ss_sim.py 프로젝트: Robbybp/IDAES-CLC
def main():
    """
    Make the flowsheet object and solve
    """
    flowsheet = Flowsheet(name='MB_Model') 
    
    # Fix variables
    setInputs(flowsheet) 

    ts = time.time() 

    mb = flowsheet.MB_fuel
    
    # Initialize fuel reactor
    flowsheet.MB_fuel._initialize(outlvl=1,
                              optarg={"tol"            : 1e-8,
                                      "max_cpu_time"   : 600,
                                      "print_level"    : 1,
                                      "halt_on_ampl_error": 'yes'})        
       
    # Create a solver
    opt = SolverFactory('ipopt')
    opt.options = {'tol': 1e-8,
                   'linear_solver'  : 'ma27',
                   'bound_push': 1e-8,
                   'max_cpu_time': 600,
                   'print_level': 5}
    
    results = opt.solve(flowsheet,tee=True,symbolic_solver_labels=False,
                            keepfiles=False)
    
    
    print("\n")
    print("----------------------------------------------------------")
    print('Total simulation time: ', value(time.time() - ts), " s")
    print("----------------------------------------------------------")

    
    # Print some variables 
    print_summary_fuel_reactor(flowsheet) 

    # Plot some variables 
    results_plot_fuel_reactor(flowsheet) 

    with open('ss_flowsheet.txt','w') as f:
        flowsheet.display(ostream=f)


    dt_Gflux_CO2    = []
    dt_Gflux_H2O    = []
    dt_Gflux_CH4    = []
    dt_Sflux_Fe2O3  = []
    dt_Sflux_Fe3O4  = []
    dt_Sflux_Al2O3  = []
    dt_Ctrans_CO2   = []
    dt_Ctrans_H2O   = []
    dt_Ctrans_CH4   = []
    dt_qtrans_Fe2O3 = []
    dt_qtrans_Fe3O4 = []
    dt_qtrans_Al2O3 = []
    dt_Ghflux       = []
    dt_Ts           = []
    dt_TgGS         = []
    dt_TsGS         = []
    dt_vg           = []
    dt_vs           = []

    for z in mb.z.get_finite_elements():
        if z != mb.z.first() and z != mb.z.last():

            dt_Gflux_CO2.append( (mb.Cg[z,'CO2'].value-mb.Cg[prev,'CO2'].value)/\
                    (mb.G_flux[z,'CO2'].value-mb.G_flux[prev,'CO2'].value) \
                    *(z-prev)*mb.eps.value*mb.L.value /(z-prev))

            dt_Gflux_H2O.append( (mb.Cg[z,'H2O'].value-mb.Cg[prev,'H2O'].value)/\
                    (mb.G_flux[z,'H2O'].value-mb.G_flux[prev,'H2O'].value) \
                    *(z-prev)*mb.eps.value*mb.L.value /(z-prev))

            dt_Gflux_CH4.append( (mb.Cg[z,'CH4'].value-mb.Cg[prev,'CH4'].value)/\
                    (mb.G_flux[z,'CH4'].value-mb.G_flux[prev,'CH4'].value) \
                    *(z-prev)*mb.eps.value*mb.L.value /(z-prev))

            dt_Ctrans_CO2.append( (mb.Cg[z,'CO2'].value-mb.Cg[prev,'CO2'].value)/\
                    (mb.Ctrans[z,'CO2'].value)* \
                    #-mv.Ctrans[prev,'CO2'].value)*\
                    mb.eps.value/(1-mb.eps.value) /(z-prev))

            dt_Ctrans_H2O.append( (mb.Cg[z,'H2O'].value-mb.Cg[prev,'H2O'].value)/\
                    (mb.Ctrans[z,'H2O'].value)* \
                    #-mv.Ctrans[prev,'H2O'].value)*\
                    mb.eps.value/(1-mb.eps.value) /(z-prev))

            dt_Ctrans_CH4.append( (mb.Cg[z,'CH4'].value-mb.Cg[prev,'CH4'].value)/\
                    (mb.Ctrans[z,'CH4'].value)* \
                    #-mv.Ctrans[prev,'CH4'].value)*\
                    mb.eps.value/(1-mb.eps.value) /(z-prev))

            dt_Sflux_Fe2O3.append( (mb.q[z,'Fe2O3'].value-mb.q[prev,'Fe2O3'].value)/\
                    (mb.S_flux[z,'Fe2O3'].value-mb.S_flux[prev,'Fe2O3'].value)*\
                    (z-prev)/(1-mb.eps.value)*mb.L.value /(z-prev))

            dt_Sflux_Fe3O4.append( (mb.q[z,'Fe3O4'].value-mb.q[prev,'Fe3O4'].value)/\
                    (mb.S_flux[z,'Fe3O4'].value-mb.S_flux[prev,'Fe3O4'].value)*\
                    (z-prev)/(1-mb.eps.value)*mb.L.value /(z-prev))

            dt_Sflux_Al2O3.append( (mb.q[z,'Al2O3'].value-mb.q[prev,'Al2O3'].value)/\
                    (mb.S_flux[z,'Al2O3'].value-mb.S_flux[prev,'Al2O3'].value)*\
                    (z-prev)/(1-mb.eps.value)*mb.L.value /(z-prev))

            dt_qtrans_Fe2O3.append( (mb.q[z,'Fe2O3'].value-mb.q[prev,'Fe2O3'].value)/\
                    (mb.qtrans[z,'Fe2O3'].value )/(z-prev)) 
                    #-mb.qtrans[prev,'Fe2O3'].value) )

            dt_qtrans_Fe3O4.append( (mb.q[z,'Fe3O4'].value-mb.q[prev,'Fe3O4'].value)/\
                    (mb.qtrans[z,'Fe3O4'].value )/(z-prev)) 
                    #-mb.qtrans[prev,'Fe3O4'].value) )

            dt_qtrans_Al2O3.append( (mb.q[z,'Fe3O4'].value-mb.q[prev,'Fe3O4'].value)/\
                    (mb.qtrans[z,'Fe3O4'].value )/(z-prev)) 
                    #-mb.qtrans[prev,'Fe3O4'].value) )

            dt_Ghflux.append( (mb.Tg[z].value-mb.Tg[prev].value)/\
                (mb.Gh_flux[z].value-mb.Gh_flux[prev].value)* (z-prev)* mb.eps.value*\
                mb.L.value* mb.rho_vap[z].value* mb.cp_gas[z].value /(z-prev)) 

            dt_Ts.append( (z-prev)*(1-mb.eps.value)*mb.L.value/mb.vs.value /(z-prev))

            dt_TgGS.append( (mb.Tg[z].value - mb.Tg[prev].value)/\
                    mb.Tg_GS[z].value* mb.eps.value* mb.rho_vap[z].value* mb.cp_gas[z].value 
                    /(z-prev))
    
            dt_TsGS.append( (mb.Ts[z].value - mb.Ts[prev].value)/\
                    mb.Tg_GS[z].value* (1-mb.eps.value)* mb.rho_sol.value* mb.cp_sol[z].value*1e-3 
                    /(z-prev))
    
            dt_vg.append( mb.L.value*(z-prev)/mb.vg[z].value /(z-prev))
    
            dt_vs.append( mb.L.value*(z-prev)/mb.vs.value /(z-prev))

        prev = z

    with open('dt.txt','w') as f:
        f.write('dt_Gflux_CO2\t')
        for t in dt_Gflux_CO2:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_Gflux_H2O\t')
        for t in dt_Gflux_H2O:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_Gflux_CH4\t')    
        for t in dt_Gflux_CH4:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_Sflux_Fe2O3\t') 
        for t in dt_Sflux_Fe2O3:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_Sflux_Fe3O4\t')  
        for t in dt_Sflux_Fe3O4:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_Sflux_Al2O3\t')  
        for t in dt_Sflux_Al2O3:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_Ctrans_CO2\t')  
        for t in dt_Ctrans_CO2:
            f.write('%1.3f'%t +'\t')
            
        f.write('\ndt_Ctrans_H2O\t')   
        for t in dt_Ctrans_H2O:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_Ctrans_CH4\t')   
        for t in dt_Ctrans_CH4:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_qtrans_Fe2O3\t') 
        for t in dt_qtrans_Fe2O3:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_qtrans_Fe3O4\t') 
        for t in dt_qtrans_Fe3O4:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_qtrans_Al2O3\t') 
        for t in dt_qtrans_Al2O3:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_Ghflux\t')      
        for t in dt_Ghflux:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_Ts\t\t')           
        for t in dt_Ts:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_TgGS\t\t')         
        for t in dt_TgGS:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_TsGS\t\t')         
        for t in dt_TsGS:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_vg\t\t')           
        for t in dt_vg:
            f.write('%1.3f'%t +'\t')

        f.write('\ndt_vs\t\t')           
        for t in dt_vs:
            f.write('%1.3f'%t +'\t')


    # Store the flowsheet    
    return flowsheet
예제 #24
0
    def initialize(blk,
                   state_args=None,
                   hold_state=False,
                   state_vars_fixed=False,
                   outlvl=idaeslog.NOTSET,
                   solver="ipopt",
                   optarg={"tol": 1e-8}):
        """
        Initialization routine for property package.
        Keyword Arguments:
            state_args : Dictionary with initial guesses for the state vars
                         chosen. Note that if this method is triggered
                         through the control volume, and if initial guesses
                         were not provided at the unit model level, the
                         control volume passes the inlet values as initial
                         guess.
                         Keys for the state_args dictionary are:
                         flow_mol, temperature, pressure and mole_frac_comp
            outlvl : sets output level of initialization routine
            optarg : solver options dictionary object (default=None)
            solver : str indicating which solver to use during
                     initialization (default = "ipopt")
            hold_state : flag indicating whether the initialization routine
                         should unfix any state variables fixed during
                         initialization (default=False).
                         - True - states varaibles are not unfixed, and
                                 a dict of returned containing flags for
                                 which states were fixed during
                                 initialization.
                        - False - state variables are unfixed after
                                 initialization by calling the
                                 relase_state method
        Returns:
            If hold_states is True, returns a dict containing flags for
            which states were fixed during initialization.
        """
        init_log = idaeslog.getInitLogger(blk.name, outlvl, tag="properties")
        solve_log = idaeslog.getSolveLogger(blk.name, outlvl, tag="properties")

        init_log.info_high('Starting initialization')

        # Deactivate the constraints specific for non-inlet blocks i.e.
        # when defined state is False
        for k in blk.keys():
            if blk[k].config.defined_state is False:
                blk[k].sum_component_eqn.deactivate()

        # Fix state variables if not already fixed
        if state_vars_fixed is False:
            flags = fix_state_vars(blk, state_args)
        else:
            # Check when the state vars are fixed already result in dof 0
            for k in blk.keys():
                if degrees_of_freedom(blk[k]) != 0:
                    raise Exception("State vars fixed but degrees of freedom "
                                    "for state block is not zero during "
                                    "initialization.")

        # Set solver options
        opt = SolverFactory(solver)
        opt.options = optarg

        # ---------------------------------------------------------------------
        # Initialise values
        for k in blk.keys():

            if hasattr(blk[k], "mw_eqn"):
                calculate_variable_from_constraint(blk[k].mw, blk[k].mw_eqn)

            if hasattr(blk[k], "ideal_gas"):
                calculate_variable_from_constraint(blk[k].dens_mol,
                                                   blk[k].ideal_gas)

            if hasattr(blk[k], "dens_mass_basis"):
                calculate_variable_from_constraint(blk[k].dens_mass,
                                                   blk[k].dens_mass_basis)

            if hasattr(blk[k], "mixture_heat_capacity_eqn"):
                calculate_variable_from_constraint(
                    blk[k].cp_mol, blk[k].mixture_heat_capacity_eqn)

            if hasattr(blk[k], "cp_mass_basis"):
                calculate_variable_from_constraint(blk[k].cp_mass,
                                                   blk[k].cp_mass_basis)

            if hasattr(blk[k], "visc_d_constraint"):
                calculate_variable_from_constraint(blk[k].visc_d,
                                                   blk[k].visc_d_constraint)

            if hasattr(blk[k], "therm_cond_constraint"):
                calculate_variable_from_constraint(
                    blk[k].therm_cond, blk[k].therm_cond_constraint)

            if hasattr(blk[k], "mixture_enthalpy_eqn"):
                calculate_variable_from_constraint(blk[k].enth_mol,
                                                   blk[k].mixture_enthalpy_eqn)

            for j in blk[k]._params.component_list:

                if hasattr(blk[k], "comp_conc_eqn"):
                    calculate_variable_from_constraint(blk[k].dens_mol_comp[j],
                                                       blk[k].comp_conc_eqn[j])

                if hasattr(blk[k], "diffusion_comp_constraint"):
                    calculate_variable_from_constraint(
                        blk[k].diffusion_comp[j],
                        blk[k].diffusion_comp_constraint[j])

                if hasattr(blk[k], "cp_shomate_eqn"):
                    calculate_variable_from_constraint(
                        blk[k].cp_mol_comp[j], blk[k].cp_shomate_eqn[j])

                if hasattr(blk[k], "enthalpy_shomate_eqn"):
                    calculate_variable_from_constraint(
                        blk[k].enth_mol_comp[j],
                        blk[k].enthalpy_shomate_eqn[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("Initialization complete {}.".format(
            idaeslog.condition(res)))

        # ---------------------------------------------------------------------
        if state_vars_fixed is False:
            if hold_state is True:
                return flags
            else:
                blk.release_state(flags)
예제 #25
0
    def initialize(blk,
                   state_args=None,
                   state_vars_fixed=False,
                   hold_state=False,
                   outlvl=1,
                   solver='ipopt',
                   optarg={'tol': 1e-8}):
        """
        Initialisation routine for property package.
        Keyword Arguments:
            state_args : Dictionary with initial guesses for the state vars
                         chosen. Note that if this method is triggered
                         through the control volume, and if initial guesses
                         were not provied at the unit model level, the
                         control volume passes the inlet values as initial
                         guess.The keys for the state_args dictionary are:

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

        _log.info('Starting {} initialisation'.format(blk.name))

        # Deactivate the constraints specific for outlet block i.e.
        # when defined state is False
        for k in blk.keys():
            if blk[k].config.defined_state is False:
                blk[k].sum_mole_frac_out.deactivate()

        # Fix state variables if not already fixed
        if state_vars_fixed is False:
            Fflag = {}
            Xflag = {}
            Pflag = {}
            Tflag = {}

            for k in blk.keys():
                if blk[k].flow_mol.fixed is True:
                    Fflag[k] = True
                else:
                    Fflag[k] = False
                    if state_args is None:
                        blk[k].flow_mol.fix(1.0)
                    else:
                        blk[k].flow_mol.fix(state_args["flow_mol"])

                for j in blk[k]._params.component_list:
                    if blk[k].mole_frac_comp[j].fixed is True:
                        Xflag[k, j] = True
                    else:
                        Xflag[k, j] = False
                        if state_args is None:
                            blk[k].mole_frac_comp[j].fix(
                                1 / len(blk[k]._params.component_list))
                        else:
                            blk[k].mole_frac_comp[j].fix(
                                state_args["mole_frac_comp"][j])

                if blk[k].pressure.fixed is True:
                    Pflag[k] = True
                else:
                    Pflag[k] = False
                    if state_args is None:
                        blk[k].pressure.fix(101325.0)
                    else:
                        blk[k].pressure.fix(state_args["pressure"])

                if blk[k].temperature.fixed is True:
                    Tflag[k] = True
                else:
                    Tflag[k] = False
                    if state_args is None:
                        blk[k].temperature.fix(325)
                    else:
                        blk[k].temperature.fix(state_args["temperature"])

            # ---------------------------------------------------------------------
            # If input block, return flags, else release state
            flags = {
                "Fflag": Fflag,
                "Xflag": Xflag,
                "Pflag": Pflag,
                "Tflag": Tflag
            }

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

        if optarg is None:
            sopt = {'tol': 1e-8}
        else:
            sopt = optarg

        opt = SolverFactory('ipopt')
        opt.options = sopt

        # ---------------------------------------------------------------------
        # If present, initialize bubble and dew point calculations
        for k in blk.keys():
            if hasattr(blk[k], "eq_temperature_bubble"):
                calculate_variable_from_constraint(
                    blk[k].temperature_bubble, blk[k].eq_temperature_bubble)

            if hasattr(blk[k], "eq_temperature_dew"):
                calculate_variable_from_constraint(blk[k].temperature_dew,
                                                   blk[k].eq_temperature_dew)

            if hasattr(blk[k], "eq_pressure_bubble"):
                calculate_variable_from_constraint(blk[k].pressure_bubble,
                                                   blk[k].eq_pressure_bubble)

            if hasattr(blk[k], "eq_pressure_dew"):
                calculate_variable_from_constraint(blk[k].pressure_dew,
                                                   blk[k].eq_pressure_dew)

        if outlvl > 0:
            _log.info("Dew and bubble points initialization for "
                      "{} completed".format(blk.name))

        # ---------------------------------------------------------------------
        # If flash, initialize T1 and Teq
        for k in blk.keys():
            if blk[k].config.has_phase_equilibrium:
                blk[k]._t1.value = max(blk[k].temperature.value,
                                       blk[k].temperature_bubble.value)
                blk[k]._teq.value = min(blk[k]._t1.value,
                                        blk[k].temperature_dew.value)

        if outlvl > 0:
            _log.info("Equilibrium temperature initialization for "
                      "{} completed".format(blk.name))

        # ---------------------------------------------------------------------
        # Initialize flow rates and compositions
        # TODO : This will need ot be generalised more when we move to a
        # modular implementation
        for k in blk.keys():
            if blk[k]._params.config.valid_phase == "Liq":
                blk[k].flow_mol_phase['Liq'].value = \
                    blk[k].flow_mol.value

                for j in blk[k]._params.component_list:
                    blk[k].mole_frac_phase_comp['Liq', j].value = \
                        blk[k].mole_frac_comp[j].value

            elif blk[k]._params.config.valid_phase == "Vap":
                blk[k].flow_mol_phase['Vap'].value = \
                    blk[k].flow_mol.value

                for j in blk[k]._params.component_list:
                    blk[k].mole_frac_phase_comp['Vap', j].value = \
                        blk[k].mole_frac_comp[j].value

            else:
                # Seems to work best with default values for phase flows
                for j in blk[k]._params.component_list:
                    blk[k].mole_frac_phase_comp['Vap', j].value = \
                        blk[k].mole_frac_comp[j].value
                    blk[k].mole_frac_phase_comp['Liq', j].value = \
                        blk[k].mole_frac_comp[j].value

                    calculate_variable_from_constraint(
                        blk[k].pressure_sat[j], blk[k].eq_pressure_sat[j])

        # ---------------------------------------------------------------------
        # Solve phase equilibrium constraints
        for k in blk.keys():
            for c in blk[k].component_objects(Constraint):
                # Deactivate all property constraints
                if c.local_name not in ("total_flow_balance",
                                        "component_flow_balances",
                                        "equilibrium_constraint",
                                        "sum_mole_frac", "_t1_constraint",
                                        "_teq_constraint", "eq_pressure_dew",
                                        "eq_pressure_bubble",
                                        "eq_temperature_dew",
                                        "eq_temperature_bubble",
                                        "eq_pressure_sat"):
                    c.deactivate()

        results = solve_indexed_blocks(opt, [blk], tee=stee)

        if outlvl > 0:
            if results.solver.termination_condition \
                    == TerminationCondition.optimal:
                _log.info("Phase state initialization for "
                          "{} completed".format(blk.name))
            else:
                _log.warning("Phase state initialization for "
                             "{} failed".format(blk.name))

        # ---------------------------------------------------------------------
        # Initialize other properties
        for k in blk.keys():
            for c in blk[k].component_objects(Constraint):
                # Activate all constraints except sum_mole_frac_out
                if c.local_name not in ("sum_mole_frac_out"):
                    c.activate()

        if outlvl > 0:
            if results.solver.termination_condition \
                    == TerminationCondition.optimal:
                _log.info("Property initialization for "
                          "{} completed".format(blk.name))
            else:
                _log.warning("Property initialization for "
                             "{} failed".format(blk.name))

        # ---------------------------------------------------------------------
        # Return state to initial conditions
        for k in blk.keys():
            if (blk[k].config.defined_state is False):
                blk[k].sum_mole_frac_out.activate()

        if state_vars_fixed is False:
            if hold_state is True:
                return flags
            else:
                blk.release_state(flags)

        if outlvl > 0:
            _log.info("Initialisation completed for {}".format(blk.name))
예제 #26
0
    def initialize(blk,
                   state_args=None,
                   hold_state=False,
                   outlvl=0,
                   solver='ipopt',
                   optarg={'tol': 1e-8}):
        """
        Initialisation routine for property package.

        Keyword Arguments:
            state_args : Dictionary with initial guesses for the state vars
                         chosen. Note that if this method is triggered
                         through the control volume, and if initial guesses
                         were not provied at the unit model level, the
                         control volume passes the inlet values as initial
                         guess.The keys for the state_args dictionary are:

                         flow_mol : value at which to initialize component
                                    flows
                         pressure : value at which to initialize pressure
                         temperature : value at which to initialize temperature
                         mole_frac_comp: value at which to initialize the component
                                    mixture mole fraction
            outlvl : sets output level of initialisation routine

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

            optarg : solver options dictionary object (default=None)
            solver : str indicating whcih solver to use during
                     initialization (default = 'ipopt')
            hold_state : flag indicating whether the initialization routine
                         should unfix any state variables fixed during
                         initialization (default=False).
                         - True - states varaibles are not unfixed, and
                                 a dict of returned containing flags for
                                 which states were fixed during
                                 initialization.
                        - False - state variables are unfixed after
                                 initialization by calling the
                                 relase_state method

        Returns:
            If hold_states is True, returns a dict containing flags for
            which states were fixed during initialization.
        """
        # Fix state variables if not already fixed
        flags = fix_state_vars(blk, state_args)

        # Set solver options
        if outlvl > 1:
            stee = True
        else:
            stee = False

        if optarg is None:
            sopt = {'tol': 1e-8}
        else:
            sopt = optarg

        opt = SolverFactory('ipopt')
        opt.options = sopt

        # ---------------------------------------------------------------------
        for k in blk.keys():

            blk[k].eq_total.deactivate()
            blk[k].eq_comp.deactivate()
            if (blk[k].config.defined_state is False):
                blk[k].eq_mol_frac_out.deactivate()
            if (blk[k].config.has_phase_equilibrium) or \
                    (blk[k].config.parameters.config.valid_phase ==
                        ('Liq', 'Vap')) or \
                    (blk[k].config.parameters.config.valid_phase ==
                        ('Vap', 'Liq')):
                blk[k].eq_Keq.deactivate()
                blk[k].eq_sum_mol_frac.deactivate()

        if (blk[k].config.has_phase_equilibrium) or \
                (blk[k].config.parameters.config.valid_phase ==
                    ('Liq', 'Vap')) or \
                (blk[k].config.parameters.config.valid_phase ==
                    ('Vap', 'Liq')):
            results = solve_indexed_blocks(opt, [blk], tee=stee)

            if outlvl > 0:
                if results.solver.termination_condition \
                        == TerminationCondition.optimal:
                    _log.info("Initialisation step 1 for "
                              "{} completed".format(blk.name))
                else:
                    _log.warning("Initialisation step 1 for "
                                 "{} failed".format(blk.name))

        else:
            if outlvl > 0:
                _log.info("Initialisation step 1 for "
                          "{} skipped".format(blk.name))

        for k in blk.keys():
            blk[k].eq_total.activate()
            blk[k].eq_comp.activate()
            if (blk[k].config.has_phase_equilibrium) or \
                    (blk[k].config.parameters.config.valid_phase ==
                        ('Liq', 'Vap')) or \
                    (blk[k].config.parameters.config.valid_phase ==
                        ('Vap', 'Liq')):
                blk[k].eq_Keq.activate()
                blk[k].eq_sum_mol_frac.activate()

        results = solve_indexed_blocks(opt, [blk], tee=stee)

        if outlvl > 0:
            if results.solver.termination_condition \
                    == TerminationCondition.optimal:
                _log.info("Initialisation step 2 for "
                          "{} completed".format(blk.name))
            else:
                _log.warning("Initialisation step 2 for "
                             "{} failed".format(blk.name))

        for k in blk.keys():
            if (blk[k].config.defined_state is False):
                blk[k].eq_mol_frac_out.activate()
        # ---------------------------------------------------------------------
        # If input block, return flags, else release state
        if hold_state is True:
            return flags
        else:
            blk.release_state(flags)

        if outlvl > 0:
            if outlvl > 0:
                _log.info('{} Initialisation Complete.'.format(blk.name))
예제 #27
0
    def initialize(blk,
                   flow_mol_phase_comp=None,
                   temperature=None,
                   pressure=None,
                   state_vars_fixed=False,
                   hold_state=False,
                   outlvl=1,
                   solver='ipopt',
                   optarg={'tol': 1e-8}):
        """
        Initialisation routine for property package.
        Keyword Arguments:
            flow_mol_phase_comp : value at which to initialize phase-component
                                flows (default=None)
            pressure : value at which to initialize pressure (default=None)
            temperature : value at which to initialize temperature
                          (default=None)
            outlvl : sets output level of initialisation routine
                     * 0 = no output (default)
                     * 1 = return solver state for each step in routine
                     * 2 = include solver output infomation (tee=True)
            optarg : solver options dictionary object (default=None)
            state_vars_fixed: Flag to denote if state vars have already been
                              fixed.
                              - True - states have already been fixed by the
                                       control volume 1D. Control volume 0D
                                       does not fix the state vars, so will
                                       be False if this state block is used
                                       with 0D blocks.
                             - False - states have not been fixed. The state
                                       block will deal with fixing/unfixing.
            solver : str indicating whcih solver to use during
                     initialization (default = 'ipopt')
            hold_state : flag indicating whether the initialization routine
                         should unfix any state variables fixed during
                         initialization (default=False).
                         - True - states varaibles are not unfixed, and
                                 a dict of returned containing flags for
                                 which states were fixed during
                                 initialization.
                        - False - state variables are unfixed after
                                 initialization by calling the
                                 relase_state method
        Returns:
            If hold_states is True, returns a dict containing flags for
            which states were fixed during initialization.
        """

        _log.info('Starting {} initialisation'.format(blk.name))

        # Fix state variables if not already fixed
        if state_vars_fixed is False:
            Fflag = {}
            Pflag = {}
            Tflag = {}

            for k in blk.keys():
                for p in blk[k]._params.phase_list:
                    for j in blk[k]._params.component_list:
                        if blk[k].flow_mol_phase_comp[p, j].fixed is True:
                            Fflag[k, p, j] = True
                        else:
                            Fflag[k, p, j] = False
                            if flow_mol_phase_comp is None:
                                blk[k].flow_mol_phase_comp[p, j].fix(
                                    1 / len(blk[k]._params.component_list))
                            else:
                                blk[k].flow_mol_phase_comp[p, j].fix(
                                    flow_mol_phase_comp[p, j])

                if blk[k].pressure.fixed is True:
                    Pflag[k] = True
                else:
                    Pflag[k] = False
                    if pressure is None:
                        blk[k].pressure.fix(101325.0)
                    else:
                        blk[k].pressure.fix(pressure)

                if blk[k].temperature.fixed is True:
                    Tflag[k] = True
                else:
                    Tflag[k] = False
                    if temperature is None:
                        blk[k].temperature.fix(325)
                    else:
                        blk[k].temperature.fix(temperature)

            # -----------------------------------------------------------------
            # If input block, return flags, else release state
            flags = {"Fflag": Fflag, "Pflag": Pflag, "Tflag": Tflag}

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

        if optarg is None:
            sopt = {'tol': 1e-8}
        else:
            sopt = optarg

        opt = SolverFactory('ipopt')
        opt.options = sopt

        # ---------------------------------------------------------------------
        # If present, initialize bubble and dew point calculations
        for k in blk.keys():
            if hasattr(blk[k], "eq_temperature_dew"):
                calculate_variable_from_constraint(blk[k].temperature_dew,
                                                   blk[k].eq_temperature_dew)

            if hasattr(blk[k], "eq_pressure_dew"):
                calculate_variable_from_constraint(blk[k].pressure_dew,
                                                   blk[k].eq_pressure_dew)

        if outlvl > 0:
            _log.info("Dew and bubble points initialization for "
                      "{} completed".format(blk.name))

        # ---------------------------------------------------------------------
        # If flash, initialize T1 and Teq
        for k in blk.keys():
            if (blk[k].config.has_phase_equilibrium
                    and not blk[k].config.defined_state):
                blk[k]._t1.value = max(blk[k].temperature.value,
                                       blk[k].temperature_bubble.value)
                blk[k]._teq.value = min(blk[k]._t1.value,
                                        blk[k].temperature_dew.value)

        if outlvl > 0:
            _log.info("Equilibrium temperature initialization for "
                      "{} completed".format(blk.name))

        # ---------------------------------------------------------------------
        # Initialize flow rates and compositions
        # TODO : This will need ot be generalised more when we move to a
        # modular implementation
        for k in blk.keys():
            # Deactivate equilibrium constraints, as state is fixed
            if hasattr(blk[k], 'equilibrium_constraint'):
                blk[k].equilibrium_constraint.deactivate()

        free_vars = 0
        for k in blk.keys():
            free_vars += number_unfixed_variables(blk[k])
        if free_vars > 0:
            try:
                results = solve_indexed_blocks(opt, [blk], tee=stee)
            except:
                results = None
        else:
            results = None

        for k in blk.keys():
            # Reactivate equilibrium constraints
            if hasattr(blk[k], 'equilibrium_constraint'):
                blk[k].equilibrium_constraint.activate()

        if outlvl > 0:
            if results is None or results.solver.termination_condition \
                    == TerminationCondition.optimal:
                _log.info("Property initialization for "
                          "{} completed".format(blk.name))
            else:
                _log.warning("Property initialization for "
                             "{} failed".format(blk.name))

        # ---------------------------------------------------------------------
        # Return state to initial conditions
        if state_vars_fixed is False:
            if hold_state is True:
                return flags
            else:
                blk.release_state(flags)

        if outlvl > 0:
            _log.info("Initialisation completed for {}".format(blk.name))
예제 #28
0
def main():
    """
    Make the flowsheet object and solve
    """
    ss_init = ss_sim.main()

    flowsheet = Flowsheet(name='MB_Model')

    # fill in values of IC parameters from steady state solve
    setICs(flowsheet, ss_init)

    # Fix variables
    setInputs(flowsheet)

    # Initialize at steady state
    initialize_ss(flowsheet, ss_init)
    mb = flowsheet.MB_fuel

    #write_differential_equations(flowsheet)

    # Then perturb
    ptb = {}
    solid_x_ptb = {'Fe2O3': 0.25, 'Fe3O4': 0.01, 'Al2O3': 0.74}
    gas_y_ptb = {'CO2': 0.04999, 'H2O': 0.00001, 'CH4': 0.95}
    #perturbInputs(flowsheet,0,Solid_M=691.4,Solid_T=1283.15,Solid_x=solid_x_ptb,
    #        Gas_F=150,Gas_T=350,Gas_y=gas_y_ptb)
    for t in mb.t:
        ptb_inputs(flowsheet, t, Solid_M=691.4)

    ss_final = ss_sim.main(Solid_M=691.4)

    with open('ss_init.txt', 'w') as f:
        ss_init.display(ostream=f)

    with open('ss_fin.txt', 'w') as f:
        ss_final.display(ostream=f)

    # should put this in a dedicated ~intialize~ function
    # that also intelligently initializes the model after perturbation
    mb.eq_d4.deactivate()
    mb.eq_d5.deactivate()
    mb.eq_d8.deactivate()
    mb.eq_d9.deactivate()
    mb.eq_d10.deactivate()
    mb.eq_g7.deactivate()
    mb.eq_g8.deactivate()
    mb.eq_g10.deactivate()
    mb.eq_g11.deactivate()
    mb.eq_g12.deactivate()
    mb.eq_g13.deactivate()
    mb.eq_g14.deactivate()
    mb.eq_g4.deactivate()
    mb.eq_g5.deactivate()
    mb.eq_g2.deactivate()
    mb.Tg_GW.fix(0.0)
    mb.Tw_GW.fix(0.0)
    mb.Tg_refractory.fix(0.0)
    mb.Tw_Wamb.fix()
    mb.Tw.fix()
    mb.Nuw.fix()
    mb.Nu_ext.fix()
    mb.hw.fix()
    mb.hext.fix()
    mb.hext2.fix()
    mb.U.fix()
    mb.Uw.fix()
    mb.Pr_ext.fix()
    mb.Ra.fix()
    mb.Re.fix()
    ###

    # other tentatively unused variables:
    mb.mFe_mAl.fix(0.0)
    mb.Solid_Out_M_Comp.fix()

    # choose how to calculate certain algebraic variables:
    mb.eq_c5.deactivate()

    # Create a solver
    tol = 1e-8
    opt = SolverFactory('ipopt')
    opt.options = {
        'tol': tol,
        'linear_solver': 'ma57',
        'bound_push': 1e-8,
        'max_cpu_time': 600,
        'print_level': 5,
        'output_file': 'ipopt_out.txt',
        'linear_system_scaling': 'mc19',
        #'linear_scaling_on_demand' : 'yes',
        'halt_on_ampl_error': 'yes'
    }

    # initialized at steady state, works regardless:
    flowsheet.strip_bounds()

    print_violated_constraints(flowsheet, tol)

    for t in mb.t:
        alg_update(flowsheet, t)
        update_time_derivatives(flowsheet, t)

    constraint_list = []
    for c in mb.component_objects(Constraint):
        constraint_list.append(c)
    create_suffixes(flowsheet)
    vars_to_scale = []
    data_scaled = []
    con_data_2update = []
    for var in mb.component_objects(Var):
        # need static list of vars to scale
        vars_to_scale.append(var)
    for var in mb.component_data_objects(Var):
        # should I create parallel blocks of scaled/unscaled constraints?
        data_scaled.append(var)
    for con in mb.component_data_objects(Constraint):
        con_data_2update.append(con)
    # should separate variables into input/response variables
    # only scale response variables, or have separate function to
    # scale input variables
    #
    # or, an is_alg_fcn_of() function would be nice, but probably very
    # difficult to implement
    #
    # should be able to partition variables into useful categories...
    # differential, algebraic-important, algebraic-auxiliary, time-derivative,
    # space-derivative, geometric, (parameter,) input, input-algebraic
    #
    # such a partition would be incredibly powerful for a variety of applications
    # e.g. identifying degrees of freedom, index reduction, initialization,
    #      model simplification

    diff_vars = [mb.Cg, mb.q, mb.Tg, mb.Ts]
    alg_vars = [
        mb.Gas_Out_P, mb.Solid_Out_M, mb.Solid_Out_Ts, mb.Solid_Out_x, mb.CgT,
        mb.Ctrans, mb.G_flux, mb.X_gas, mb.y, mb.ytot, mb.Ftotal, mb.F,
        mb.Gas_M, mb.qT, mb.qtrans, mb.S_flux, mb.X_OC, mb.x, mb.xtot,
        mb.Solid_M_total, mb.Solid_M, mb.Solid_F_total, mb.Solid_F, mb.mFe_mAl,
        mb.P, mb.Tg_GS, mb.Ts_dHr, mb.vg, mb.umf, mb.v_diff, mb.Rep, mb.Pr,
        mb.Pr_ext, mb.Ra, mb.Nu, mb.hf, mb.Gh_flux, mb.Sh_flux, mb.DH_rxn_s,
        mb.cp_sol, mb.MW_vap, mb.rho_vap, mb.mu_vap, mb.cp_gas, mb.cp_vap,
        mb.k_cpcv, mb.k_vap, mb.X, mb.X_term, mb.k, mb.r_gen, mb.rg, mb.rs,
        mb.dG_fluxdz, mb.dS_fluxdz, mb.dPdz, mb.dGh_fluxdz, mb.dSh_fluxdz
    ]
    dyn_vars = diff_vars + alg_vars
    constraints_to_scan = []
    for con in mb.component_objects(Constraint):
        constraints_to_scan.append(con)
    for var in dyn_vars:
        print(var.name)
        create_scale_values(var, flowsheet, ss_init, ss_final)
    #create_scale_values(mb.Cg, flowsheet, ss_init, ss_final)
    #with open('pre_constraint_update.txt', 'w') as f:
    #    flowsheet.display(ostream=f)
    for con in constraints_to_scan:
        # probably need to selectively update constraints as well
        print(con.name)
        update_constraint(con, flowsheet)
    # TODO: -check that constraints have been properly updated,
    #       -check for violated constraints (in this single element),
    #        ^ should only be discretization equations...
    #       -try to solve model
    #       -have not scaled constraints yet, but should still solve...

    #update_constraint(mb.eq_c4, flowsheet)
    #update_constraint(mb.eq_b1, flowsheet)
    #update_constraint(mb.eq_a2, flowsheet)
    #update_constraint(mb.eq_p2, flowsheet)

    with open('scale_vars.txt', 'w') as f:
        # per custom, I should replace this with a 'write_scale_vars()' function

        #    line = ''
        #    for var in m.component_objects(Var):
        #        if isinstance(var, SimpleVar):
        #            line = line + var.name + ' ' + str(var.value)
        #            # ^probably need to re-format this value string
        #            try:
        #                if var.has_dev_exp == True:
        #                    line = line + '\t' + var.dev.name + ' ' + str(value(var.dev))
        #            except AttributeError:
        #                pass
        #        else:
        #            try:
        #                if var.has_dev_exp == True:
        #                    for index in var:
        for var in data_scaled:
            line = var.local_name + ' '
            try:
                if var.parent_component().has_dev_exp == True:
                    line = (line + var.parent_component().dev_exp[
                        var.index()].expr.to_string())
            except AttributeError:
                line = line + ' has no deviation expression'
            line = line + '\n'
            f.write(line)

    write_constraint_expressions(con_data_2update)
    #print(mb.eq_p2[0.00062,0].expr.to_string())
    #print(mb.eq_p2.dev_con[0.00062,0].expr.to_string())

    with open('dyn_scaled_init.txt', 'w') as f:
        flowsheet.display(ostream=f)

    mb.cont_param.set_value(1)

    return flowsheet