def __init__(self, *args, **kwargs):
     deprecation_warning(
         "DEPRECATED: The PIDBlock model is deprecated and will be removed."
         "Use PIDController instead.",
         version=1.12,
     )
     super().__init__(*args, **kwargs)
Exemple #2
0
    def load(self, arg, namespaces=[None], profile_memory=0, report_timing=None):
        """
        Load the model with data from a file, dictionary or DataPortal object.
        """
        if report_timing is not None:
            deprecation_warning(
                "The report_timing argument to Model.load() is deprecated.  "
                "Use pyomo.common.timing.report_timing() to enable reporting "
                "construction timing")
        if arg is None or isinstance(arg, basestring):
            dp = DataPortal(filename=arg, model=self)
        elif type(arg) is DataPortal:
            dp = arg
        elif type(arg) is dict:
            dp = DataPortal(data_dict=arg, model=self)
        elif isinstance(arg, SolverResults):
            if len(arg.solution):
                logger.warning(
"""DEPRECATION WARNING: the Model.load() method is deprecated for
loading solutions stored in SolverResults objects.  Call
Model.solutions.load_from().""")
                self.solutions.load_from(arg)
            else:
                logger.warning(
"""DEPRECATION WARNING: the Model.load() method is deprecated for
loading solutions stored in SolverResults objects.  By default, results
from solvers are immediately loaded into the original model instance.""")
            return
        else:
            msg = "Cannot load model model data from with object of type '%s'"
            raise ValueError(msg % str( type(arg) ))
        self._load_model_data(dp,
                              namespaces,
                              profile_memory=profile_memory)
Exemple #3
0
    def load(self, arg, namespaces=[None], profile_memory=0, report_timing=None):
        """
        Load the model with data from a file, dictionary or DataPortal object.
        """
        if report_timing is not None:
            deprecation_warning(
                "The report_timing argument to Model.load() is deprecated.  "
                "Use pyomo.common.timing.report_timing() to enable reporting "
                "construction timing")
        if arg is None or isinstance(arg, basestring):
            dp = DataPortal(filename=arg, model=self)
        elif type(arg) is DataPortal:
            dp = arg
        elif type(arg) is dict:
            dp = DataPortal(data_dict=arg, model=self)
        elif isinstance(arg, SolverResults):
            if len(arg.solution):
                logger.warning(
"""DEPRECATION WARNING: the Model.load() method is deprecated for
loading solutions stored in SolverResults objects.  Call
Model.solutions.load_from().""")
                self.solutions.load_from(arg)
            else:
                logger.warning(
"""DEPRECATION WARNING: the Model.load() method is deprecated for
loading solutions stored in SolverResults objects.  By default, results
from solvers are immediately loaded into the original model instance.""")
            return
        else:
            msg = "Cannot load model model data from with object of type '%s'"
            raise ValueError(msg % str( type(arg) ))
        self._load_model_data(dp,
                              namespaces,
                              profile_memory=profile_memory)
Exemple #4
0
    def __init__(self,
                 substitute=None,
                 descend_into_named_expressions=True,
                 remove_named_expressions=True):
        if substitute is None:
            substitute = {}
        # Note: preserving the attribute names from the previous
        # implementation of the expression walker.
        self.substitute = substitute
        self.enter_named_expr = descend_into_named_expressions
        self.rm_named_expr = remove_named_expressions

        kwds = {}
        if hasattr(self, 'visiting_potential_leaf'):
            deprecation_warning(
                "ExpressionReplacementVisitor: this walker has been ported "
                "to derive from StreamBasedExpressionVisitor.  "
                "visiting_potential_leaf() has been replaced by beforeChild()"
                "(note to implementers: the sense of the bool return value "
                "has been inverted).",
                version='6.2')

            def beforeChild(node, child, child_idx):
                is_leaf, ans = self.visiting_potential_leaf(child)
                return not is_leaf, ans

            kwds['beforeChild'] = beforeChild

        if hasattr(self, 'visit'):
            raise DeveloperError(
                "ExpressionReplacementVisitor: this walker has been ported "
                "to derive from StreamBasedExpressionVisitor.  "
                "overriding visit() has no effect (and is likely to generate "
                "invalid expression trees)")
        super().__init__(**kwds)
Exemple #5
0
def target_list(x):
    deprecation_msg = ("In future releases ComponentUID targets will no "
                      "longer be supported in the core.add_slack_variables "
                      "transformation. Specify targets as a Constraint or "
                      "list of Constraints.")
    if isinstance(x, ComponentUID):
        if deprecation_msg:
            deprecation_warning(deprecation_msg)
            # only emit the message once
            deprecation_msg = None
        # [ESJ 07/15/2020] We have to just pass it through because we need the
        # instance in order to be able to do anything about it...
        return [ x ]
    elif isinstance(x, (Constraint, _ConstraintData)):
        return [ x ]
    elif hasattr(x, '__iter__'):
        ans = []
        for i in x:
            if isinstance(i, ComponentUID):
                if deprecation_msg:
                    deprecation_warning(deprecation_msg)
                    deprecation_msg = None
                # same as above...
                ans.append(i)
            elif isinstance(i, (Constraint, _ConstraintData)):
                ans.append(i)
            else:
                raise ValueError(
                    "Expected Constraint or list of Constraints."
                    "\n\tRecieved %s" % (type(i),))
        return ans
    else:
        raise ValueError(
            "Expected Constraint or list of Constraints."
            "\n\tRecieved %s" % (type(x),))
 def __init__(self, *args, **kwargs):
     deprecation_warning(
         "DEPRECATED: The idaes.power_generation.control.pid_controller.PIDController"
         " model is deprecated and will be removed. Use"
         " idaes.generic_models.control.PIDController instead.",
         version=1.12,
     )
     super().__init__(*args, **kwargs)
Exemple #7
0
def xsequence(*args):
    from pyomo.common.deprecation import deprecation_warning
    deprecation_warning(
        "The xsequence function is deprecated.  Use the sequence() "
        "function, which returns a generator.",
        version='5.5.1',
        remove_in='6.0')
    return sequence(*args)
Exemple #8
0
    def __new__(cls, *args, **kwds):
        if cls != Model:
            return super(Model, cls).__new__(cls)

        deprecation_warning(
            "Using the 'Model' class is deprecated.  Please use the "
            "AbstractModel or ConcreteModel class instead.",
            version='4.3.11323')
        return AbstractModel.__new__(AbstractModel)
Exemple #9
0
    def __nonzero__(self):
        if _using_chained_inequality and not self.is_constant():    #pragma: no cover
            deprecation_warning("Chained inequalities are deprecated. "
                                "Use the inequality() function to "
                                "express ranged inequality expressions.")     # Remove in Pyomo 6.0
            _chainedInequality.call_info = traceback.extract_stack(limit=2)[-2]
            _chainedInequality.prev = self
            return True
            #return bool(self())                # This is needed to apply simple evaluation of inequalities

        return bool(self())
Exemple #10
0
 def __contains__(self, val):
     if val not in Reals:
         deprecation_warning(
             "The default domain for Param objects is 'Any'.  However, "
             "we will be changing that default to 'Reals' in the "
             "future.  If you really intend the domain of this Param (%s) "
             "to be 'Any', you can suppress this warning by explicitly "
             "specifying 'within=Any' to the Param constructor."
             % ('Unknown' if self._owner is None else self._owner().name,),
             version='5.6.9', remove_in='6.0')
     return True
Exemple #11
0
def alias(name, doc=None, subclass=None):
    if subclass is not None:
        deprecation_warning(
            "The Pyomo plugin infrastructure alias() function does "
            "not support the subclass flag.", version='6.0')
    calling_frame = inspect.currentframe().f_back
    locals_ = calling_frame.f_locals
    #
    # Some sanity checks
    #
    assert locals_ is not calling_frame.f_globals and '__module__' in locals_, \
        'implements() can only be used in a class definition'
    #
    locals_.setdefault('__plugin_aliases__', []).append((name, doc))
Exemple #12
0
def list_of_phase_types(arg):
    '''Domain validator for lists of PhaseTypes

    Args:
        arg : argument to be cast to list of PhaseTypes and validated

    Returns:
        List of PhaseTypes
    '''
    deprecation_warning(
        "The list_of_phase_types function is deprecated.  Use the "
        "ListOf(PhaseType) validator from pyomo.common.config instead.",
        version='1.11', remove_in='1.13')

    return ListOf(PhaseType)(arg)
Exemple #13
0
 def __contains__(self, val):
     if val not in Reals:
         if self._owner is None or self._owner() is None:
             name = 'Unknown'
         else:
             name = self._owner().name
         deprecation_warning(
             f"Param '{name}' declared with an implicit domain of 'Any'. "
             "The default domain for Param objects is 'Any'.  However, "
             "we will be changing that default to 'Reals' in the "
             "future.  If you really intend the domain of this Param"
             "to be 'Any', you can suppress this warning by explicitly "
             "specifying 'within=Any' to the Param constructor.",
             version='5.6.9', remove_in='6.0')
     return True
Exemple #14
0
def list_of_floats(arg):
    '''Domain validator for lists of floats

    Args:
        arg : argument to be cast to list of floats and validated

    Returns:
        List of floats
    '''
    deprecation_warning(
        "The list_of_floats function is deprecated.  Use the ListOf(float) "
        "validator from pyomo.common.config instead.", version='1.11',
        remove_in='1.13')

    return ListOf(float)(arg)
Exemple #15
0
 def _resolve_tempdir(self, dir=None):
     if dir is not None:
         return dir
     elif self.tempdir is not None:
         return self.tempdir
     elif self.manager().tempdir is not None:
         return self.manager().tempdir
     elif pyutilib_mngr is not None and pyutilib_mngr.tempdir is not None:
         deprecation_warning(
             "The use of the PyUtilib TempfileManager.tempdir "
             "to specify the default location for Pyomo "
             "temporary files has been deprecated.  "
             "Please set TempfileManager.tempdir in "
             "pyomo.common.tempfiles",
             version='5.7.2')
         return pyutilib_mngr.tempdir
     return None
Exemple #16
0
    def as_binary(self):
        """Return the binary variable associated with this Boolean variable.

        This method returns the associated binary variable along with a
        deprecation warning about using the Boolean variable in a numeric
        context.

        """
        deprecation_warning(
            "Implicit conversion of the Boolean indicator_var '%s' to a "
            "binary variable is deprecated and will be removed.  "
            "Either express constraints on indicator_var using "
            "LogicalConstraints or work with the associated binary "
            "variable from indicator_var.get_associated_binary()" %
            (self.name, ),
            version='6.0')
        return self.get_associated_binary()
Exemple #17
0
    def transform(self, name=None, **kwds):
        if name is None:
            deprecation_warning(
                "Use the TransformationFactory iterator to get the list "
                "of known transformations.", version='4.3.11323')
            return list(TransformationFactory)

        deprecation_warning(
            "Use TransformationFactory('%s') to construct a transformation "
            "object, or TransformationFactory('%s').apply_to(model) to "
            "directly apply the transformation to the model instance." % (
                name,name,), version='4.3.11323')

        xfrm = TransformationFactory(name)
        if xfrm is None:
            raise ValueError("Unknown model transformation '%s'" % name)
        return xfrm.apply_to(self, **kwds)
Exemple #18
0
def implements(interface, inherit=None, namespace=None, service=False):
    if namespace is not None:
        deprecation_warning(
            "The Pyomo plugin infrastructure only supports a "
            "single global namespace.", version='6.0')
    calling_frame = inspect.currentframe().f_back
    locals_ = calling_frame.f_locals
    #
    # Some sanity checks
    #
    assert locals_ is not calling_frame.f_globals and '__module__' in locals_, \
        'implements() can only be used in a class definition'
    assert issubclass(interface, Interface)
    #
    locals_.setdefault('__implements__', []).append(
        (interface, inherit, service)
    )
Exemple #19
0
    def __call__(self):
        deprecation_warning(
            "Relying on core.logical_to_linear to transform "
            "BooleanVars that do not appear in LogicalConstraints "
            "is deprecated. Please associate your own binaries if "
            "you have BooleanVars not used in logical expressions.",
            version='6.2')

        parent_block = self._boolvar().parent_block()
        new_var = Var(domain=Binary)
        parent_block.add_component(
            unique_component_name(parent_block,
                                  self._boolvar().local_name + "_asbinary"),
            new_var)
        self._boolvar()._associated_binary = None
        self._boolvar().associate_binary_var(new_var)
        return new_var
Exemple #20
0
    def create_tempfile(self, suffix=None, prefix=None, text=False, dir=None):
        """Create a unique temporary file

        Returns the absolute path of a temporary filename that is
        guaranteed to be unique.  This function generates the file and
        returns the filename.

        """
        if suffix is None:
            suffix = ''
        if prefix is None:
            prefix = 'tmp'
        if dir is None:
            dir = self.tempdir
            if dir is None and pyutilib_mngr is not None:
                dir = pyutilib_mngr.tempdir
                if dir is not None:
                    deprecation_warning(
                        "The use of the PyUtilib TempfileManager.tempdir "
                        "to specify the default location for Pyomo "
                        "temporary files has been deprecated.  "
                        "Please set TempfileManager.tempdir in "
                        "pyomo.common.tempfiles",
                        version='5.7.2')

        ans = tempfile.mkstemp(suffix=suffix,
                               prefix=prefix,
                               text=text,
                               dir=dir)
        ans = list(ans)
        if not os.path.isabs(ans[1]):  #pragma:nocover
            fname = os.path.join(dir, ans[1])
        else:
            fname = ans[1]
        os.close(ans[0])
        if self._ctr >= 0:
            new_fname = os.path.join(dir, prefix + str(self._ctr) + suffix)
            # Delete any file having the sequential name and then
            # rename
            if os.path.exists(new_fname):
                os.remove(new_fname)
            shutil.move(fname, new_fname)
            fname = new_fname
            self._ctr += 1
        self._tempfiles[-1].append(fname)
        return fname
Exemple #21
0
    def test_deprecation_warning(self):
        DEP_OUT = StringIO()
        with LoggingIntercept(DEP_OUT, 'pyomo'):
            deprecation_warning(None, version='1.2', remove_in='3.4')

        self.assertIn('DEPRECATED: This has been deprecated',
                      DEP_OUT.getvalue())
        self.assertIn('(deprecated in 1.2, will be removed in (or after) 3.4)',
                      DEP_OUT.getvalue().replace('\n',' '))

        DEP_OUT = StringIO()
        with LoggingIntercept(DEP_OUT, 'pyomo'):
            deprecation_warning("custom message here", version='1.2', remove_in='3.4')

        self.assertIn('DEPRECATED: custom message here',
                      DEP_OUT.getvalue())
        self.assertIn('(deprecated in 1.2, will be removed in (or after) 3.4)',
                      DEP_OUT.getvalue().replace('\n',' '))
Exemple #22
0
    def getname(self,
                fully_qualified=False,
                name_buffer=None,
                relative_to=None):
        """Returns the component name associated with this object.

        Parameters
        ----------
        fully_qualified: bool
            Generate full name from nested block names

        relative_to: Block
            Generate fully_qualified names reletive to the specified block.
        """
        local_name = self._name
        if fully_qualified:
            pb = self.parent_block()
            if relative_to is None:
                relative_to = self.model()
            if pb is not None and pb is not relative_to:
                ans = pb.getname(fully_qualified, name_buffer, relative_to) \
                      + "." + name_repr(local_name)
            elif pb is None and relative_to != self.model():
                raise RuntimeError(
                    "The relative_to argument was specified but not found "
                    "in the block hierarchy: %s" % str(relative_to))
            else:
                ans = name_repr(local_name)
        else:
            # Note: we want "getattr(x.parent_block(), x.local_name) == x"
            # so we do not want to call _safe_name_str, as that could
            # add quotes or otherwise escape the string.
            ans = local_name
        if name_buffer is not None:
            deprecation_warning(
                "The 'name_buffer' argument to getname is deprecated. "
                "The functionality is no longer necessary since getting names "
                "is no longer a quadratic operation. Additionally, note that "
                "use of this argument poses risks if the buffer contains "
                "names relative to different Blocks in the model hierarchy or "
                "a mixture of local and fully_qualified names.",
                version='TODO')
            name_buffer[id(self)] = ans
        return ans
Exemple #23
0
    def create_tempdir(self, suffix=None, prefix=None, dir=None):
        """Create a unique temporary directory

        Returns the absolute path of a temporary directory that is
        guaranteed to be unique.  This function generates the directory
        and returns the directory name.

        """
        if suffix is None:
            suffix = ''
        if prefix is None:
            prefix = 'tmp'
        if dir is None:
            dir = self.tempdir
            if dir is None and pyutilib_mngr is not None:
                dir = pyutilib_mngr.tempdir
                if dir is not None:
                    deprecation_warning(
                        "The use of the PyUtilib TempfileManager.tempdir "
                        "to specify the default location for Pyomo "
                        "temporary directories has been deprecated.  "
                        "Please set TempfileManager.tempdir in "
                        "pyomo.common.tempfiles",
                        version='5.7.2')

        dirname = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir)
        if self._tempfiles[-1].ctr >= 0:
            new_dirname = os.path.join(
                os.path.dirname(dirname),
                prefix + str(self._tempfiles[-1].ctr) + suffix)
            # Delete any directory having the sequential name and then
            # rename
            if os.path.exists(new_dirname):
                shutil.rmtree(new_dirname)
            shutil.move(dirname, new_dirname)
            dirname = new_dirname
            self._tempfiles[-1].ctr += 1

        self._tempfiles[-1].append(dirname)
        return dirname
Exemple #24
0
    def __init__(self, **kwds):
        # This is slightly tricky: We want derived classes to be able to
        # override the "None" defaults here, and for keyword arguments
        # to override both.  The hasattr check prevents the "None"
        # defaults from overriding attributes or methods defined on
        # derived classes.
        for field in self.client_methods:
            if field in kwds:
                setattr(self, field, kwds.pop(field))
            elif not hasattr(self, field):
                setattr(self, field, None)
        if kwds:
            raise RuntimeError("Unrecognized keyword arguments: %s" % (kwds, ))

        # Handle deprecated APIs
        _fcns = (('beforeChild', 2), ('acceptChildResult', 3), ('afterChild',
                                                                2))
        for name, nargs in _fcns:
            fcn = getattr(self, name)
            if fcn is None:
                continue
            _args = inspect.getfullargspec(fcn)
            _self_arg = 1 if inspect.ismethod(fcn) else 0
            if len(_args.args) == nargs + _self_arg and _args.varargs is None:
                deprecation_warning(
                    "Note that the API for the StreamBasedExpressionVisitor "
                    "has changed to include the child index for the %s() "
                    "method.  Please update your walker callbacks." % (name, ),
                    version='5.7.0')

                def wrap(fcn, nargs):
                    def wrapper(*args):
                        return fcn(*args[:nargs])

                    return wrapper

                setattr(self, name, wrap(fcn, nargs))
Exemple #25
0
from pyomo.common.deprecation import deprecation_warning

try:
    deprecation_warning("The use of pyomo.contrib.simple model is deprecated. "  
                        "This capability is now supported in the "
                        "pyomo_simplemodel package, which is included in the "
                        "pyomo_community distribution.", version='TBD', 
                        remove_in='TBD')
    from pyomocontrib_simplemodel import *
except:
    # Only raise exception if nose is NOT running
    import sys
    if 'nose' not in sys.modules and 'nose2' not in sys.modules:
        raise RuntimeError(
            "The pyomocontrib_simplemodel package is not installed.")
Exemple #26
0
    def _apply_to_impl(self, instance, **kwds):
        config = self.CONFIG(kwds.pop('options', {}))

        # We will let args override suffixes and estimate as a last
        # resort. More specific args/suffixes override ones anywhere in
        # the tree. Suffixes lower down in the tree override ones higher
        # up.
        if 'default_bigM' in kwds:
            deprecation_warning("the 'default_bigM=' argument has been "
                                "replaced by 'bigM='", version='5.4')
            config.bigM = kwds.pop('default_bigM')

        config.set_value(kwds)
        bigM = config.bigM
        self.assume_fixed_vars_permanent = config.assume_fixed_vars_permanent

        targets = config.targets
        if targets is None:
            targets = (instance, )
        # We need to check that all the targets are in fact on instance. As we
        # do this, we will use the set below to cache components we know to be
        # in the tree rooted at instance.
        knownBlocks = {}
        for t in targets:
            # check that t is in fact a child of instance
            if not is_child_of(parent=instance, child=t,
                               knownBlocks=knownBlocks):
                raise GDP_Error(
                    "Target '%s' is not a component on instance '%s'!"
                    % (t.name, instance.name))
            elif t.ctype is Disjunction:
                if t.is_indexed():
                    self._transform_disjunction(t, bigM)
                else:
                    self._transform_disjunctionData( t, bigM, t.index())
            elif t.ctype in (Block, Disjunct):
                if t.is_indexed():
                    self._transform_block(t, bigM)
                else:
                    self._transform_blockData(t, bigM)
            else:
                raise GDP_Error(
                    "Target '%s' was not a Block, Disjunct, or Disjunction. "
                    "It was of type %s and can't be transformed."
                    % (t.name, type(t)))

        # issue warnings about anything that was in the bigM args dict that we
        # didn't use
        if bigM is not None:
            unused_args = ComponentSet(bigM.keys()) - \
                          ComponentSet(self.used_args.keys())
            if len(unused_args) > 0:
                warning_msg = ("Unused arguments in the bigM map! "
                               "These arguments were not used by the "
                               "transformation:\n")
                for component in unused_args:
                    if hasattr(component, 'name'):
                        warning_msg += "\t%s\n" % component.name
                    else:
                        warning_msg += "\t%s\n" % component
                logger.warning(warning_msg)
Exemple #27
0
from pyomo.common.deprecation import deprecation_warning
deprecation_warning(
    'The pyomo.gdp.plugins.chull module is deprecated.  '
    'Import the Hull reformulation objects from pyomo.gdp.plugins.hull.',
    version='5.7')

from .hull import _Deprecated_Name_Hull as ConvexHull_Transformation
Exemple #28
0
    def create_instance(self,
                        filename=None,
                        data=None,
                        name=None,
                        namespace=None,
                        namespaces=None,
                        profile_memory=0,
                        report_timing=False,
                        **kwds):
        """
        Create a concrete instance of an abstract model, possibly using data
        read in from a file.

        Parameters
        ----------
        filename: `str`, optional           
            The name of a Pyomo Data File that will be used to load data into 
            the model.
        data: `dict`, optional
            A dictionary containing initialization data for the model to be 
            used if there is no filename
        name: `str`, optional
            The name given to the model.
        namespace: `str`, optional          
            A namespace used to select data.
        namespaces: `list`, optional   
            A list of namespaces used to select data.
        profile_memory: `int`, optional    
            A number that indicates the profiling level.
        report_timing: `bool`, optional     
            Report timing statistics during construction.

        """
        #
        # Generate a warning if this is a concrete model but the
        # filename is specified.  A concrete model is already
        # constructed, so passing in a data file is a waste of time.
        #
        if self.is_constructed() and isinstance(filename, str):
            msg = "The filename=%s will not be loaded - supplied as an " \
                  "argument to the create_instance() method of a "\
                  "concrete instance with name=%s." % (filename, name)
            logger.warning(msg)

        if 'clone' in kwds:
            kwds.pop('clone')
            deprecation_warning(
                "Model.create_instance() no longer accepts the 'clone' "
                "argument: the base abstract model is always cloned.",
                version='5.4')
        if 'preprocess' in kwds:
            kwds.pop('preprocess')
            deprecation_warning(
                "Model.create_instance() no longer accepts the preprocess' "
                "argument: preprocessing is always deferred to when the "
                "model is sent to the solver",
                version='5.4')
        if kwds:
            msg = \
"""Model.create_instance() passed the following unrecognized keyword
arguments (which have been ignored):"""
            for k in kwds:
                msg = msg + "\n    '%s'" % (k, )
            logger.error(msg)

        if self.is_constructed():
            deprecation_warning(
                "Cannot call Model.create_instance() on a constructed "
                "model; returning a clone of the current model instance.",
                version='5.4')
            return self.clone()

        if report_timing:
            timing.report_timing()

        if name is None:
            # Preserve only the local name (not the FQ name, as that may
            # have been quoted or otherwise escaped)
            name = self.local_name
        if filename is not None:
            if data is not None:
                logger.warning(
                    "Model.create_instance() passed both 'filename' "
                    "and 'data' keyword arguments.  Ignoring the "
                    "'data' argument")
            data = filename
        if data is None:
            data = {}

        #
        # Clone the model and load the data
        #
        instance = self.clone()

        if name is not None:
            instance._name = name

        # If someone passed a rule for creating the instance, fire the
        # rule before constructing the components.
        if instance._rule is not None:
            instance._rule(instance, next(iter(self.index_set())))

        if namespaces:
            _namespaces = list(namespaces)
        else:
            _namespaces = []
        if namespace is not None:
            _namespaces.append(namespace)
        if None not in _namespaces:
            _namespaces.append(None)

        instance.load(data,
                      namespaces=_namespaces,
                      profile_memory=profile_memory)

        #
        # Indicate that the model is concrete/constructed
        #
        instance._constructed = True
        #
        # Change this class from "Abstract" to "Concrete".  It is
        # absolutely crazy that this is allowed in Python, but since the
        # AbstractModel and ConcreteModel are basically identical, we
        # can "reassign" the new concrete instance to be an instance of
        # ConcreteModel
        #
        instance.__class__ = ConcreteModel
        return instance
Exemple #29
0
    def create_instance( self, filename=None, data=None, name=None,
                         namespace=None, namespaces=None,
                         profile_memory=0, report_timing=False,
                         **kwds ):
        """
        Create a concrete instance of an abstract model, possibly using data
        read in from a file.

        Parameters
        ----------
        filename: `str`, optional           
            The name of a Pyomo Data File that will be used to load data into 
            the model.
        data: `dict`, optional
            A dictionary containing initialization data for the model to be 
            used if there is no filename
        name: `str`, optional
            The name given to the model.
        namespace: `str`, optional          
            A namespace used to select data.
        namespaces: `list`, optional   
            A list of namespaces used to select data.
        profile_memory: `int`, optional    
            A number that indicates the profiling level.
        report_timing: `bool`, optional     
            Report timing statistics during construction.

        """
        #
        # Generate a warning if this is a concrete model but the
        # filename is specified.  A concrete model is already
        # constructed, so passing in a data file is a waste of time.
        #
        if self.is_constructed() and isinstance(filename, string_types):
            msg = "The filename=%s will not be loaded - supplied as an " \
                  "argument to the create_instance() method of a "\
                  "concrete instance with name=%s." % (filename, name)
            logger.warning(msg)

        if 'clone' in kwds:
            kwds.pop('clone')
            deprecation_warning(
                "Model.create_instance() no longer accepts the 'clone' "
                "argument: the base abstract model is always cloned.")
        if 'preprocess' in kwds:
            kwds.pop('preprocess')
            deprecation_warning(
                "Model.create_instance() no longer accepts the preprocess' "
                "argument: preprocessing is always deferred to when the "
                "model is sent to the solver")
        if kwds:
            msg = \
"""Model.create_instance() passed the following unrecognized keyword
arguments (which have been ignored):"""
            for k in kwds:
                msg = msg + "\n    '%s'" % (k,)
            logger.error(msg)

        if self.is_constructed():
            deprecation_warning(
                "Cannot call Model.create_instance() on a constructed "
                "model; returning a clone of the current model instance.")
            return self.clone()

        if report_timing:
            pyomo.common.timing.report_timing()

        if name is None:
            name = self.name
        if filename is not None:
            if data is not None:
                logger.warning("Model.create_instance() passed both 'filename' "
                               "and 'data' keyword arguments.  Ignoring the "
                               "'data' argument")
            data = filename
        if data is None:
            data = {}

        #
        # Clone the model and load the data
        #
        instance = self.clone()

        if name is not None:
            instance._name = name

        # If someone passed a rule for creating the instance, fire the
        # rule before constructing the components.
        if instance._rule is not None:
            instance._rule(instance)

        if namespaces:
            _namespaces = list(namespaces)
        else:
            _namespaces = []
        if namespace is not None:
            _namespaces.append(namespace)
        if None not in _namespaces:
            _namespaces.append(None)

        instance.load( data,
                       namespaces=_namespaces,
                       profile_memory=profile_memory )

        #
        # Preprocess the new model
        #

        if False and preprocess is True:

            if report_timing is True:
                start_time = time.time()

            instance.preprocess()

            if report_timing is True:
                total_time = time.time() - start_time
                print("      %6.2f seconds required for preprocessing" % total_time)

            if (pympler_available is True) and (profile_memory >= 2):
                mem_used = muppy.get_size(muppy.get_objects())
                print("      Total memory = %d bytes following instance preprocessing" % mem_used)
                print("")

            if (pympler_available is True) and (profile_memory >= 2):
                print("")
                print("      Summary of objects following instance preprocessing")
                post_preprocessing_summary = summary.summarize(muppy.get_objects())
                summary.print_(post_preprocessing_summary, limit=100)

        #
        # Indicate that the model is concrete/constructed
        #
        instance._constructed = True
        #
        # Change this class from "Abstract" to "Concrete".  It is
        # absolutely crazy that this is allowed in Python, but since the
        # AbstractModel and ConcreteModel are basically identical, we
        # can "reassign" the new concrete instance to be an instance of
        # ConcreteModel
        #
        instance.__class__ = ConcreteModel
        return instance
Exemple #30
0
def xsequence(*args):
    from pyomo.common.deprecation import deprecation_warning
    deprecation_warning("The xsequence function is deprecated.  Use the sequence() function, which returns a generator.")  # Remove in Pyomo 6.0
    return sequence(*args)
Exemple #31
0
#  ___________________________________________________________________________
#
#  Pyomo: Python Optimization Modeling Objects
#  Copyright (c) 2008-2022
#  National Technology and Engineering Solutions of Sandia, LLC
#  Under the terms of Contract DE-NA0003525 with National Technology and
#  Engineering Solutions of Sandia, LLC, the U.S. Government retains certain
#  rights in this software.
#  This software is distributed under the 3-clause BSD License.
#  ___________________________________________________________________________

from pyomo.common.collections import ComponentMap
from pyomo.common.deprecation import deprecation_warning

deprecation_warning(
    'The pyomo.core.kernel.component_map module is deprecated.  '
    'Import ComponentMap from pyomo.common.collections.',
    version='5.7.1')
Exemple #32
0
#  Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC
#  Under the terms of Contract DE-NA0003525 with National Technology and
#  Engineering Solutions of Sandia, LLC, the U.S. Government retains certain
#  rights in this software.
#  This software is distributed under the 3-clause BSD License.
#  ___________________________________________________________________________

# TODO
# . rename 'filter' to something else
# . confirm that filtering is efficient

__all__ = ['Set', 'set_options', 'simple_set_rule', 'SetOf']

from .set import (
    process_setarg,
    set_options,
    simple_set_rule,
    _SetDataBase,
    _SetData,
    Set,
    SetOf,
    IndexedSet,
)

from pyomo.common.deprecation import deprecation_warning

deprecation_warning(
    'The pyomo.core.base.sets module is deprecated.  '
    'Import Set objects from pyomo.core.base.set or pyomo.core.',
    version='5.7')
Exemple #33
0
#  ___________________________________________________________________________
#
#  Pyomo: Python Optimization Modeling Objects
#  Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC
#  Under the terms of Contract DE-NA0003525 with National Technology and
#  Engineering Solutions of Sandia, LLC, the U.S. Government retains certain
#  rights in this software.
#  This software is distributed under the 3-clause BSD License.
#  ___________________________________________________________________________

__all__ = ['RangeSet']

from .set import RangeSet

from pyomo.common.deprecation import deprecation_warning

deprecation_warning(
    'The pyomo.core.base.rangeset module is deprecated.  '
    'Import RangeSet objects from pyomo.core.base.set or pyomo.core.',
    version='TBD')