def check_active_bound_noisy(self):
        """Checks if the dof_(super-basic) have active bounds, if so, add them to the exclusion list"""
        if hasattr(self.lsmhe, "dof_v"):
            self.lsmhe.dof_v.clear()
        else:
            self.lsmhe.dof_v = Suffix(direction=Suffix.EXPORT)  #: dof_v
        if hasattr(self.lsmhe, "rh_name"):
            self.lsmhe.rh_name.clear()
        else:
            self.lsmhe.rh_name = Suffix(direction=Suffix.IMPORT)  #: Red_hess_name

        self.xkN_nexcl = []
        k = 0
        for x in self.x_noisy:
            v = getattr(self.lsmhe, x)
            for j in self.x_vars[x]:
                active_bound = False
                if v[(2, 0) + j].lb:
                    if v[(2, 0) + j].value - v[(2, 0) + j].lb < 1e-08:
                        active_bound = True
                if v[(2, 0) + j].ub:
                    if v[(2, 0) + j].ub - v[(2, 0) + j].value < 1e-08:
                        active_bound = True
                if active_bound:
                    print("Active bound {:s}, {:d}, value {:f}".format(x, j[0], v[(2, 0) + j].value), file=sys.stderr)
                    v[(2, 0) + j].set_suffix_value(self.lsmhe.dof_v, 0)
                    self.xkN_nexcl.append(0)
                    k += 1
                else:
                    v[(2, 0) + j].set_suffix_value(self.lsmhe.dof_v, 1)
                    self.xkN_nexcl.append(1)  #: Not active, add it to the non-exclusion list.
        if k > 0:
            print("I[[check_active_bound_noisy]] {:d} Active bounds.".format(k))
Beispiel #2
0
    def sens_dot_nmpc(self):
        self.journalist("I", self._iteration_count, "sens_dot_nmpc", "Set-up")

        if hasattr(self.olnmpc, "npdp"):
            self.olnmpc.npdp.clear()
        else:
            self.olnmpc.npdp = Suffix(direction=Suffix.EXPORT)

        for x in self.states:
            con_name = x + "_icc"
            con_ = getattr(self.olnmpc, con_name)
            for j in self.state_vars[x]:
                con_[j].set_suffix_value(self.olnmpc.npdp, self.curr_state_offset[(x, j)])

        if hasattr(self.olnmpc, "f_timestamp"):
            self.olnmpc.f_timestamp.clear()
        else:
            self.olnmpc.f_timestamp = Suffix(direction=Suffix.EXPORT,
                                            datatype=Suffix.INT)
        self.olnmpc.set_suffix_value(self.olnmpc.f_timestamp, self.int_file_nmpc_suf)

        self.olnmpc.f_timestamp.display(ostream=sys.stderr)

        self.journalist("I", self._iteration_count, "sens_dot_nmpc", self.olnmpc.name)

        results = self.dot_driver.solve(self.olnmpc, tee=True, symbolic_solver_labels=True)
        self.olnmpc.solutions.load_from(results)
        self.olnmpc.f_timestamp.display(ostream=sys.stderr)

        ftiming = open("timings_dot_driver.txt", "r")
        s = ftiming.readline()
        ftiming.close()
        k = s.split()
        self._dot_timing = k[0]
    def create_rh_sfx(self, set_suffix=True):
        """Creates relevant suffixes for k_aug (prior at fe=2) (Reduced_Hess)
        Args:
            set_suffix (bool): True if update must be done
        Returns:
            None
        """
        if hasattr(self.lsmhe, "dof_v"):
            self.lsmhe.dof_v.clear()
        else:
            self.lsmhe.dof_v = Suffix(direction=Suffix.EXPORT)  #: dof_v
        if hasattr(self.lsmhe, "rh_name"):
            self.lsmhe.rh_name.clear()
        else:
            self.lsmhe.rh_name = Suffix(direction=Suffix.IMPORT)  #: Red_hess_name

        if hasattr(self.lsmhe, "f_timestamp"):
            self.lsmhe.f_timestamp.clear()
        else:
            self.lsmhe.f_timestamp = Suffix(direction=Suffix.EXPORT,
                                            datatype=Suffix.INT)

        if set_suffix:
            for key in self.x_noisy:
                var = getattr(self.lsmhe, key)
                for j in self.x_vars[key]:
                    var[(2, 0) + j].set_suffix_value(self.lsmhe.dof_v, 1)
Beispiel #4
0
    def create_suffixes_nmpc(self):
        """Creates the required suffixes for the olnmpc problem"""
        if hasattr(self.olnmpc, "npdp"):
            pass
        else:
            self.olnmpc.npdp = Suffix(direction=Suffix.EXPORT)
        if hasattr(self.olnmpc, "dof_v"):
            pass
        else:
            self.olnmpc.dof_v = Suffix(direction=Suffix.EXPORT)

        for u in self.u:
            uv = getattr(self.olnmpc, u)
            uv[0].set_suffix_value(self.olnmpc.dof_v, 1)
    def sens_dot_mhe(self):
        """Updates suffixes, solves using the dot_driver"""
        self.journalizer("I", self._c_it, "sens_dot_mhe", "Set-up")

        if hasattr(self.lsmhe, "npdp"):
            self.lsmhe.npdp.clear()
        else:
            self.lsmhe.npdp = Suffix(direction=Suffix.EXPORT)
        self.create_sens_suffix_mhe()
        for y in self.y:
            for j in self.y_vars[y]:
                k = self.yk_key[(y, j)]
                self.lsmhe.hyk_c_mhe[self.nfe_t, k].set_suffix_value(
                    self.lsmhe.npdp, self.curr_y_offset[(y, j)])

        # with open("somefile0.txt", "w") as f:
        #     self.lsmhe.x.display(ostream=f)
        #     self.lsmhe.M.display(ostream=f)
        #     f.close()
        if hasattr(self.lsmhe, "f_timestamp"):
            self.lsmhe.f_timestamp.clear()
        else:
            self.lsmhe.f_timestamp = Suffix(direction=Suffix.EXPORT,
                                            datatype=Suffix.INT)
        #: Looks for the file with the timestamp
        self.lsmhe.set_suffix_value(self.lsmhe.f_timestamp,
                                    self.int_file_mhe_suf)

        self.lsmhe.f_timestamp.display(ostream=sys.stderr)

        self.journalizer("I", self._c_it, "sens_dot_mhe", self.lsmhe.name)

        results = self.dot_driver.solve(self.lsmhe,
                                        tee=True,
                                        symbolic_solver_labels=True)
        self.lsmhe.solutions.load_from(results)
        self.lsmhe.f_timestamp.display(ostream=sys.stderr)

        # with open("somefile1.txt", "w") as f:
        #     self.lsmhe.x.display(ostream=f)
        #     self.lsmhe.M.display(ostream=f)
        #     f.close()

        ftiming = open("timings_dot_driver.txt", "r")
        s = ftiming.readline()
        ftiming.close()
        k = s.split()
        self._dot_timing = k[0]
Beispiel #6
0
    def _GDPopt_initialize_master(self, solve_data, config):
        """Initialize the decomposition algorithm.

        This includes generating the initial cuts require to build the master
        problem.

        """
        config.logger.info("---Starting GDPopt initialization---")
        m = solve_data.working_model
        if not hasattr(m, 'dual'):  # Set up dual value reporting
            m.dual = Suffix(direction=Suffix.IMPORT)
        m.dual.activate()

        # Set up the linear GDP model
        solve_data.linear_GDP = m.clone()
        # deactivate nonlinear constraints
        for c in solve_data.linear_GDP.GDPopt_utils.\
                working_nonlinear_constraints:
            c.deactivate()

        # Initialization strategies
        init_strategy = valid_init_strategies.get(config.init_strategy, None)
        if init_strategy is not None:
            init_strategy(solve_data, config)
        else:
            raise ValueError('Unknown initialization strategy: %s. '
                             'Valid strategies include: %s' %
                             (config.init_strategy, ", ".join(
                                 valid_init_strategies.keys())))
Beispiel #7
0
    def _apply_to(self, model, **kwds):
        options = kwds.pop('options', {})
        if kwds.get('undo', options.get('undo', False)):
            for v, d in itervalues(model._relaxed_discrete_vars[None]):
                v.domain = d
            model.del_component("_relaxed_discrete_vars")
            return

        # Relax the model
        relaxed_vars = {}
        _base_model_vars = model.component_data_objects(Var,
                                                        active=True,
                                                        descend_into=True)
        for var in _base_model_vars:
            if var.domain in _discrete_relaxation_map:
                if var.domain is Binary or var.domain is Boolean:
                    var.setlb(0)
                    var.setub(1)
                # Note: some indexed components can only have their
                # domain set on the parent component (the individual
                # indices cannot be set independently)
                _c = var.parent_component()
                if id(_c) in _discrete_relaxation_map:
                    continue
                try:
                    _domain = var.domain
                    var.domain = _discrete_relaxation_map[_domain]
                    relaxed_vars[id(var)] = (var, _domain)
                except:
                    _domain = _c.domain
                    _c.domain = _discrete_relaxation_map[_domain]
                    relaxed_vars[id(_c)] = (_c, _domain)
        model._relaxed_discrete_vars = Suffix(direction=Suffix.LOCAL)
        model._relaxed_discrete_vars[None] = relaxed_vars
    def load_covariance_prior(self):
        """Computes the reduced-hessian (inverse of the prior-covariance)
        Reads the result_hessian.txt file that contains the covariance information"""
        self.journalizer("I", self._c_it, "load_covariance_prior", "K_AUG w red_hess")
        self.k_aug.options["compute_inv"] = ""
        if hasattr(self.lsmhe, "f_timestamp"):
            self.lsmhe.f_timestamp.clear()
        else:
            self.lsmhe.f_timestamp = Suffix(direction=Suffix.EXPORT,
                                            datatype=Suffix.INT)
        self.create_rh_sfx()
        self.k_aug.solve(self.lsmhe, tee=True)
        self.lsmhe.f_timestamp.display(ostream=sys.stderr)

        self._PI.clear()
        with open("inv_.in", "r") as rh:
            ll = []
            l = rh.readlines()
            row = 0
            for i in l:
                ll = i.split()
                col = 0
                for j in ll:
                    self._PI[row, col] = float(j)
                    col += 1
                row += 1
            rh.close()
        print("-" * 120)
        print("I[[load covariance]] e-states nrows {:d} ncols {:d}".format(len(l), len(ll)))
        print("-" * 120)
    def sens_k_aug_mhe(self):
        self.journalizer("I", self._c_it, "sens_k_aug_mhe",
                         "k_aug sensitivity")
        self.lsmhe.ipopt_zL_in.update(self.lsmhe.ipopt_zL_out)
        self.lsmhe.ipopt_zU_in.update(self.lsmhe.ipopt_zU_out)
        self.journalizer("I", self._c_it, "sens_k_aug_mhe", self.lsmhe.name)

        if hasattr(self.lsmhe, "f_timestamp"):
            self.lsmhe.f_timestamp.clear()
        else:
            self.lsmhe.f_timestamp = Suffix(direction=Suffix.EXPORT,
                                            datatype=Suffix.INT)
        #: Now, the sensitivity step will have the timestamp for dot_in

        self.lsmhe.set_suffix_value(self.lsmhe.f_timestamp,
                                    self.int_file_mhe_suf)
        self.lsmhe.f_timestamp.display(ostream=sys.stderr)
        self.create_sens_suffix_mhe()
        results = self.k_aug_sens.solve(self.lsmhe,
                                        tee=True,
                                        symbolic_solver_labels=True)
        self.lsmhe.solutions.load_from(results)
        self.lsmhe.f_timestamp.display(ostream=sys.stderr)
        ftimings = open("timings_k_aug.txt", "r")
        s = ftimings.readline()
        ftimings.close()
        self._k_timing = s.split()
Beispiel #10
0
 def create_sens_suffix_mhe(self, set_suffix=True):
     """Creates relevant suffixes for k_aug (Sensitivity)
     Args:
         set_suffix (bool): True if update must be done
     Returns:
         None"""
     if hasattr(self.lsmhe, "dof_v"):
         self.lsmhe.dof_v.clear()
     else:
         self.lsmhe.dof_v = Suffix(direction=Suffix.EXPORT)  #: dof_v
     if hasattr(self.lsmhe, "rh_name"):
         self.lsmhe.rh_name.clear()
     else:
         self.lsmhe.rh_name = Suffix(direction=Suffix.IMPORT)  #: Red_hess_name
     if set_suffix:
         for key in self.x_noisy:
             var = getattr(self.lsmhe, key)
             for j in self.x_vars[key]:
                 var[(self.nfe_t, self.ncp_t) + j].set_suffix_value(self.lsmhe.dof_v, 1)
Beispiel #11
0
    def _load_rc(self, vars_to_load=None):
        if not hasattr(self._pyomo_model, 'rc'):
            self._pyomo_model.rc = Suffix(direction=Suffix.IMPORT)
        var_map = self._pyomo_var_to_solver_var_map
        ref_vars = self._referenced_variables
        rc = self._pyomo_model.rc
        if vars_to_load is None:
            vars_to_load = var_map.keys()

        cplex_vars_to_load = [var_map[pyomo_var] for pyomo_var in vars_to_load]
        vals = self._solver_model.solution.get_reduced_costs(cplex_vars_to_load)

        for i, pyomo_var in enumerate(vars_to_load):
            if ref_vars[pyomo_var] > 0:
                rc[pyomo_var] = vals[i]
Beispiel #12
0
    def _load_slacks(self, cons_to_load=None):
        if not hasattr(self._pyomo_model, 'slack'):
            self._pyomo_model.slack = Suffix(direction=Suffix.IMPORT)
        con_map = self._pyomo_con_to_solver_con_map
        reverse_con_map = self._solver_con_to_pyomo_con_map
        slack = self._pyomo_model.slack

        if cons_to_load is None:
            linear_cons_to_load = self._solver_model.linear_constraints.get_names(
            )
            linear_vals = self._solver_model.solution.get_linear_slacks()
            quadratic_cons_to_load = self._solver_model.quadratic_constraints.get_names(
            )
            quadratic_vals = self._solver_model.solution.get_quadratic_slacks()
        else:
            cplex_cons_to_load = set(
                [con_map[pyomo_con] for pyomo_con in cons_to_load])
            linear_cons_to_load = cplex_cons_to_load.intersection(
                set(self._solver_model.linear_constraints.get_names()))
            linear_vals = self._solver_model.solution.get_linear_slacks(
                linear_cons_to_load)
            quadratic_cons_to_load = cplex_cons_to_load.intersection(
                set(self._solver_model.quadratic_constraints.get_names()))
            quadratic_vals = self._solver_model.solution.get_quadratic_slacks(
                quadratic_cons_to_load)

        for i, cplex_con in enumerate(linear_cons_to_load):
            pyomo_con = reverse_con_map[cplex_con]
            if pyomo_con in self._range_constraints:
                R_ = self._solver_model.linear_constraints.get_range_values(
                    cplex_con)
                if R_ == 0:
                    slack[pyomo_con] = linear_vals[i]
                else:
                    Ls_ = linear_vals[i]
                    Us_ = R_ - Ls_
                    if abs(Us_) > abs(Ls_):
                        slack[pyomo_con] = Us_
                    else:
                        slack[pyomo_con] = -Ls_
            else:
                slack[pyomo_con] = linear_vals[i]

        for i, cplex_con in enumerate(quadratic_cons_to_load):
            pyomo_con = reverse_con_map[cplex_con]
            slack[pyomo_con] = quadratic_vals[i]
Beispiel #13
0
    def _apply_to(self, model, **kwds):
        options = kwds.pop('options', {})
        if kwds.get('undo', options.get('undo', False)):
            for v, d in model._relaxed_integer_vars[None].values():
                bounds = v.bounds
                v.domain = d
                v.setlb(bounds[0])
                v.setub(bounds[1])
            model.del_component("_relaxed_integer_vars")
            return
        # True by default, you can specify False if you want
        descend = kwds.get('transform_deactivated_blocks',
                           options.get('transform_deactivated_blocks', True))
        active = None if descend else True

        # Relax the model
        relaxed_vars = {}
        _base_model_vars = model.component_data_objects(Var,
                                                        active=active,
                                                        descend_into=True)
        for var in _base_model_vars:
            if not var.is_integer():
                continue
            # Note: some indexed components can only have their
            # domain set on the parent component (the individual
            # indices cannot be set independently)
            _c = var.parent_component()
            try:
                lb, ub = var.bounds
                _domain = var.domain
                var.domain = Reals
                var.setlb(lb)
                var.setub(ub)
                relaxed_vars[id(var)] = (var, _domain)
            except:
                if id(_c) in relaxed_vars:
                    continue
                _domain = _c.domain
                lb, ub = _c.bounds
                _c.domain = Reals
                _c.setlb(lb)
                _c.setub(ub)
                relaxed_vars[id(_c)] = (_c, _domain)
        model._relaxed_integer_vars = Suffix(direction=Suffix.LOCAL)
        model._relaxed_integer_vars[None] = relaxed_vars
Beispiel #14
0
    def _apply_to(self, model, **kwds):
        options = kwds.pop('options', {})
        if kwds.get('undo', options.get('undo', False)):
            for v in model._fixed_discrete_vars[None]:
                v.unfix()
            model.del_component("_fixed_discrete_vars")
            return

        fixed_vars = []
        _base_model_vars = model.component_data_objects(Var,
                                                        active=True,
                                                        descend_into=True)
        for var in _base_model_vars:
            if var.domain in _discrete_relaxation_map and not var.is_fixed():
                fixed_vars.append(var)
                var.fix()
        model._fixed_discrete_vars = Suffix(direction=Suffix.LOCAL)
        model._fixed_discrete_vars[None] = fixed_vars
Beispiel #15
0
    def _load_duals(self, cons_to_load=None):
        if not hasattr(self._pyomo_model, 'dual'):
            self._pyomo_model.dual = Suffix(direction=Suffix.IMPORT)
        con_map = self._pyomo_con_to_solver_con_map
        reverse_con_map = self._solver_con_to_pyomo_con_map
        dual = self._pyomo_model.dual

        if cons_to_load is None:
            linear_cons_to_load = self._solver_model.linear_constraints.get_names()
            vals = self._solver_model.solution.get_dual_values()
        else:
            cplex_cons_to_load = set([con_map[pyomo_con] for pyomo_con in cons_to_load])
            linear_cons_to_load = cplex_cons_to_load.intersection(set(self._solver_model.linear_constraints.get_names()))
            vals = self._solver_model.solution.get_dual_values(linear_cons_to_load)

        for i, cplex_con in enumerate(linear_cons_to_load):
            pyomo_con = reverse_con_map[cplex_con]
            dual[pyomo_con] = vals[i]
Beispiel #16
0
    def sens_k_aug_nmpc(self):
        self.journalist("I", self._iteration_count, "sens_k_aug_nmpc", "k_aug sensitivity")
        self.olnmpc.ipopt_zL_in.update(self.olnmpc.ipopt_zL_out)
        self.olnmpc.ipopt_zU_in.update(self.olnmpc.ipopt_zU_out)
        self.journalist("I", self._iteration_count, "solve_k_aug_nmpc", self.olnmpc.name)

        if hasattr(self.olnmpc, "f_timestamp"):
            self.olnmpc.f_timestamp.clear()
        else:
            self.olnmpc.f_timestamp = Suffix(direction=Suffix.EXPORT,
                                             datatype=Suffix.INT)

        self.olnmpc.set_suffix_value(self.olnmpc.f_timestamp, self.int_file_nmpc_suf)
        self.olnmpc.f_timestamp.display(ostream=sys.stderr)
        results = self.k_aug_sens.solve(self.olnmpc, tee=True, symbolic_solver_labels=True)
        self.olnmpc.solutions.load_from(results)
        self.olnmpc.f_timestamp.display(ostream=sys.stderr)
        ftimings = open("timings_k_aug.txt", "r")
        s = ftimings.readline()
        ftimings.close()
        self._k_timing = s.split()
Beispiel #17
0
    def _apply_to(self, model, **kwds):
        options = kwds.pop('options', {})
        if kwds.get('undo', options.get('undo', False)):
            for v in model._fixed_discrete_vars[None]:
                v.unfix()
            model.del_component("_fixed_discrete_vars")
            return

        fixed_vars = []
        _base_model_vars = model.component_data_objects(Var,
                                                        active=True,
                                                        descend_into=True)
        for var in _base_model_vars:
            # Instead of checking against `_discrete_relaxation_map.keys()`
            # we just check the item properties to fix #995
            # When #326 has been resolved, we can check against the dict-keys again
            if not var.is_continuous() and not var.is_fixed():
                fixed_vars.append(var)
                var.fix()
        model._fixed_discrete_vars = Suffix(direction=Suffix.LOCAL)
        model._fixed_discrete_vars[None] = fixed_vars
Beispiel #18
0
    def __init__(self, nfe_t, ncp_t, **kwargs):
        ConcreteModel.__init__(self)

        steady = kwargs.pop('steady', False)
        _t = kwargs.pop('_t', 1.0)
        Ntray = kwargs.pop('Ntray', 42)
        # --------------------------------------------------------------------------------------------------------------
        # Orthogonal Collocation Parameters section

        # Radau
        self._alp_gauB_t = 1
        self._bet_gauB_t = 0

        if steady:
            print("[I] " + str(self.__class__.__name__) + " NFE and NCP Overriden - Steady state mode")
            self.nfe_t = 1
            self.ncp_t = 1
        else:
            self.nfe_t = nfe_t
            self.ncp_t = ncp_t

        self.tau_t = collptsgen(self.ncp_t, self._alp_gauB_t, self._bet_gauB_t)

        # start at zero
        self.tau_i_t = {0: 0.}
        # create a list

        for ii in range(1, self.ncp_t + 1):
            self.tau_i_t[ii] = self.tau_t[ii - 1]

        # ======= SETS ======= #
        # For finite element = 1 .. NFE
        # This has to be > 0

        self.fe_t = Set(initialize=[ii for ii in range(1, self.nfe_t + 1)])

        # collocation points
        # collocation points for differential variables
        self.cp_t = Set(initialize=[ii for ii in range(0, self.ncp_t + 1)])
        # collocation points for algebraic variables
        self.cp_ta = Set(within=self.cp_t, initialize=[ii for ii in range(1, self.ncp_t + 1)])

        # create collocation param
        self.taucp_t = Param(self.cp_t, initialize=self.tau_i_t)

        self.ldot_t = Param(self.cp_t, self.cp_t, initialize=
        (lambda m, j, k: lgrdot(k, m.taucp_t[j], self.ncp_t, self._alp_gauB_t, self._bet_gauB_t)))  #: watch out for this!

        self.l1_t = Param(self.cp_t, initialize=
        (lambda m, j: lgr(j, 1, self.ncp_t, self._alp_gauB_t, self._bet_gauB_t)))

        # --------------------------------------------------------------------------------------------------------------
        # Model parameters
        self.Ntray = Ntray
        self.tray = Set(initialize=[i for i in range(1, Ntray + 1)])
        self.feed = Param(self.tray,
                          initialize=lambda m, t: 57.5294 if t == 21 else 0.0,
                          mutable=True)

        self.xf = Param(initialize=0.32, mutable=True)  # feed mole fraction
        self.hf = Param(initialize=9081.3)  # feed enthalpy

        self.hlm0 = Param(initialize=2.6786e-04)
        self.hlma = Param(initialize=-0.14779)
        self.hlmb = Param(initialize=97.4289)
        self.hlmc = Param(initialize=-2.1045e04)

        self.hln0 = Param(initialize=4.0449e-04)
        self.hlna = Param(initialize=-0.1435)
        self.hlnb = Param(initialize=121.7981)
        self.hlnc = Param(initialize=-3.0718e04)

        self.r = Param(initialize=8.3147)
        self.a = Param(initialize=6.09648)
        self.b = Param(initialize=1.28862)
        self.c1 = Param(initialize=1.016)
        self.d = Param(initialize=15.6875)
        self.l = Param(initialize=13.4721)
        self.f = Param(initialize=2.615)

        self.gm = Param(initialize=0.557)
        self.Tkm = Param(initialize=512.6)
        self.Pkm = Param(initialize=8.096e06)

        self.gn = Param(initialize=0.612)
        self.Tkn = Param(initialize=536.7)
        self.Pkn = Param(initialize=5.166e06)

        self.CapAm = Param(initialize=23.48)
        self.CapBm = Param(initialize=3626.6)
        self.CapCm = Param(initialize=-34.29)

        self.CapAn = Param(initialize=22.437)
        self.CapBn = Param(initialize=3166.64)
        self.CapCn = Param(initialize=-80.15)

        self.pstrip = Param(initialize=250)
        self.prect = Param(initialize=190)

        def _p_init(m, t):
            ptray = 9.39e04
            if t <= 20:
                return _p_init(m, 21) + m.pstrip * (21 - t)
            elif 20 < t < m.Ntray:
                return ptray + m.prect * (m.Ntray - t)
            elif t == m.Ntray:
                return 9.39e04

        self.p = Param(self.tray, initialize=_p_init)

        self.T29_des = Param(initialize=343.15)
        self.T15_des = Param(initialize=361.15)
        self.Dset = Param(initialize=1.83728)
        self.Qcset = Param(initialize=1.618890)
        self.Qrset = Param(initialize=1.786050)
        # self.Recset = Param()

        self.alpha_T29 = Param(initialize=1)
        self.alpha_T15 = Param(initialize=1)
        self.alpha_D = Param(initialize=1)
        self.alpha_Qc = Param(initialize=1)
        self.alpha_Qr = Param(initialize=1)
        self.alpha_Rec = Param(initialize=1)

        def _alpha_init(m, i):
            if i <= 21:
                return 0.62
            else:
                return 0.35

        self.alpha = Param(self.tray,
                           initialize=lambda m, t: 0.62 if t <= 21 else 0.35)

        # --------------------------------------------------------------------------------------------------------------
        #: First define differential state variables (state: x, ic-Param: x_ic, derivative-Var:dx_dt
        #: States (differential) section
        zero_tray = dict.fromkeys(self.tray)
        zero3 = dict.fromkeys(self.fe_t * self.cp_t * self.tray)

        for key in zero3.keys():
            zero3[key] = 0.0

        def __m_init(m, i, j, t):
            if t < m.Ntray:
                return 4000.
            elif t == 1:
                return 104340.
            elif t == m.Ntray:
                return 5000.

        #: Liquid hold-up
        self.M = Var(self.fe_t, self.cp_t, self.tray,
                     initialize=__m_init)
        #: Mole-fraction
        self.x = Var(self.fe_t, self.cp_t, self.tray, initialize=lambda m, i, j, t: 0.999 * t / m.Ntray)

        #: Initial state-Param
        self.M_ic = zero_tray if steady else Param(self.tray, initialize=0.0, mutable=True)
        self.x_ic = zero_tray if steady else Param(self.tray, initialize=0.0, mutable=True)

        #:  Derivative-var
        self.dM_dt = zero3 if steady else Var(self.fe_t, self.cp_t, self.tray, initialize=0.0)
        self.dx_dt = zero3 if steady else Var(self.fe_t, self.cp_t, self.tray, initialize=0.0)

        # --------------------------------------------------------------------------------------------------------------
        # States (algebraic) section
        # Tray temperature
        self.T = Var(self.fe_t, self.cp_ta, self.tray,
                     initialize=lambda m, i, j, t: ((370.781 - 335.753) / m.Ntray) * t + 370.781)
        self.Tdot = Var(self.fe_t, self.cp_ta, self.tray, initialize=1e-05)  #: Not really a der_var

        # saturation pressures
        self.pm = Var(self.fe_t, self.cp_ta, self.tray, initialize=1e4)
        self.pn = Var(self.fe_t, self.cp_ta, self.tray, initialize=1e4)

        # Vapor mole flowrate
        self.V = Var(self.fe_t, self.cp_ta, self.tray, initialize=44.0)

        def _l_init(m, i, j, t):
            if 2 <= t <= 21:
                return 83.
            elif 22 <= t <= 42:
                return 23
            elif t == 1:
                return 40

        # Liquid mole flowrate
        self.L = Var(self.fe_t, self.cp_ta, self.tray, initialize=_l_init)

        # Vapor mole frac & diff var
        self.y = Var(self.fe_t, self.cp_ta, self.tray,
                     initialize=lambda m, i, j, t: ((0.99 - 0.005) / m.Ntray) * t + 0.005)

        # Liquid enthalpy    # enthalpy
        self.hl = Var(self.fe_t, self.cp_ta, self.tray, initialize=10000.)

        # Liquid enthalpy    # enthalpy
        self.hv = Var(self.fe_t, self.cp_ta, self.tray, initialize=5e+04)
        # Re-boiler & condenser heat
        self.Qc = Var(self.fe_t, self.cp_ta, initialize=1.6e06)
        self.D = Var(self.fe_t, self.cp_ta, initialize=18.33)
        # vol holdups
        self.Vm = Var(self.fe_t, self.cp_ta, self.tray, initialize=6e-05)

        self.Mv = Var(self.fe_t, self.cp_ta, self.tray,
                      initialize=lambda m, i, j, t: 0.23 if 1 < t < m.Ntray else 0.0)
        self.Mv1 = Var(self.fe_t, self.cp_ta, initialize=8.57)
        self.Mvn = Var(self.fe_t, self.cp_ta, initialize=0.203)

        hi_t = dict.fromkeys(self.fe_t)
        for key in hi_t.keys():
            hi_t[key] = 1.0 if steady else _t/self.nfe_t

        self.hi_t = hi_t if steady else Param(self.fe_t, initialize=hi_t)

        # --------------------------------------------------------------------------------------------------------------
        #: Controls
        self.u1 = Param(self.fe_t, initialize=7.72700925775773761472464684629813E-01, mutable=True)  #: Dummy
        self.u2 = Param(self.fe_t, initialize=1.78604740940007800236344337463379E+06, mutable=True)  #: Dummy

        self.Rec = Var(self.fe_t, initialize=7.72700925775773761472464684629813E-01)
        self.Qr = Var(self.fe_t, initialize=1.78604740940007800236344337463379E+06)

        # --------------------------------------------------------------------------------------------------------------
        #: Constraints for the differential states
        #: Then the ode-Con:de_x, collocation-Con:dvar_t_x, noisy-Expr: noisy_x, cp-Constraint: cp_x, initial-Con: x_icc
        #: Differential equations
        self.de_M = Constraint(self.fe_t, self.cp_ta, self.tray, rule=m_ode)
        self.de_x = Constraint(self.fe_t, self.cp_ta, self.tray, rule=x_ode)

        #: Collocation equations
        self.dvar_t_M = None if steady else Constraint(self.fe_t, self.cp_ta, self.tray, rule=M_COLL)
        self.dvar_t_x = None if steady else Constraint(self.fe_t, self.cp_ta, self.tray, rule=x_coll)

        #: Continuation equations (redundancy here)
        if self.nfe_t > 1:
            #: Noisy expressions
            self.noisy_M = None if steady else Expression(self.fe_t, self.tray, rule=M_CONT)
            self.noisy_x = None if steady else Expression(self.fe_t, self.tray, rule=x_cont)

            #: Continuation equations
            self.cp_M = None if steady else \
                Constraint(self.fe_t, self.tray,
                           rule=lambda m, i, t: self.noisy_M[i, t] == 0.0 if i < self.nfe_t else Constraint.Skip)
            self.cp_x = None if steady else \
                Constraint(self.fe_t, self.tray,
                           rule=lambda m, i, t: self.noisy_x[i, t] == 0.0 if i < self.nfe_t else Constraint.Skip)

        #: Initial condition-Constraints
        self.M_icc = None if steady else Constraint(self.tray, rule=acm)
        self.x_icc = None if steady else Constraint(self.tray, rule=acx)

        # --------------------------------------------------------------------------------------------------------------
        #: Constraint section (algebraic equations)

        self.hrc = Constraint(self.fe_t, self.cp_ta, rule=hrc)
        self.gh = Constraint(self.fe_t, self.cp_ta, self.tray, rule=gh)
        self.ghb = Constraint(self.fe_t, self.cp_ta, rule=ghb)
        self.ghc = Constraint(self.fe_t, self.cp_ta, rule=ghc)
        self.hkl = Constraint(self.fe_t, self.cp_ta, self.tray, rule=hkl)
        self.hkv = Constraint(self.fe_t, self.cp_ta, self.tray, rule=hkv)
        self.lpself = Constraint(self.fe_t, self.cp_ta, self.tray, rule=lpm)
        self.lpn = Constraint(self.fe_t, self.cp_ta, self.tray, rule=lpn)
        self.dp = Constraint(self.fe_t, self.cp_ta, self.tray, rule=dp)
        self.lTdot = Constraint(self.fe_t, self.cp_ta, self.tray, rule=lTdot)
        self.gy0 = Constraint(self.fe_t, self.cp_ta, rule=gy0)
        self.gy = Constraint(self.fe_t, self.cp_ta, self.tray, rule=gy)
        self.dMV = Constraint(self.fe_t, self.cp_ta, self.tray, rule=dMV)
        self.dMv1 = Constraint(self.fe_t, self.cp_ta, rule=dMv1)
        self.dMvn = Constraint(self.fe_t, self.cp_ta, rule=dMvn)
        self.hyd = Constraint(self.fe_t, self.cp_ta, self.tray, rule=hyd)
        self.hyd1 = Constraint(self.fe_t, self.cp_ta, rule=hyd1)
        self.hydN = Constraint(self.fe_t, self.cp_ta, rule=hydN)
        self.dvself = Constraint(self.fe_t, self.cp_ta, self.tray, rule=dvm)

        # --------------------------------------------------------------------------------------------------------------
        #: Control constraint
        self.u1_e = Expression(self.fe_t, rule=lambda m, i: self.Rec[i])
        self.u2_e = Expression(self.fe_t, rule=lambda m, i: self.Qr[i])

        self.u1_c = Constraint(self.fe_t, rule=lambda m, i: self.u1[i] == self.u1_e[i])
        self.u2_c = Constraint(self.fe_t, rule=lambda m, i: self.u2[i] == self.u2_e[i])
        # --------------------------------------------------------------------------------------------------------------
        #: Suffixes
        self.dual = Suffix(direction=Suffix.IMPORT_EXPORT)
        self.ipopt_zL_out = Suffix(direction=Suffix.IMPORT)
        self.ipopt_zU_out = Suffix(direction=Suffix.IMPORT)
        self.ipopt_zL_in = Suffix(direction=Suffix.EXPORT)
        self.ipopt_zU_in = Suffix(direction=Suffix.EXPORT)
Beispiel #19
0
                actual_key.append(int(k))
            actual_key.append(actual_key.pop(0))
            actual_key = tuple(actual_key)

            value = kk[8]
            value = float(value)
            dict[var, actual_key] = value
        except IndexError:
            continue
    file_i.close()
    return dict


file_tst = open("iv_ss.txt", "r")
somedict = parse_ig_ampl(file_tst)
somemodel.ipopt_zL_out = Suffix(direction=Suffix.IMPORT)
somemodel.ipopt_zU_out = Suffix(direction=Suffix.IMPORT)

somemodel.display(filename="somefile0.txt")

for var in somemodel.component_objects(Var, active=True):
    vx = getattr(somemodel, str(var))
    for v, k in var.iteritems():
        # print(str(var), v)
        try:
            vx[v] = somedict[str(var), v]
        except KeyError:
            continue

someresults = solver.solve(somemodel, tee=True)
# somemodel.pprint(filename="pprint.txt")
Beispiel #20
0
#     f.close()
e.find_target_ss()  #: Compute target-steady state (beforehand)

# For ideal nmpc
for i in range(1, 2):
    print(str(i) + "--" * 20, file=sys.stderr)
    print("*" * 100)

    e.solve_d(e.d1)
    e.update_state_real()  # update the current state

    e.cycle_ics(plant_step=True)
    e.plant_input_gen(e.d1, "mod", src=e.ss2)
    # e.plant_input_gen(e.d1, src_kind="dict")

e.d1.dcdp = Suffix(direction=Suffix.EXPORT)
e.d1.var_order = Suffix(direction=Suffix.EXPORT)

e.d1.sens_init_constr = Suffix(direction=Suffix.EXPORT)
small_value = 1e-06
ii = 1
for x in e.states:
    con = getattr(e.d1, x + '_icc')
    con.set_suffix_value(e.d1.sens_init_constr, 1)
    var = getattr(e.d1, x)
    for key in var.keys():
        if key[1] == 0:
            if var[key].stale:
                continue
            setattr(e.d1, "sens_state_" + str(ii),
                    Suffix(direction=Suffix.EXPORT))
Beispiel #21
0
    def GradientsTool(self):
        self.journalizer("E", self._c_it, "GradientsTool", "Begin")
        src = self.d1
        src.dum_objfun = Objective(expr=1, sense=minimize)
        self.d1.var_order = Suffix(direction=Suffix.EXPORT)
        self.d1.con_order = Suffix(direction=Suffix.EXPORT)

        src.pprint(filename="first.txt")
        #: Fix/Deactivate irrelevant stuff
        for var in src.component_objects(Var, active=True):
            if not var.is_indexed():
                var.fix()
            for index in var.keys():
                if type(index) != tuple:
                    var.fix()
                    continue
                try:
                    if index[1] == self.ncp_t:
                        continue
                    var[index].fix()
                except IndexError:
                    var.fix()
                    print("Variable not indexed by time",
                          var.name,
                          file=sys.stderr)
        for con in src.component_objects(Constraint, active=True):
            if not con.is_indexed():
                con.deactivate()
            for index in con.keys():
                if type(index) != tuple:
                    con.deactivate()
                    continue
                try:
                    if index[1] == self.ncp_t:
                        continue
                    con[index].deactivate()
                except IndexError:
                    con.deactivate()
                    print("Constraint not indexed by time",
                          con.name,
                          file=sys.stderr)

        for i in self.states:  #: deactivate collocation related equations
            # con = getattr(src, "cp_" + i)  #: continuation
            # con.deactivate()
            con = getattr(src, "dvar_t_" + i)  #: derivative vars
            con.deactivate()
            con = getattr(src, i + "_icc")  #: initial-conditions
            con.deactivate()
            var = getattr(src, "d" + i + "_dt")
            var.fix()
            var = getattr(src, i)
            var.fix()  #: left with the av
            con = getattr(src, "de_" + i)  #: initial-conditions
            con.deactivate()
        # colcount = 0
        # for i in src.component_data_objects(Var, active=True):
        #     if i.is_fixed():
        #         continue
        #     print(i)
        #     colcount += 1
        #     i.set_suffix_value(src.var_order, colcount)
        # print(colcount)

        self.d1.write_nl(name="dgy.nl")
        sfxdict = dict()
        self.parse_rc("dgy.row", sfxdict)
        colcount = 1
        for ob in sfxdict.keys():
            con = getattr(src, sfxdict[ob][0])
            con[sfxdict[ob][1]].set_suffix_value(src.con_order, colcount)
            colcount += 1

        sfxdict = dict()
        self.parse_rc("dgy.col", sfxdict)
        colcount = 1
        for ob in sfxdict.keys():
            var = getattr(src, sfxdict[ob][0])
            var[sfxdict[ob][1]].set_suffix_value(src.var_order, colcount)
            colcount += 1
        print("Colcount\t", str(colcount), file=sys.stderr)
        src.write_nl(name="dgy.nl")
        #: Now dgx
        for var in src.component_objects(Var):
            var.fix()  #: Fix everything
        for i in self.states:
            var = getattr(src, i)
            for index in var.keys():
                try:
                    if index[1] == self.ncp_t:
                        var[index].unfix()
                except IndexError:
                    print("Something whent wrong :(\t",
                          var.name,
                          file=sys.stderr)

        self.d1.write_nl(name="dgx.nl")

        sfxdict = dict()
        self.parse_rc("dgx.col", sfxdict)
        colcount = 1
        for ob in sfxdict.keys():
            var = getattr(src, sfxdict[ob][0])
            var[sfxdict[ob][1]].set_suffix_value(src.var_order, colcount)
            colcount += 1
        src.write_nl(name="dgx.nl")

        #: Now dfy
        for var in src.component_objects(Var):
            var.unfix()
        for var in src.component_objects(Var):
            if not var.is_indexed():
                var.fix()
            for index in var.keys():
                if type(index) != tuple:
                    var.fix()
                    continue
                try:
                    if index[1] == self.ncp_t:
                        continue
                    var[index].fix()
                except IndexError:
                    var.fix()
                    print("Variable not indexed by time",
                          var.name,
                          file=sys.stderr)

        for con in src.component_objects(Constraint):
            con.deactivate()  #: deactivate everything

        for i in self.states:  #: deactivate collocation related terms
            var = getattr(src, "d" + i + "_dt")
            var.fix()
            var = getattr(src, i)
            var.fix()  #: left with the av
            con = getattr(src, "de_" + i)
            for index in con.keys():
                if index[1] == self.ncp_t:
                    con[index].activate()
        self.d1.reconstruct()
        # self.d1.write_nl(name="dfy.nl")

        sfxdict = dict()
        self.parse_rc("dgx.col", sfxdict)
        colcount = 1
        for ob in sfxdict.keys():
            col = getattr(src, "de_" + sfxdict[ob][0])
            col[sfxdict[ob][1]].set_suffix_value(src.con_order, colcount)
            colcount += 1
        src.write_nl(name="dfy.nl")

        #: Now dfx
        for var in src.component_objects(Var):
            var.fix()  #: Fix everything

        for i in self.states:
            var = getattr(src, i)
            for index in var.keys():
                try:
                    if index[1] == self.ncp_t:
                        var[index].unfix()
                except IndexError:
                    print("Something whent wrong :(\t",
                          var.name,
                          file=sys.stderr)
            # var.pprint()
        self.d1.reconstruct()
        src.pprint(filename="second.txt")
        self.d1.write_nl(name="dfx.nl")
Beispiel #22
0
    def __init__(self, nfe_t, ncp_t, **kwargs):
        #: type: (int, int, dict)
        #: if steady == True fallback to steady-state computation
        self.nfe_t = nfe_t  #:
        self.ncp_t = ncp_t
        self.scheme = kwargs.pop('scheme', 'LAGRANGE-RADAU')
        self.steady = kwargs.pop('steady', False)
        self._t = kwargs.pop('_t', 1.0)
        ncstr = kwargs.pop('n_cstr', 1)
        ConcreteModel.__init__(self)
        self.ncstr = Set(initialize=[i for i in range(0, ncstr)])

        if self.steady:
            self.t = Set(initialize=[1])
        else:
            self.t = ContinuousSet(bounds=(0, self._t))

        self.Cainb = Param(default=1.0)
        self.Tinb = Param(default=275.0)
        self.Tjinb = Param(default=250.0)

        self.V = Param(initialize=100)
        self.UA = Param(initialize=20000 * 60)
        self.rho = Param(initialize=1000)
        self.Cp = Param(initialize=4.2)
        self.Vw = Param(initialize=10)
        self.rhow = Param(initialize=1000)
        self.Cpw = Param(initialize=4.2)
        self.k0 = Param(initialize=4.11e13)
        self.E = Param(initialize=76534.704)
        self.R = Param(initialize=8.314472)
        self.Er = Param(initialize=lambda m: (value(self.E) / value(self.R)))
        self.dH = Param(initialize=596619.)

        self.F = Param(self.t, mutable=True, default=1.2000000000000000E+02)
        self.Fw = Param(self.t, mutable=True, default=3.0000000000000000E+01)

        # States
        self.Ca = Var(self.t, self.ncstr, initialize=1.60659680385930765667001907104350E-02)
        self.T = Var(self.t, self.ncstr, initialize=3.92336059452774350120307644829154E+02)
        self.Tj = Var(self.t, self.ncstr, initialize=3.77995395658401662331016268581152E+02)

        self.k = Var(self.t, self.ncstr, initialize=4.70706140E+02)
        self.kdef = Constraint(self.t, self.ncstr)

        #: These guys have to be zero at the steady-state (steady).
        zero0 = dict.fromkeys(self.t * self.ncstr)
        for key in zero0.keys():
            zero0[key] = 0.0
        if self.steady:
            self.Cadot = zero0
            self.Tdot = zero0
            self.Tjdot = zero0
        else:
            self.Cadot = DerivativeVar(self.Ca, initialize=-3.58709135E+01)
            self.Tdot = DerivativeVar(self.T, initialize=5.19191848E+03)
            self.Tjdot = DerivativeVar(self.Tj, initialize=-9.70467399E+02)
        #: These guys as well (steady).
        self.Ca_ic = Param(self.ncstr, default=1.9193793974995963E-02)
        self.T_ic = Param(self.ncstr, default=3.8400724261199036E+02)
        self.Tj_ic = Param(self.ncstr, default=3.7127352272578315E+02)

        # m.Ca_ic = Param(m.ncstr, default=1.9193793974995963E-02)
        # m.T_ic = Param(m.ncstr, default=3.8400724261199036E+02)
        # m.Tj_ic = Param(m.ncstr, default=3.7127352272578315E+02)

        self.ODE_ca = Constraint(self.t, self.ncstr)
        self.ODE_T = Constraint(self.t, self.ncstr)
        self.ODE_Tj = Constraint(self.t, self.ncstr)

        #: No need of these guys at steady.
        if self.steady:
            self.Ca_icc = None
            self.T_icc = None
            self.Tj_icc = None
        else:
            self.Ca_icc = Constraint(self.ncstr)
            self.T_icc = Constraint(self.ncstr)
            self.Tj_icc = Constraint(self.ncstr)

        def _rule_k(m, i, n):
            if i == 0:
                return Constraint.Skip
            else:
                return m.k[i, n] == m.k0 * exp(-m.Er / m.T[i, n])

        def _rule_ca(m, i, n):
            if i == 0:
                return Constraint.Skip
            else:
                rule = m.Cadot[i, n] == (m.F[i] / m.V) * (m.Cainb - m.Ca[i, n]) - 2 * m.k[i, n] * m.Ca[i, n] ** 2
                return rule

        def _rule_t(m, i, n):
            if i == 0:
                return Constraint.Skip
            else:
                return m.Tdot[i, n] == (m.F[i] / m.V) * (m.Tinb - m.T[i, n]) + \
                2.0 * m.dH / (m.rho * m.Cp) * m.k[i, n] * m.Ca[i, n] ** 2 -\
                m.UA / (m.V * m.rho * m.Cp) * (m.T[i, n] - m.Tj[i, n])

        def _rule_tj(m, i, n):
            if i == 0:
                return Constraint.Skip
            else:
                return m.Tjdot[i, n] == \
                       (m.Fw[i] / m.Vw) * (m.Tjinb - m.Tj[i, n]) + m.UA / (m.Vw * m.rhow * m.Cpw) * (m.T[i, n] - m.Tj[i, n])

        def _rule_ca0(m, n):
            return m.Ca[0, n] == m.Ca_ic[n]

        def _rule_t0(m, n):
            return m.T[0, n] == m.T_ic[n]

        def _rule_tj0(m, n):
            return m.Tj[0, n] == m.Tj_ic[n]

        # let Ca0 := 1.9193793974995963E-02 ;
        # let T0  := 3.8400724261199036E+02 ;
        # let Tj0 := 3.7127352272578315E+02 ;

        self.kdef.rule = lambda m, i, n: _rule_k(m, i, n)
        self.ODE_ca.rule = lambda m, i, n: _rule_ca(m, i, n)
        self.ODE_T.rule = lambda m, i, n: _rule_t(m, i, n)
        self.ODE_Tj.rule = lambda m, i, n: _rule_tj(m, i, n)

        if self.steady:
            pass
        else:
            self.Ca_icc.rule = lambda m, n: _rule_ca0(m, n)
            self.T_icc.rule = lambda m, n: _rule_t0(m, n)
            self.Tj_icc.rule = lambda m, n: _rule_tj0(m, n)
            self.Ca_icc.reconstruct()
            self.T_icc.reconstruct()
            self.Tj_icc.reconstruct()

        self.kdef.reconstruct()
        self.ODE_ca.reconstruct()
        self.ODE_T.reconstruct()
        self.ODE_Tj.reconstruct()


        # Declare at framework level
        self.dual = Suffix(direction=Suffix.IMPORT_EXPORT)
        self.ipopt_zL_out = Suffix(direction=Suffix.IMPORT)
        self.ipopt_zU_out = Suffix(direction=Suffix.IMPORT)
        self.ipopt_zL_in = Suffix(direction=Suffix.EXPORT)
        self.ipopt_zU_in = Suffix(direction=Suffix.EXPORT)

        self.discretizer = TransformationFactory('dae.collocation')