How to use the gpkit.constraints.set.ConstraintSet function in gpkit

To help you get started, we’ve selected a few gpkit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github convexengineering / gpkit / gpkit / constraints / linked.py View on Github external
"Implements LinkedConstraintSet"
from .set import ConstraintSet
from ..varkey import VarKey
from .. import SignomialsEnabled


class LinkedConstraintSet(ConstraintSet):
    """A ConstraintSet that links duplicate variables in its constraints

    VarKeys with the same `.str_without(["models"])` are linked.

    The new linking varkey will have the same attributes as the first linked
    varkey of that name, without any value, models, or modelnums.

    If any of the constraints have a substitution for a linked varkey,
    the linking varkey will have that substitution as well; if more than one
    linked varkey has a substitution a ValueError will be raised.

    Arguments
    ---------
    constraints: iterable
        valid argument to ConstraintSet
github convexengineering / gpkit / gpkit / constraints / bounded.py View on Github external
def __init__(self, constraints, *, verbosity=1,
                 eps=1e-30, lower=None, upper=None):
        if not isinstance(constraints, ConstraintSet):
            constraints = ConstraintSet(constraints)
        self.verbosity = verbosity
        self.lowerbound = lower if (lower or upper) else eps
        self.upperbound = upper if (lower or upper) else 1/eps
        constrained_varkeys = constraints.constrained_varkeys()
        self.bound_varkeys = frozenset(vk for vk in constrained_varkeys
                                       if vk not in constraints.substitutions)
        bounding_constraints = varkey_bounds(self.bound_varkeys,
                                             self.lowerbound, self.upperbound)
        super().__init__({"original constraints": constraints,
                          "variable bounds": bounding_constraints})
github convexengineering / gpkit / gpkit / constraints / tight.py View on Github external
"Implements Tight"
from .set import ConstraintSet
from ..nomials import PosynomialInequality, SignomialInequality
from ..small_scripts import mag
from ..small_scripts import appendsolwarning
from .. import SignomialsEnabled


class Tight(ConstraintSet):
    "ConstraintSet whose inequalities must result in an equality."
    reltol = 1e-3

    def __init__(self, constraints, *, reltol=None, **kwargs):
        super().__init__(constraints)
        self.reltol = reltol or self.reltol
        self.__dict__.update(kwargs)  # NOTE: for Berk's use in labelling

    def process_result(self, result):
        "Checks that all constraints are satisfied with equality"
        super().process_result(result)
        variables = result["variables"]
        for constraint in self.flat():
            rel_diff = 0
            if isinstance(constraint, PosynomialInequality):
                leftsubbed = constraint.left.sub(variables).value
github convexengineering / gpkit / gpkit / constraints / set.py View on Github external
def __init__(self, constraints, substitutions=None, recursesubs=True):
        if isinstance(constraints, ConstraintSet):
            constraints = [constraints]
        list.__init__(self, constraints)
        subs = substitutions if substitutions else {}
        self.unused_variables = None
        if not isinstance(constraints, ConstraintSet):
            # constraintsetify everything
            for i, constraint in enumerate(self):
                if (hasattr(constraint, "__iter__") and
                        not isinstance(constraint, ConstraintSet)):
                    self[i] = ConstraintSet(constraint)
        else:
            # grab the substitutions dict from the top constraintset
            subs.update(constraints.substitutions)  # pylint: disable=no-member
        if recursesubs:
            self.reset_varkeys()
            self.substitutions = KeyDict.with_keys(self.varkeys,
                                                   self._iter_subs(subs))
        else:
            self.substitutions = subs
        # initializations for attributes used elsewhere
        self.posymap = []
github convexengineering / gpkit / gpkit / constraints / relax.py View on Github external
def __init__(self, original_constraints):
        if not isinstance(original_constraints, ConstraintSet):
            original_constraints = ConstraintSet(original_constraints)
        self.original_constraints = original_constraints
        original_substitutions = original_constraints.substitutions
        with NamedVariables("Relax"):
            self.relaxvars = VectorVariable(len(original_constraints), "C")

        with SignomialsEnabled():
            relaxed_constraints = [
                c.relaxed(self.relaxvars[i])
                for i, c in enumerate(original_constraints.flat())]

        ConstraintSet.__init__(self, {
            "relaxed constraints": relaxed_constraints,
            "minimum relaxation": self.relaxvars >= 1}, original_substitutions)
github convexengineering / gpkit / gpkit / constraints / relax.py View on Github external
def __init__(self, original_constraints):
        if not isinstance(original_constraints, ConstraintSet):
            original_constraints = ConstraintSet(original_constraints)
        self.original_constraints = original_constraints
        original_substitutions = original_constraints.substitutions

        with NamedVariables("Relax"):
            self.relaxvar = Variable("C")
        with SignomialsEnabled():
            relaxed_constraints = [c.relaxed(self.relaxvar)
                                   for c in original_constraints.flat()]

        ConstraintSet.__init__(self, {
            "relaxed constraints": relaxed_constraints,
            "minimum relaxation": self.relaxvar >= 1}, original_substitutions)
github convexengineering / gpkit / gpkit / constraints / relax.py View on Github external
def __init__(self, constraints, *, include_only=None, exclude=None):
        exclude = frozenset(exclude) if exclude else frozenset()
        include_only = frozenset(include_only) if include_only else frozenset()
        with NamedVariables("Relax") as (self.lineage, _):
            pass  # gives this model the correct lineage.

        if not isinstance(constraints, ConstraintSet):
            constraints = ConstraintSet(constraints)
        substitutions = KeyDict(constraints.substitutions)
        constants, _, linked = parse_subs(constraints.varkeys, substitutions)
        if linked:
            kdc = KeyDict(constants)
            constrained_varkeys = constraints.constrained_varkeys()
            constants.update({k: f(kdc) for k, f in linked.items()
                              if k in constrained_varkeys})

        self._derelax_map = {}
        relaxvars, self.freedvars, relaxation_constraints = [], [], {}
        for const, val in sorted(constants.items(), key=lambda i: i[0].eqstr):
            if val == 0:
                substitutions[const] = 0
                continue
            if include_only and const.name not in include_only:
                continue
github convexengineering / gpkit / gpkit / constraints / bounded.py View on Github external
def process_result(self, result):
        "Add boundedness to the model's solution"
        ConstraintSet.process_result(self, result)
        if "boundedness" not in result:
            result["boundedness"] = {}
        result["boundedness"].update(
            self.check_boundaries(result, verbosity=self.verbosity))
github convexengineering / gpkit / gpkit / constraints / loose.py View on Github external
"Implements Loose"
from .set import ConstraintSet
from ..small_scripts import appendsolwarning


class Loose(ConstraintSet):
    "ConstraintSet whose inequalities must result in an equality."
    senstol = 1e-5
    raiseerror = False

    def __init__(self, constraints, *, senstol=None):
        super().__init__(constraints)
        self.senstol = senstol or self.senstol

    def process_result(self, result):
        "Checks that all constraints are satisfied with equality"
        super().process_result(result)
        for constraint in self.flat():
            c_senss = result["sensitivities"]["constraints"].get(constraint, 0)
            if c_senss >= self.senstol:
                cstr = ("Constraint [ %.100s... %s %.100s... )"
                        % (constraint.left, constraint.oper, constraint.right))
github convexengineering / gpkit / gpkit / constraints / set.py View on Github external
def as_gpconstr(self, x0):
        """Returns GPConstraint approximating this constraint at x0

        When x0 is none, may return a default guess."""
        gpconstrs = [constr.as_gpconstr(x0) for constr in self]
        return ConstraintSet(gpconstrs,
                             self.substitutions, recursesubs=False)