How to use the gpkit.keydict.KeyDict 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 / prog_factories.py View on Github external
try:
            result = solvefn(solver, verbosity=verbosity-1, **solveargs)
            if solveargs.get("process_result", True):
                self.process_result(result)
            solution.append(result)
        except Infeasible as e:
            last_error = e
            if not skipsweepfailures:
                raise RuntimeWarning(
                    "Sweep halted! Progress saved to m.program. To skip over"
                    " such failures, solve with skipsweepfailures=True.") from e
    if not solution:
        raise RuntimeWarning("No sweeps solved successfully.") from last_error

    solution["sweepvariables"] = KeyDict()
    ksweep = KeyDict(sweep)
    for var, val in list(solution["constants"].items()):
        if var in ksweep:
            solution["sweepvariables"][var] = val
            del solution["constants"][var]
        elif var not in linked:
            solution["constants"][var] = [val[0]]

    if verbosity > 0:
        soltime = time() - tic
        print("Sweeping took %.3g seconds." % (soltime,))
github convexengineering / gpkit / gpkit / constraints / prog_factories.py View on Github external
N_passes = sweep_grids[0].size
    sweep_vects = {var: grid.reshape(N_passes)
                   for (var, grid) in zip(sweepvars, sweep_grids)}

    if verbosity > 0:
        print("Sweeping over %i solves." % N_passes)
        tic = time()

    self.program = []
    last_error = None
    for i in range(N_passes):
        constants.update({var: sweep_vect[i]
                          for (var, sweep_vect) in sweep_vects.items()})
        if linked:
            kdc = KeyDict(constants)
            constants.update({v: f(kdc) for v, f in linked.items()})
        program, solvefn = genfunction(self, constants)
        self.program.append(program)  # NOTE: SIDE EFFECTS
        try:
            result = solvefn(solver, verbosity=verbosity-1, **solveargs)
            if solveargs.get("process_result", True):
                self.process_result(result)
            solution.append(result)
        except Infeasible as e:
            last_error = e
            if not skipsweepfailures:
                raise RuntimeWarning(
                    "Sweep halted! Progress saved to m.program. To skip over"
                    " such failures, solve with skipsweepfailures=True.") from e
    if not solution:
        raise RuntimeWarning("No sweeps solved successfully.") from last_error
github convexengineering / gpkit / gpkit / constraints / gp.py View on Github external
Arguments
        ---------
        solver_out: dict
            dict in format returned by solverfn within GeometricProgram.solve

        Returns
        -------
        result: dict
            dict in format returned by GeometricProgram.solve()
        """
        result = {"cost": float(solver_out["objective"])}
        primal = solver_out["primal"]
        if len(self.varlocs) != len(primal):
            raise RuntimeWarning("The primal solution was not returned.")
        result["freevariables"] = KeyDict(zip(self.varlocs, np.exp(primal)))
        result["constants"] = KeyDict(self.substitutions)
        result["variables"] = KeyDict(result["freevariables"])
        result["variables"].update(result["constants"])
        result["sensitivities"] = {"constraints": {}}
        la, self.nu_by_posy = self._generate_nula(solver_out)
        cost_senss = sum(nu_i*exp for (nu_i, exp) in zip(self.nu_by_posy[0],
                                                         self.cost.hmap))
        self.v_ss = cost_senss.copy()
        for las, nus, c in zip(la[1:], self.nu_by_posy[1:], self.hmaps[1:]):
            while getattr(c, "parent", None) is not None:
                c = c.parent
            v_ss, c_senss = c.sens_from_dual(las, nus, result)
            for vk, x in v_ss.items():
                self.v_ss[vk] = x + self.v_ss.get(vk, 0)
            while getattr(c, "generated_by", None) is not None:
                c = c.generated_by
github convexengineering / gpkit / gpkit / constraints / prog_factories.py View on Github external
def evaluate_linked(constants, linked):
    "Evaluates the values and gradients of linked variables."
    kdc = KeyDict({k: adnumber(maybe_flatten(v))
                   for k, v in constants.items()})
    kdc.log_gets = True
    kdc_plain = None
    array_calulated, logged_array_gets = {}, {}
    for v, f in linked.items():
        try:
            if v.veckey and v.veckey.original_fn:
                if v.veckey not in array_calulated:
                    ofn = v.veckey.original_fn
                    array_calulated[v.veckey] = np.array(ofn(kdc))
                    logged_array_gets[v.veckey] = kdc.logged_gets
                logged_gets = logged_array_gets[v.veckey]
                out = array_calulated[v.veckey][v.idx]
            else:
                logged_gets = kdc.logged_gets
                out = f(kdc)
github convexengineering / gpkit / gpkit / constraints / gp.py View on Github external
---------
        solver_out: dict
            dict in format returned by solverfn within GeometricProgram.solve

        Returns
        -------
        result: dict
            dict in format returned by GeometricProgram.solve()
        """
        result = {"cost": float(solver_out["objective"])}
        primal = solver_out["primal"]
        if len(self.varlocs) != len(primal):
            raise RuntimeWarning("The primal solution was not returned.")
        result["freevariables"] = KeyDict(zip(self.varlocs, np.exp(primal)))
        result["constants"] = KeyDict(self.substitutions)
        result["variables"] = KeyDict(result["freevariables"])
        result["variables"].update(result["constants"])
        result["sensitivities"] = {"constraints": {}}
        la, self.nu_by_posy = self._generate_nula(solver_out)
        cost_senss = sum(nu_i*exp for (nu_i, exp) in zip(self.nu_by_posy[0],
                                                         self.cost.hmap))
        self.v_ss = cost_senss.copy()
        for las, nus, c in zip(la[1:], self.nu_by_posy[1:], self.hmaps[1:]):
            while getattr(c, "parent", None) is not None:
                c = c.parent
            v_ss, c_senss = c.sens_from_dual(las, nus, result)
            for vk, x in v_ss.items():
                self.v_ss[vk] = x + self.v_ss.get(vk, 0)
            while getattr(c, "generated_by", None) is not None:
                c = c.generated_by
            result["sensitivities"]["constraints"][c] = c_senss
        # carry linked sensitivities over to their constants
github convexengineering / gpkit / gpkit / keydict.py View on Github external
def update(self, *args, **kwargs):
        "Iterates through the dictionary created by args and kwargs"
        if not self and len(args) == 1 and isinstance(args[0], KeyDict):
            super().update(args[0])
            self.keymap.update(args[0].keymap)
            self._unmapped_keys.update(args[0]._unmapped_keys)  # pylint:disable=protected-access
        else:
            for k, v in dict(*args, **kwargs).items():
                self[k] = v
github convexengineering / gpkit / gpkit / constraints / prog_factories.py View on Github external
for key in logged_gets:
                if key.shape:
                    grad = out.gradient(kdc[key])
                    v.gradients[key] = np.array(grad)
                else:
                    v.gradients[key] = out.d(kdc[key])
        except Exception as exception:  # pylint: disable=broad-except
            from .. import settings
            if settings.get("ad_errors_raise", None):
                raise
            print("Warning: skipped auto-differentiation of linked variable"
                  " %s because %s was raised. Set `gpkit.settings"
                  "[\"ad_errors_raise\"] = True` to raise such Exceptions"
                  " directly.\n" % (v, repr(exception)))
            if kdc_plain is None:
                kdc_plain = KeyDict(constants)
            constants[v] = f(kdc_plain)
            v.descr.pop("gradients", None)
        finally:
            kdc.logged_gets = set()
github convexengineering / gpkit / gpkit / constraints / gp.py View on Github external
dlogv_dlogc = dv_dc * result["constants"][c]/val
                # make nans / infs explicitly to avoid warnings
                elif dlogcost_dlogv == 0:
                    dlogv_dlogc = np.nan
                else:
                    dlogv_dlogc = np.inf * dv_dc*result["constants"][c]
                accum = var_senss.get(c, 0)
                var_senss[c] = dlogcost_dlogv*dlogv_dlogc + accum
                if v in cost_senss:
                    if c in self.cost.varkeys:
                        dlogcost_dlogv = cost_senss.pop(v)
                        accum = cost_senss.get(c, 0)
                        cost_senss[c] = dlogcost_dlogv*dlogv_dlogc + accum

        result["sensitivities"]["cost"] = cost_senss
        result["sensitivities"]["variables"] = KeyDict(var_senss)
        result["sensitivities"]["constants"] = KeyDict(
            {k: v for k, v in var_senss.items() if k in result["constants"]})
        result["soltime"] = solver_out["soltime"]
        return SolutionArray(result)
github convexengineering / gpkit / gpkit / constraints / gp.py View on Github external
Arguments
        ---------
        solver_out: dict
            dict in format returned by solverfn within GeometricProgram.solve

        Returns
        -------
        result: dict
            dict in format returned by GeometricProgram.solve()
        """
        result = {"cost": float(solver_out["objective"])}
        primal = solver_out["primal"]
        if len(self.varlocs) != len(primal):
            raise RuntimeWarning("The primal solution was not returned.")
        result["freevariables"] = KeyDict(zip(self.varlocs, np.exp(primal)))
        result["constants"] = KeyDict(self.substitutions)
        result["variables"] = KeyDict(result["freevariables"])
        result["variables"].update(result["constants"])
        result["sensitivities"] = {"constraints": {}}
        la, self.nu_by_posy = self._generate_nula(solver_out)
        cost_senss = sum(nu_i*exp for (nu_i, exp) in zip(self.nu_by_posy[0],
                                                         self.cost.hmap))
        self.v_ss = cost_senss.copy()
        for las, nus, c in zip(la[1:], self.nu_by_posy[1:], self.hmaps[1:]):
            while getattr(c, "parent", None) is not None:
                c = c.parent
            v_ss, c_senss = c.sens_from_dual(las, nus, result)
            for vk, x in v_ss.items():
                self.v_ss[vk] = x + self.v_ss.get(vk, 0)
            while getattr(c, "generated_by", None) is not None:
                c = c.generated_by
            result["sensitivities"]["constraints"][c] = c_senss