Exemple #1
0
class InitMidpoint(IsomorphicTransformation):
    """Initializes non-fixed variables to the midpoint of their bounds.

    - If the variable does not have bounds, set the value to zero.
    - If the variable is missing one bound, set the value to that of the
        existing bound.
    """

    alias('contrib.init_vars_midpoint',
          doc=textwrap.fill(textwrap.dedent(__doc__.strip())))

    def _apply_to(self, instance, overwrite=False):
        """Apply the transformation.

        Kwargs:
            overwrite: if False, transformation will not overwrite existing
                variable values.
        """
        for var in instance.component_data_objects(ctype=Var,
                                                   descend_into=True):
            if var.fixed:
                continue
            if var.value is not None and not overwrite:
                continue
            if var.lb is None and var.ub is None:
                # If LB and UB do not exist, set variable value to 0
                var.set_value(0)
            elif var.lb is None:
                # if one bound does not exist, set variable value to the other
                var.set_value(value(var.ub))
            elif var.ub is None:
                # if one bound does not exist, set variable value to the other
                var.set_value(value(var.lb))
            else:
                var.set_value((value(var.lb) + value(var.ub)) / 2.)
Exemple #2
0
class InitZero(IsomorphicTransformation):
    """Initializes non-fixed variables to zeros.

    - If setting the variable value to zero will violate a bound, set the
      variable value to the relevant bound value.

    """

    alias(
        'contrib.init_vars_zero',
        doc=textwrap.fill(textwrap.dedent(__doc__.strip())))

    def _apply_to(self, instance, overwrite=False):
        """Apply the transformation.

        Kwargs:
            overwrite: if False, transformation will not overwrite existing
                variable values.
        """
        for var in instance.component_data_objects(
                ctype=Var, descend_into=True):
            if var.fixed:
                continue
            if var.value is not None and not overwrite:
                continue
            if var.lb is not None and value(var.lb) > 0:
                var.set_value(value(var.lb))
            elif var.ub is not None and value(var.ub) < 0:
                var.set_value(value(var.ub))
            else:
                var.set_value(0)
Exemple #3
0
class sqlite3_db_Table(db_Table):

    alias('sqlite3', "sqlite3 database interface")

    def __init__(self):
        db_Table.__init__(self)
        self.using = 'sqlite3'

    def available(self):
        return sqlite3_available

    def requirements(self):
        return 'sqlite3'

    def connect(self, connection, options):
        assert (options['using'] == 'sqlite3')

        filename = connection
        if not os.path.exists(filename):
            raise Exception("No such file: " + filename)

        con = sqlite3.connect(filename)
        if options.text_factory:
            con.text_factory = options.text_factory
        return con
Exemple #4
0
class MockGLPK(GLPKSHELL_old, MockMIP):
    """A Mock GLPK solver used for testing
    """

    alias('_mock_glpk')

    def __init__(self, **kwds):
        try:
            GLPKSHELL_old.__init__(self, **kwds)
        except ApplicationError:  #pragma:nocover
            pass  #pragma:nocover
        MockMIP.__init__(self, "glpk")

    def available(self, exception_flag=True):
        return GLPKSHELL_old.available(self, exception_flag)

    def create_command_line(self, executable, problem_files):
        command = GLPKSHELL_old.create_command_line(self, executable,
                                                    problem_files)
        MockMIP.create_command_line(self, executable, problem_files)
        return command

    def executable(self):
        return MockMIP.executable(self)

    def _execute_command(self, cmd):
        return MockMIP._execute_command(self, cmd)

    def _convert_problem(self, args, pformat, valid_pformats):
        if pformat in [ProblemFormat.mps, ProblemFormat.cpxlp]:
            return (args, pformat, None)
        else:
            return (args, ProblemFormat.cpxlp, None)
Exemple #5
0
class FixDiscreteVars(Transformation):

    alias('core.fix_discrete',
          doc="Fix known discrete domains to continuous counterparts")

    def __init__(self):
        super(FixDiscreteVars, self).__init__()

    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
Exemple #6
0
class TrustRegionSolver(plugin.Plugin):
    """
    A trust region filter method for black box / glass box optimizaiton
    Solves nonlinear optimization problems containing external function calls
    through automatic construction of reduced models (ROM), also known as
    surrogate models.
    Currently implements linear and quadratic reduced models.
    See Eason, Biegler (2016) AIChE Journal for more details

    Arguments:
    """
    #    + param.CONFIG.generte_yaml_template()

    plugin.implements(IOptSolver)
    plugin.alias(
        'trustregion',
        doc='Trust region filter method for black box/glass box optimization')

    def available(self, exception_flag=True):
        """Check if solver is available.

        TODO: For now, it is always available. However, sub-solvers may not
        always be available, and so this should reflect that possibility.

        """
        return True

    def version(self):
        """Return a 3-tuple describing the solver version."""
        return __version__

    def solve(self, model, eflist, **kwds):
        assert not kwds
        #config = param.CONFIG(kwds)
        return TRF(model, eflist)  #, config)
Exemple #7
0
class HACK_GDP_Var_Mover(Transformation):
    """Move indicator vars to top block.

    HACK: this will move all indicator variables on the model to the top block
    so the writers can find them.

    """

    alias('gdp.varmover', doc=textwrap.fill(textwrap.dedent(__doc__.strip())))

    @deprecated(msg="The gdp.varmover transformation has been deprecated in "
                "favor of the gdp.reclassify transformation.")
    def _apply_to(self, instance, **kwds):
        assert not kwds
        count = 0
        disjunct_generator = instance.component_data_objects(
            Disjunct, descend_into=(Block, Disjunct))
        for disjunct in disjunct_generator:
            count += 1
            var = disjunct.indicator_var
            var.doc = "%s(Moved from %s)" % (
                var.doc + " " if var.doc else "",
                var.name,
            )
            disjunct.del_component(var)
            instance.add_component("_gdp_moved_IV_%s" % (count, ), var)
class TightenContraintFromVars(IsomorphicTransformation):
    """Tightens upper and lower bound on constraints based on variable bounds.

    Iterates through each variable and tightens the constraint bounds using
    the inferred values from the variable bounds.

    For now, this only operates on linear constraints.

    """

    alias('core.tighten_constraints_from_vars',
          doc=textwrap.fill(textwrap.dedent(__doc__.strip())))

    def _apply_to(self, instance):
        for constr in instance.component_data_objects(ctype=Constraint,
                                                      active=True,
                                                      descend_into=True):
            repn = generate_standard_repn(constr.body)
            if not repn.is_linear():
                continue

            # tighten the constraint bound as much as possible
            LB = UB = 0
            if repn.constant:
                LB = UB = repn.constant
            # loop through each coefficent and variable pair
            for i, coef in enumerate(repn.linear_coefs):
                # TODO: Rounding issues
                # Calculate bounds using interval arithmetic
                if coef >= 0:
                    if repn.linear_vars[i].has_ub():
                        UB = UB + coef * value(repn.linear_vars[i].ub)
                    else:
                        UB = float('Inf')
                    if repn.linear_vars[i].has_lb():
                        LB = LB + coef * value(repn.linear_vars[i].lb)
                    else:
                        LB = float('-Inf')
                else:
                    # coef is negative, so signs switch
                    if repn.linear_vars[i].has_lb():
                        UB = UB + coef * value(repn.linear_vars[i].lb)
                    else:
                        LB = float('-Inf')
                    if repn.linear_vars[i].has_ub():
                        LB = LB + coef * value(repn.linear_vars[i].ub)
                    else:
                        UB = float('Inf')

            # if inferred bound is tighter, replace bound
            new_ub = min(value(constr.upper), UB) if constr.has_ub() else UB
            new_lb = max(value(constr.lower), LB) if constr.has_lb() else LB
            constr.set_value((new_lb, constr.body, new_ub))

            if UB < LB:
                logger.error("Infeasible variable bounds: "
                             "Constraint %s has inferred LB %s > UB %s" %
                             (constr.name, new_lb, new_ub))
class ZeroSumPropagator(IsomorphicTransformation):
    """Propagates fixed-to-zero for sums of only positive (or negative) vars.

    If :math:`z` is fixed to zero and :math:`z = x_1 + x_2 + x_3` and
    :math:`x_1`, :math:`x_2`, :math:`x_3` are all non-negative or all
    non-positive, then :math:`x_1`, :math:`x_2`, and :math:`x_3` will be fixed
    to zero.

    """

    alias('contrib.propagate_zero_sum',
          doc=textwrap.fill(textwrap.dedent(__doc__.strip())))

    def _apply_to(self, instance):
        for constr in instance.component_data_objects(ctype=Constraint,
                                                      active=True,
                                                      descend_into=True):
            if not constr.body.polynomial_degree() == 1:
                continue  # constraint not linear. Skip.

            repn = generate_standard_repn(constr.body)
            if (constr.has_ub()
                    and ((repn.constant is None and value(constr.upper) == 0)
                         or repn.constant == value(constr.upper))):
                # term1 + term2 + term3 + ... <= 0
                # all var terms need to be non-negative
                if all(
                        # variable has 0 coefficient
                        coef == 0 or
                        # variable is non-negative and has non-negative coefficient
                    (repn.linear_vars[i].has_lb()
                     and value(repn.linear_vars[i].lb) >= 0 and coef >= 0) or
                        # variable is non-positive and has non-positive coefficient
                    (repn.linear_vars[i].has_ub()
                     and value(repn.linear_vars[i].ub) <= 0 and coef <= 0)
                        for i, coef in enumerate(repn.linear_coefs)):
                    for i, coef in enumerate(repn.linear_coefs):
                        if not coef == 0:
                            repn.linear_vars[i].fix(0)
                    continue
            if (constr.has_lb()
                    and ((repn.constant is None and value(constr.lower) == 0)
                         or repn.constant == value(constr.lower))):
                # term1 + term2 + term3 + ... >= 0
                # all var terms need to be non-positive
                if all(
                        # variable has 0 coefficient
                        coef == 0 or
                        # variable is non-negative and has non-positive coefficient
                    (repn.linear_vars[i].has_lb()
                     and value(repn.linear_vars[i].lb) >= 0 and coef <= 0) or
                        # variable is non-positive and has non-negative coefficient
                    (repn.linear_vars[i].has_ub()
                     and value(repn.linear_vars[i].ub) <= 0 and coef >= 0)
                        for i, coef in enumerate(repn.linear_coefs)):
                    for i, coef in enumerate(repn.linear_coefs):
                        if not coef == 0:
                            repn.linear_vars[i].fix(0)
Exemple #10
0
class CSVTable(TableData):

    alias("csv", "CSV file interface")

    def __init__(self):
        TableData.__init__(self)

    def open(self):
        if self.filename is None:  #pragma:nocover
            raise IOError("No filename specified")

    def close(self):
        self.FILE.close()

    def read(self):
        from pyomo.core.base.param import Param
        if not os.path.exists(self.filename):  #pragma:nocover
            raise IOError("Cannot find file '%s'" % self.filename)
        self.FILE = open(self.filename, 'r')
        tmp = []
        for tokens in csv.reader(self.FILE):
            if tokens != ['']:
                tmp.append(tokens)
        self.FILE.close()
        if len(tmp) == 0:
            raise IOError("Empty *.csv file")
        elif len(tmp) == 1:
            if not self.options.param is None:
                if type(self.options.param) in (list, tuple):
                    p = self.options.param[0]
                else:
                    p = self.options.param
                if isinstance(p, Param):
                    self.options.model = p.model()
                    p = p.local_name
                self._info = ["param", p, ":=", tmp[0][0]]
            elif len(self.options.symbol_map) == 1:
                self._info = [
                    "param",
                    self.options.symbol_map[self.options.symbol_map.keys()[0]],
                    ":=", tmp[0][0]
                ]
            else:
                raise IOError(
                    "Data looks like a parameter, but multiple parameter names have been specified: %s"
                    % str(self.options.symbol_map))
        else:
            self._set_data(tmp[0], tmp[1:])

    def write(self, data):
        if self.options.set is None and self.options.param is None:
            raise IOError("Unspecified model component")
        self.FILE = open(self.filename, 'w')
        table = self._get_table()
        writer = csv.writer(self.FILE)
        writer.writerows(table)
        self.FILE.close()
Exemple #11
0
class phboundextension(SingletonPlugin, _PHBoundExtensionImpl):

    implements(phextension.IPHExtension)

    alias("phboundextension")

    def __init__(self):

        _PHBoundExtensionImpl.__init__(self)
Exemple #12
0
class FixedVarDetector(IsomorphicTransformation):
    """Detects variables that are de-facto fixed but not considered fixed.

    For each variable :math:`v` found on the model, check to see if its lower
    bound :math:`v^{LB}` is within some tolerance of its upper bound
    :math:`v^{UB}`. If so, fix the variable to the value of :math:`v^{LB}`.

    Keyword arguments below are specified for the ``apply_to`` and
    ``create_using`` functions.

    """

    CONFIG = ConfigBlock("FixedVarDetector")
    CONFIG.declare(
        "tmp",
        ConfigValue(
            default=False,
            domain=bool,
            description="True to store the set of transformed variables and "
            "their old values so that they can be restored."))
    CONFIG.declare(
        "tolerance",
        ConfigValue(default=1E-13,
                    domain=NonNegativeFloat,
                    description="tolerance on bound equality (LB == UB)"))

    __doc__ = add_docstring_list(__doc__, CONFIG)

    alias('contrib.detect_fixed_vars',
          doc=textwrap.fill(textwrap.dedent(__doc__.strip())))

    def _apply_to(self, instance, **kwargs):
        config = self.CONFIG(kwargs)

        if config.tmp:
            instance._xfrm_detect_fixed_vars_old_values = ComponentMap()

        for var in instance.component_data_objects(ctype=Var,
                                                   descend_into=True):
            if var.fixed or var.lb is None or var.ub is None:
                # if the variable is already fixed, or if it is missing a
                # bound, we skip it.
                continue
            if fabs(value(var.lb) - value(var.ub)) <= config.tolerance:
                if config.tmp:
                    instance._xfrm_detect_fixed_vars_old_values[var] = \
                        var.value
                var.fix(var.lb)

    def revert(self, instance):
        """Revert variables fixed by the transformation."""
        for var, var_value in iteritems(
                instance._xfrm_detect_fixed_vars_old_values):
            var.unfix()
            var.set_value(var_value)

        del instance._xfrm_detect_fixed_vars_old_values
Exemple #13
0
class TestSolver2(pyomo.opt.OptSolver):

    alias('stest2')

    def __init__(self, **kwds):
        kwds['type'] = 'stest_type'
        pyomo.opt.OptSolver.__init__(self,**kwds)

    def enabled(self):
        return False
Exemple #14
0
class StandardForm(IsomorphicTransformation):
    """
    Produces a standard-form representation of the model. This form has 
    the coefficient matrix (A), the cost vector (c), and the
    constraint vector (b), where the 'standard form' problem is

    min/max c'x
    s.t.    Ax = b
            x >= 0

    Options
        slack_names         Default auxiliary_slack
        excess_names        Default auxiliary_excess
        lb_names            Default _lower_bound
        up_names            Default _upper_bound
        pos_suffix          Default _plus
        neg_suffix          Default _neg
    """

    alias("core.standard_form",
          doc="Create an equivalent LP model in standard form.")

    def __init__(self, **kwds):
        kwds['name'] = "standard_form"
        super(StandardForm, self).__init__(**kwds)

    def _create_using(self, model, **kwds):
        """
        Tranform a model to standard form
        """

        # Optional naming schemes to pass to EqualityTransform
        eq_kwds = {}
        eq_kwds["slack_names"] = kwds.pop("slack_names", "auxiliary_slack")
        eq_kwds["excess_names"] = kwds.pop("excess_names", "auxiliary_excess")
        eq_kwds["lb_names"] = kwds.pop("lb_names", "_lower_bound")
        eq_kwds["ub_names"] = kwds.pop("ub_names", "_upper_bound")

        # Optional naming schemes to pass to NonNegativeTransformation
        nn_kwds = {}
        nn_kwds["pos_suffix"] = kwds.pop("pos_suffix", "_plus")
        nn_kwds["neg_suffix"] = kwds.pop("neg_suffix", "_minus")

        nonneg = NonNegativeTransformation()
        equality = EqualityTransform()

        # Since NonNegativeTransform introduces new constraints
        # (that aren't equality constraints) we call it first.
        #
        # EqualityTransform introduces new variables, but they are
        # constrainted to be nonnegative.
        sf = nonneg(model, **nn_kwds)
        sf = equality(sf, **eq_kwds)

        return sf
Exemple #15
0
class Xfrm_PyomoTransformation(Transformation):

    alias('contrib.example.xfrm',
          doc="An example of a transformation in a pyomo.contrib package")

    def __init__(self):
        super(Xfrm_PyomoTransformation, self).__init__()

    def create_using(self, instance, **kwds):
        # This transformation doesn't do anything...
        return instance
Exemple #16
0
class SolverManager_Serial(AsynchronousSolverManager):

    alias("serial", doc="Synchronously execute solvers locally")

    def clear(self):
        """
        Clear manager state
        """
        super(SolverManager_Serial, self).clear()
        self.results = OrderedDict()

    def _perform_queue(self, ah, *args, **kwds):
        """
        Perform the queue operation.  This method returns the ActionHandle,
        and the ActionHandle status indicates whether the queue was successful.
        """

        opt = kwds.pop('solver', kwds.pop('opt', None))
        if opt is None:
            raise ActionManagerError(
                "No solver passed to %s, use keyword option 'solver'" %
                (type(self).__name__))

        time_start = time.time()
        if isinstance(opt, string_types):
            with pyomo.opt.SolverFactory(opt) as _opt:
                results = _opt.solve(*args, **kwds)
        else:
            results = opt.solve(*args, **kwds)
        results.pyomo_solve_time = time.time() - time_start

        self.results[ah.id] = results
        ah.status = ActionStatus.done
        self.event_handle[ah.id].update(ah)

        return ah

    def _perform_wait_any(self):
        """
        Perform the wait_any operation.  This method returns an
        ActionHandle with the results of waiting.  If None is returned
        then the ActionManager assumes that it can call this method again.
        Note that an ActionHandle can be returned with a dummy value,
        to indicate an error.
        """
        if len(self.results) > 0:
            ah_id, result = self.results.popitem(last=False)
            self.results[ah_id] = result
            return self.event_handle[ah_id]
        return ActionHandle(error=True,
                            explanation=("No queued evaluations available in "
                                         "the 'serial' solver manager, which "
                                         "executes solvers synchronously"))
Exemple #17
0
class pymysql_db_Table(db_Table):

    alias('pymysql', "pymysql database interface")

    def __init__(self):
        db_Table.__init__(self)
        self.using = 'pymysql'

    def available(self):
        return pymysql_available

    def requirements(self):
        return 'pymysql'
Exemple #18
0
class PyomoDataCommands(Plugin):

    alias("dat", "Pyomo data command file interface")

    implements(IDataManager, service=False)

    def __init__(self):
        self._info = []
        self.options = Options()

    def available(self):
        return True

    def initialize(self, **kwds):
        self.filename = kwds.pop('filename')
        self.add_options(**kwds)

    def add_options(self, **kwds):
        self.options.update(kwds)

    def open(self):
        if self.filename is None:               #pragma:nocover
            raise IOError("No filename specified")
        if not os.path.exists(self.filename):   #pragma:nocover
            raise IOError("Cannot find file '%s'" % self.filename)

    def close(self):
        pass

    def read(self):
        """
        This function does nothing, since executing Pyomo data commands
        both reads and processes the data all at once.
        """
        pass

    def write(self, data):                      #pragma:nocover
        """
        This function does nothing, because we cannot write to a *.dat file.
        """
        pass

    def process(self, model, data, default):
        """
        Read Pyomo data commands and process the data.
        """
        _process_include(['include', self.filename], model, data, default, self.options)

    def clear(self):
        self._info = []
Exemple #19
0
    class SheetTable_xls(SheetTable):

        alias("xls", "Excel XLS file interface")

        def __init__(self):
            if win32com_available and _excel_available:
                SheetTable.__init__(self, ctype='win32com')
            else:
                SheetTable.__init__(self, ctype='xlrd')

        def available(self):
            return win32com_available or xlrd_available

        def requirements(self):
            return "win32com or xlrd"
Exemple #20
0
    class SheetTable_xlsm(SheetTable):

        alias("xlsm", "Excel XLSM file interface")

        def __init__(self):
            if win32com_available and _excel_available:
                SheetTable.__init__(self, ctype='win32com')
            else:
                SheetTable.__init__(self, ctype='openpyxl')

        def available(self):
            return win32com_available or openpyxl_available

        def requirements(self):
            return "win32com or openpyxl"
Exemple #21
0
    class SheetTable_xlsm(pyodbc_db_base):

        alias("xlsm", "Excel XLSM file interface")

        def __init__(self):
            pyodbc_db_base.__init__(self)

        def requirements(self):
            return "pyodbc or pypyodbc"

        def open(self):
            if self.filename is None:
                raise IOError("No filename specified")
            if not os.path.exists(self.filename):
                raise IOError("Cannot find file '%s'" % self.filename)
            return pyodbc_db_base.open(self)
Exemple #22
0
class InducedLinearity(IsomorphicTransformation):
    """Reformulate nonlinear constraints with induced linearity.

    Finds continuous variables :math:`v` where :math:`v = d_1 + d_2 + d_3`,
    where :math:`d`'s are discrete variables. These continuous variables may
    participate nonlinearly in other expressions, which may then be induced to
    be linear.

    The overall algorithm flow can be summarized as:

    1. Detect effectively discrete variables and the constraints that
       imply discreteness.
    2. Determine the set of valid values for each effectively discrete variable
    3. Find nonlinear expressions in which effectively discrete variables
       participate.
    4. Reformulate nonlinear expressions appropriately.

    .. note:: Tasks 1 & 2 must incorporate scoping considerations (Disjuncts)

    Keyword arguments below are specified for the ``apply_to`` and
    ``create_using`` functions.

    """

    CONFIG = ConfigBlock("contrib.induced_linearity")
    CONFIG.declare(
        'equality_tolerance',
        ConfigValue(default=1E-6,
                    domain=NonNegativeFloat,
                    description="Tolerance on equality constraints."))
    CONFIG.declare(
        'pruning_solver',
        ConfigValue(default='glpk',
                    description="Solver to use when pruning possible values."))

    __doc__ = add_docstring_list(__doc__, CONFIG)

    alias('contrib.induced_linearity',
          doc=textwrap.fill(textwrap.dedent(__doc__.strip())))

    def _apply_to(self, model, **kwds):
        """Apply the transformation to the given model."""
        config = self.CONFIG(kwds.pop('options', {}))
        config.set_value(kwds)
        _process_container(model, config)
        _process_subcontainers(model, config)
Exemple #23
0
class RemoveZeroTerms(IsomorphicTransformation):
    """Looks for 0 * var in a constraint and removes it.

    Currently limited to processing linear constraints of the form x1 = 0 *
    x3, occurring as a result of x2.fix(0).

    TODO: support nonlinear expressions

    """

    alias(
        'contrib.remove_zero_terms',
        doc=textwrap.fill(textwrap.dedent(__doc__.strip())))

    def _apply_to(self, model):
        """Apply the transformation."""
        m = model

        for constr in m.component_data_objects(
                ctype=Constraint, active=True, descend_into=True):
            if not constr.body.polynomial_degree() == 1:
                continue  # we currently only process linear constraints
            repn = generate_standard_repn(constr.body)

            # get the index of all nonzero coefficient variables
            nonzero_vars_indx = [
                i for i, _ in enumerate(repn.linear_vars)
                if not repn.linear_coefs[i] == 0
            ]
            const = repn.constant

            # reconstitute the constraint, including only variable terms with
            # nonzero coefficients
            constr_body = quicksum(repn.linear_coefs[i] * repn.linear_vars[i]
                                   for i in nonzero_vars_indx) + const
            if constr.equality:
                constr.set_value(constr_body == constr.upper)
            elif constr.has_lb() and not constr.has_ub():
                constr.set_value(constr_body >= constr.lower)
            elif constr.has_ub() and not constr.has_lb():
                constr.set_value(constr_body <= constr.upper)
            else:
                # constraint is a bounded inequality of form a <= x <= b.
                constr.set_value(EXPR.inequality(
                    constr.lower, constr_body, constr.upper))
Exemple #24
0
class pypyodbc_db_Table(pyodbc_db_Table):

    alias('pypyodbc', "%s database interface" % 'pypyodbc')

    def __init__(self):
        pyodbc_db_Table.__init__(self)
        self.using = 'pypyodbc'

    def available(self):
        return pypyodbc_available

    def requirements(self):
        return 'pypyodbc'

    def connect(self, connection, options):
        assert (options['using'] == 'pypyodbc')

        return pyodbc_db_Table.connect(self, connection, options)
Exemple #25
0
class RelaxDiscreteVars(Transformation):

    alias('core.relax_discrete',
          doc="Relax known discrete domains to continuous counterparts")

    def __init__(self):
        super(RelaxDiscreteVars, self).__init__()

    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
Exemple #26
0
class HACK_GDP_Disjunct_Reclassifier(Transformation):
    """Reclassify Disjuncts to Blocks.

    HACK: this will reclassify all Disjuncts to Blocks so the current writers
    can find the variables

    """

    alias('gdp.reclassify',
          doc=textwrap.fill(textwrap.dedent(__doc__.strip())))

    def _apply_to(self, instance, **kwds):
        assert not kwds
        disjunct_generator = instance.component_objects(
            Disjunct, descend_into=(Block, Disjunct))
        for disjunct_component in disjunct_generator:
            for disjunct in itervalues(disjunct_component._data):
                if disjunct.active:
                    logger.error("""
                    Reclassifying active Disjunct "%s" as a Block.  This
                    is generally an error as it indicates that the model
                    was not completely relaxed before applying the
                    gdp.reclassify transformation""" % (disjunct.name, ))

            # Reclassify this disjunct as a block
            disjunct_component.parent_block().reclassify_component_type(
                disjunct_component, Block)
            disjunct_component._activate_without_unfixing_indicator()

            # Deactivate all constraints.  Note that we only need to
            # descend into blocks: we will catch disjuncts in the outer
            # loop.
            #
            # Note that we defer this until AFTER we reactivate the
            # block, as the component_objects generator will not
            # return anything when active=True and the block is
            # deactivated.
            for disjunct in itervalues(disjunct_component._data):
                cons_in_disjunct = disjunct.component_objects(
                    Constraint, descend_into=Block, active=True)
                for con in cons_in_disjunct:
                    con.deactivate()
Exemple #27
0
class ResultsReader_json(results.AbstractResultsReader):
    """
    Class that reads in a *.jsn file and generates a
    SolverResults object.
    """

    alias(str(ResultsFormat.json))

    def __init__(self):
        results.AbstractResultsReader.__init__(self, ResultsFormat.json)

    def __call__(self, filename, res=None, soln=None, suffixes=[]):
        """
        Parse a *.results file
        """
        if res is None:
            res = SolverResults()
        #
        res.read(filename, using_yaml=False)
        return res
Exemple #28
0
class MPEC3_Transformation(Transformation):

    alias('mpec.standard_form', doc="Standard reformulation of complementarity condition")

    def __init__(self):
        super(MPEC3_Transformation, self).__init__()

    def _apply_to(self, instance, **kwds):
        options = kwds.pop('options', {})
        #
        # Iterate over the model finding Complementarity components
        #
        for block in instance.block_data_objects(active=True, sort=SortComponents.deterministic):
            for complementarity in block.component_objects(Complementarity, active=True, descend_into=False):
                for index in sorted(iterkeys(complementarity)):
                    _data = complementarity[index]
                    if not _data.active:
                        continue
                    _data.to_standard_form()
                    #
                block.reclassify_component_type(complementarity, Block)
Exemple #29
0
class admm(SingletonPlugin, _AdaptiveRhoBase):

    implements(phextension.IPHExtension)

    alias("admm")

    def __init__(self):
        _AdaptiveRhoBase.__init__(self)

    def pre_ph_initialization(self, ph):
        _AdaptiveRhoBase.pre_ph_initialization(self, ph)

    def post_instance_creation(self, ph):
        _AdaptiveRhoBase.post_instance_creation(self, ph)

    def post_ph_initialization(self, ph):
        _AdaptiveRhoBase.post_ph_initialization(self, ph)

    def post_iteration_0_solves(self, ph):
        _AdaptiveRhoBase.post_iteration_0_solves(self, ph)

    def post_iteration_0(self, ph):
        _AdaptiveRhoBase.post_iteration_0(self, ph)

    def pre_iteration_k_solves(self, ph):
        _AdaptiveRhoBase.pre_iteration_k_solves(self, ph)

    def post_iteration_k_solves(self, ph):
        _AdaptiveRhoBase.post_iteration_k_solves(self, ph)

    def post_iteration_k(self, ph):
        _AdaptiveRhoBase.post_iteration_k(self, ph)

    def ph_convergence_check(self, ph):
        return _AdaptiveRhoBase.ph_convergence_check(self, ph)

    def post_ph_execution(self, ph):
        _AdaptiveRhoBase.post_ph_execution(self, ph)
Exemple #30
0
class GJHSolver(ASL):
    """An interface to the AMPL GJH "solver" for evaluating a model at a
    point."""

    plugin.implements(IOptSolver)
    plugin.alias(
        'contrib.gjh', doc='Interface to the AMPL GJH "solver"')

    def __init__(self, **kwds):
        kwds['type'] = 'gjh'
        kwds['symbolic_solver_labels'] = True
        super(GJHSolver, self).__init__(**kwds)
        self.options.solver = 'gjh'
        self._metasolver = False

    # A hackish way to hold on to the model so that we can parse the
    # results.
    def _initialize_callbacks(self, model):
        self._model = model
        self._model._gjh_info = None
        super(GJHSolver, self)._initialize_callbacks(model)

    def _presolve(self, *args, **kwds):
        super(GJHSolver, self)._presolve(*args, **kwds)
        self._gjh_file = self._soln_file[:-3]+'gjh'
        TempfileManager.add_tempfile(self._gjh_file, exists=False)

    def _postsolve(self):
        #
        # TODO: We should return the information using a better data
        # structure (ComponentMap? so that the GJH solver does not need
        # to be called with symbolic_solver_labels=True
        #
        self._model._gjh_info = readgjh(self._gjh_file)
        self._model = None
        return super(GJHSolver, self)._postsolve()