Exemplo n.º 1
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.util.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)
Exemplo n.º 2
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.

        Optional:
            filename:           The name of a Pyomo Data File that will be used
                                    to load data into the model.
            data:               A dictionary containing initialization data for
                                    the model to be used if there is no filename
            name:               The name given to the model.
            namespace:          A namespace used to select data.
            namespaces:         A list of namespaces used to select data.
            profile_memory:     A number that indicates the profiling level.
            report_timing:      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.util.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
Exemplo n.º 3
0
def xsequence(*args):
    from pyomo.util.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)