How to use the gpkit.varkey.VarKey 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 / model.py View on Github external
if abs(S) >= localmodel_sensitivity_requirement}
        localcs = (variables[var]**-S for (var, S) in localexp.items())
        localc = functools_reduce(mul, localcs, cost)
        localmodel = Monomial(localexp, localc)

        # vectorvar substitution
        veckeys = set()
        for var in self.unsubbed_varlocs:
            if "idx" in var.descr and "shape" in var.descr:
                descr = dict(var.descr)
                idx = descr.pop("idx")
                if "value" in descr:
                    descr.pop("value")
                if "units" in descr:
                    units = descr.pop("units")
                    veckey = VarKey(**descr)
                    veckey.descr["units"] = units
                else:
                    veckey = VarKey(**descr)
                veckeys.add(veckey)

                for vardict in [variables, sensitivities["variables"],
                                constants, sweepvariables, freevariables]:
                    if var in vardict:
                        if veckey in vardict:
                            vardict[veckey][idx] = vardict[var]
                        else:
                            vardict[veckey] = np.full(var.descr["shape"], np.nan)
                            vardict[veckey][idx] = vardict[var]

                        del vardict[var]
github convexengineering / gpkit / gpkit / feasibility.py View on Github external
elif flavour == "product":
        slackvars = VectorVariable(len(constraints), varname)
        cost = np.sum(slackvars)
        constraints = ((1/slackvars).tolist() +  # slackvars > 1
                       [constraint/slackvars[i]  # constraint <= sv
                        for i, constraint in enumerate(constraints)])
        prog = programType(cost, constraints)
        prog.slackvars = slackvars

    elif flavour == "constants":
        slackb = VectorVariable(len(constants), units="-")
        constvarkeys, constvars, rmvalue, addvalue = [], [], {}, {}
        for vk in constants.keys():
            descr = dict(vk.descr)
            del descr["value"]
            vk_ = VarKey(**descr)
            rmvalue[vk] = vk_
            addvalue[vk_] = vk
            constvarkeys.append(vk_)
            constvars.append(Variable(**descr))
        constvars = PosyArray(constvars)
        constvalues = PosyArray(constants.values())
        constraints = [c.sub(rmvalue) for c in signomials]
        cost = slackb.prod()
        # cost function could also be .sum(); self.cost would break ties
        for i in range(len(constvars)):
            slack = slackb[i]
            constvar, constvalue = constvars[i], constvalues[i]
            if constvar.units:
                constvalue *= constvar.units
            constraints += [slack >= 1,
                            constvalue/slack <= constvar,
github convexengineering / gpkit / gpkit / nomials / variables.py View on Github external
for arg in args:
            if isinstance(arg, Strings) and "name" not in descr:
                descr["name"] = arg
            elif (isinstance(arg, (Numbers, Iterable))
                  and not isinstance(arg, Strings)
                  and "value" not in descr):
                descr["value"] = arg
            elif hasattr(arg, "__call__"):
                descr["value"] = arg
            elif isinstance(arg, Strings) and "units" not in descr:
                descr["units"] = arg
            elif isinstance(arg, Strings) and "label" not in descr:
                descr["label"] = arg

        if "name" not in descr:
            descr["name"] = "\\fbox{%s}" % VarKey.unique_id()

        value_option = None
        if "value" in descr:
            value_option = "value"
        if value_option:
            values = descr.pop(value_option)
        if value_option and not hasattr(values, "__call__"):
            if Vectorize.vectorization:
                if not hasattr(values, "shape"):
                    values = np.full(shape, values, "f")
                else:
                    values = np.broadcast_to(values, reversed(shape)).T
            elif not hasattr(values, "shape"):
                values = np.array(values)
            if values.shape != shape:
                raise ValueError("the value's shape %s is different than"
github convexengineering / gpkit / gpkit / model.py View on Github external
localmodel = Monomial(localexp, localc)

        # vectorvar substitution
        veckeys = set()
        for var in self.unsubbed_varlocs:
            if "idx" in var.descr and "shape" in var.descr:
                descr = dict(var.descr)
                idx = descr.pop("idx")
                if "value" in descr:
                    descr.pop("value")
                if "units" in descr:
                    units = descr.pop("units")
                    veckey = VarKey(**descr)
                    veckey.descr["units"] = units
                else:
                    veckey = VarKey(**descr)
                veckeys.add(veckey)

                for vardict in [variables, sensitivities["variables"],
                                constants, sweepvariables, freevariables]:
                    if var in vardict:
                        if veckey in vardict:
                            vardict[veckey][idx] = vardict[var]
                        else:
                            vardict[veckey] = np.full(var.descr["shape"], np.nan)
                            vardict[veckey][idx] = vardict[var]

                        del vardict[var]

        # TODO: remove after issue #269 is resolved
        # for veckey in veckeys:
        #     # TODO: print index that error occured at
github convexengineering / gpkit / gpkit / nomials / variables.py View on Github external
descr["name"] = arg
                elif (isinstance(arg, Numbers) or hasattr(arg, "__call__")
                      and "value" not in descr):
                    descr["value"] = arg
                elif (isinstance(arg, Iterable)
                      and not isinstance(arg, Strings)):
                    if is_sweepvar(arg):
                        descr["value"] = arg
                    else:
                        descr["value"] = ("sweep", arg)
                elif isinstance(arg, Strings) and "units" not in descr:
                    descr["units"] = arg
                elif isinstance(arg, Strings) and "label" not in descr:
                    descr["label"] = arg
            addmodelstodescr(descr, addtonamedvars=self)
            self.key = VarKey(**descr)
        Monomial.__init__(self, self.key.hmap)
        # NOTE: needed because Signomial.__init__ will change the class
        self.__class__ = Variable
github convexengineering / gpkit / gpkit / tools / fmincon.py View on Github external
"""
    if logspace: # Supplying derivatives not supported for logspace
        gradobj = 'off'
        gradconstr = 'off'

    # Create a new dictionary mapping variables to x(i)'s for use w/ fmincon
    i = 1
    newdict = {}
    lookup = []
    newlist = []
    original_varkeys = model.varkeys
    for key in model.varkeys:
        if key not in model.substitutions:
            descr = key.descr.copy()
            descr["name"] = 'x(%i)' % i
            newdict[key] = VarKey(**descr)
            newlist += [key.str_without(["units"])]
            lookup += ['x_{0}: '.format(i) + key.str_without(["units"])]
            i += 1
    x0string = make_initial_guess(model, newlist, guess, logspace)

    cost = model.cost # needs to be before subinplace()
    constraints = model
    substitutions = constraints.substitutions
    constraints.substitutions = KeyDict()
    constraints.subinplace(substitutions)
    constraints.subinplace(newdict)
    constraints.substitutions = substitutions

    # Make all constraints less than zero, return list of clean strings
    c = [] # inequality constraints
    ceq = [] # equality constraints
github convexengineering / gpkit / gpkit / nomials / variables.py View on Github external
def __init__(self, *args, **descr):
        if len(args) == 1 and isinstance(args[0], VarKey):
            self.key, = args
        else:
            for arg in args:
                if isinstance(arg, Strings) and "name" not in descr:
                    descr["name"] = arg
                elif (isinstance(arg, Numbers) or hasattr(arg, "__call__")
                      and "value" not in descr):
                    descr["value"] = arg
                elif (isinstance(arg, Iterable)
                      and not isinstance(arg, Strings)):
                    if is_sweepvar(arg):
                        descr["value"] = arg
                    else:
                        descr["value"] = ("sweep", arg)
                elif isinstance(arg, Strings) and "units" not in descr:
                    descr["units"] = arg
github convexengineering / gpkit / gpkit / model.py View on Github external
def solve_pass(i):
                this_pass = {var: sweep_vect[i]
                             for (var, sweep_vect) in sweep_vects.items()}
                linked = {var: fn(*[this_pass[VarKey(v)]
                                    for v in var.descr["args"]])
                          for var, fn in linkedsweep.items()}
                this_pass.update(linked)
                constants_ = constants
                constants_.update(this_pass)
                program, mmaps = self.formProgram(programType, posynomials,
                                                  constants_, verbosity)

                try:
                    if programType == "gp":
                        result = program.solve(*args, **kwargs)
                    elif programType == "sp":
                        result = program.localsolve(*args, **kwargs)
                    sol = self.parse_result(result, constants_, mmaps,
                                            sweep, linkedsweep)
                    return program, sol
github convexengineering / gpkit / gpkit / nomials / nomial_math.py View on Github external
# pylint: disable=too-many-statements
        # pylint: disable=too-many-branches
        # this is somewhat deprecated, used for Variables and subbing Monomials
        units = descr.get("units", None)
        # If cs has units, then they will override this setting.
        if isinstance(exps, Numbers):
            cs = exps
            exps = {}
        if (isinstance(cs, Numbers) and
                (exps is None or isinstance(exps, Strings + (VarKey, dict)))):
            # building a Monomial
            if isinstance(exps, VarKey):
                exp = {exps: 1}
                units = exps.units  # pylint: disable=no-member
            elif exps is None or isinstance(exps, Strings):
                vk = VarKey(**descr) if exps is None else VarKey(exps, **descr)
                descr = vk.descr
                units = vk.units
                exp = {vk: 1}
            elif isinstance(exps, dict):
                exp = dict(exps)
                for key in exps:
                    if isinstance(key, Strings):
                        exp[VarKey(key)] = exp.pop(key)
            else:
                raise TypeError("could not make Monomial with %s" % type(exps))
            #simplify = False #TODO: this shouldn't require simplification
            cs = [cs]
            exps = [HashVector(exp)]  # pylint: disable=redefined-variable-type
        elif isinstance(exps, Nomial):
            simplify = False
            cs = exps.cs  # pylint: disable=no-member