Beispiel #1
0
    def test_report_timing(self):
        # Create a set to ensure that the global sets have already been
        # constructed (this is an issue until the new set system is
        # merged in and the GlobalSet objects are not automatically
        # created by pyomo.core
        m = ConcreteModel()
        m.x = Var([1,2])

        ref = """
           0 seconds to construct Block ConcreteModel; 1 index total
           0 seconds to construct RangeSet r; 1 index total
           0 seconds to construct Var x; 2 indicies total
""".strip()

        os = StringIO()
        try:
            report_timing(os)
            m = ConcreteModel()
            m.r = RangeSet(2)
            m.x = Var(m.r)
            self.assertEqual(os.getvalue().strip(), ref)
        finally:
            report_timing(False)
        buf = StringIO()
        with LoggingIntercept(buf, 'pyomo'):
            m = ConcreteModel()
            m.r = RangeSet(2)
            m.x = Var(m.r)
            self.assertEqual(os.getvalue().strip(), ref)
            self.assertEqual(buf.getvalue().strip(), "")
Beispiel #2
0
    def test_report_timing(self):
        # Create a set to ensure that the global sets have already been
        # constructed (this is an issue until the new set system is
        # merged in and the GlobalSet objects are not automatically
        # created by pyomo.core
        m = ConcreteModel()
        m.x = Var([1,2])

        ref = r"""
           (0(\.\d+)?) seconds to construct Block ConcreteModel; 1 index total
           (0(\.\d+)?) seconds to construct RangeSet FiniteSimpleRangeSet; 1 index total
           (0(\.\d+)?) seconds to construct Var x; 2 indices total
           (0(\.\d+)?) seconds to construct Suffix Suffix; 1 index total
           (0(\.\d+)?) seconds to apply Transformation RelaxIntegerVars \(in-place\)
           """.strip()

        xfrm = TransformationFactory('core.relax_integer_vars')

        try:
            with capture_output() as out:
                report_timing()
                m = ConcreteModel()
                m.r = RangeSet(2)
                m.x = Var(m.r)
                xfrm.apply_to(m)
            result = out.getvalue().strip()
            self.maxDiff = None
            for l, r in zip(result.splitlines(), ref.splitlines()):
                self.assertRegex(str(l.strip()), str(r.strip()))
        finally:
            report_timing(False)

        os = StringIO()
        try:
            report_timing(os)
            m = ConcreteModel()
            m.r = RangeSet(2)
            m.x = Var(m.r)
            xfrm.apply_to(m)
            result = os.getvalue().strip()
            self.maxDiff = None
            for l, r in zip(result.splitlines(), ref.splitlines()):
                self.assertRegex(str(l.strip()), str(r.strip()))
        finally:
            report_timing(False)
        buf = StringIO()
        with LoggingIntercept(buf, 'pyomo'):
            m = ConcreteModel()
            m.r = RangeSet(2)
            m.x = Var(m.r)
            xfrm.apply_to(m)
            result = os.getvalue().strip()
            self.maxDiff = None
            for l, r in zip(result.splitlines(), ref.splitlines()):
                self.assertRegex(str(l.strip()), str(r.strip()))
            self.assertEqual(buf.getvalue().strip(), "")
Beispiel #3
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
Beispiel #4
0
    opt.set_instance(m)
    p_values = list(range(1, 31))
    obj_values = list()
    for p in p_values:
        m.P.value = p
        opt.remove_constraint(m.num_warehouses)
        opt.add_constraint(m.num_warehouses)
        res = opt.solve(save_results=False)
        assert_optimal_termination(res)
        obj_values.append(res.problem.lower_bound)


# @:parametric_persistent

# @report_timing:
report_timing()
print('Building model')
print('--------------')
m = create_warehouse_model(num_locations=200, num_customers=200)
# @:report_timing

# @report_timing_with_lin_expr:
print('Building model with LinearExpression')
print('------------------------------------')
m = create_warehouse_linear_expr(num_locations=200, num_customers=200)
# @:report_timing_with_lin_expr

report_timing(False)

# @tic_toc_timer:
timer = TicTocTimer()