Ejemplo n.º 1
0
 def __init__(self, lhs, varname, models=[], variables=[], **kwargs):
     summedvars = set([v.key for v in variables])
     alreadysummed = set()
     for model in models:
         twovars = 0
         for var in model.varkeys:
             if var.name == varname:
                 twovars += 1
         if twovars > 1:
             for dvar in model.variables_byname(varname):
                 if model.__class__.__name__ == dvar.descr["models"][0]:
                     mvars = dvar
         else:
             mvars = model[varname]
         if not hasattr(mvars, "__len__"):
             mvars = [mvars]
         # next line makes the recursion stop at depth one
         # for safety to avoid double counting
         mvars = [v for v in mvars if v.key.models[0] == model.name]
         assert len(mvars) == 1
         summedvars = summedvars.union([v.key for v in mvars])
         for constraint in model.flat():
             if hasattr(constraint, "summedvars"):
                 alreadysummed = alreadysummed.union(constraint.summedvars)
     summedvars = summedvars.difference(alreadysummed)
     ConstraintSet.__init__(self, [lhs >= sum(Variable(**vk.descr)
                                              for vk in summedvars)],
                            **kwargs)
Ejemplo n.º 2
0
    def __init__(self,
                 df,
                 ivar,
                 dvars,
                 nobounds=False,
                 err_margin=False,
                 airfoil=False):
        self.airfoil = airfoil
        self.dvars = dvars
        self.ivar = ivar

        K = int(df["K"].iloc[0])
        d = int(df["d"].iloc[0])
        ftype = df["ftype"].iloc[0]
        A = np.array(df[[
            "e%d%d" % (k, i) for k in range(1, K + 1) for i in range(1, d + 1)
        ]])[0].astype(float)
        B = np.array(df[["c%d" % k for k in range(1, K + 1)]])[0].astype(float)

        withvector = False
        withvar = False
        for dv in self.dvars:
            if hasattr(dv, "__len__"):
                withvector = True
                N = len(dv)
            else:
                withvar = True
        if withvector:
            if withvar:
                self.dvars = np.array([
                    dv if isinstance(dv, NomialArray) else [dv] * N
                    for dv in self.dvars
                ]).T
            else:
                self.dvars = np.array(self.dvars).T
        else:
            self.dvars = np.array([self.dvars])
        monos = [
            B * NomialArray([(dv**A[k * d:(k + 1) * d]).prod()
                             for k in range(K)]) for dv in self.dvars
        ]

        if err_margin == "Max":
            maxerr = float(df["max_err"].iloc[0])
            self.mfac = Variable(
                "m_{fac-fit}", 1 + maxerr, "-",
                "max error of " + ivar.descr["label"] + " fit")
        elif err_margin == "RMS":
            rmserr = float(df["rms_err"].iloc[0])
            self.mfac = Variable(
                "m_{fac-fit}", 1 + rmserr, "-",
                "RMS error of " + ivar.descr["label"] + " fit")
        else:
            self.mfac = Variable("m_{fac-fit}", 1.0, "-", "fit factor")

        if ftype == "ISMA":
            # constraint of the form 1 >= c1*u1^exp1*u2^exp2*w^(-alpha) + ....
            alpha = np.array(df[["a%d" % k
                                 for k in range(1, K + 1)]])[0].astype(float)
            lhs = 1
            rhs = NomialArray([(mono / (ivar / self.mfac)**alpha).sum()
                               for mono in monos])
        elif ftype == "SMA":
            # constraint of the form w^alpha >= c1*u1^exp1 + c2*u2^exp2 +....
            alpha = float(df["a1"].iloc[0])
            lhs = (ivar / self.mfac)**alpha
            rhs = NomialArray([mono.sum() for mono in monos])
        elif ftype == "MA":
            # constraint of the form w >= c1*u1^exp1, w >= c2*u2^exp2, ....
            lhs, rhs = (ivar / self.mfac), NomialArray(monos)

        if K == 1:
            # when possible, return an equality constraint
            if withvector:
                cstrt = [(lh == rh) for rh, lh in zip(rhs, lhs)]
            else:
                cstrt = (lhs == rhs)
        else:
            if withvector:
                cstrt = [(lh >= rh) for rh, lh in zip(rhs, lhs)]
            else:
                cstrt = (lhs >= rhs)

        constraints = [cstrt]
        if not hasattr(self.mfac, "__len__"):
            self.mfac = [self.mfac] * len(self.dvars)
        if not hasattr(self.ivar, "__len__"):
            self.ivar = [self.ivar] * len(self.dvars)

        self.bounds = []
        for dvar in self.dvars:
            bds = {}
            for i, v in enumerate(dvar):
                bds[v] = [
                    float(df["lb%d" % (i + 1)].iloc[0]),
                    float(df["ub%d" % (i + 1)].iloc[0])
                ]
            self.bounds.append(bds)

        ConstraintSet.__init__(self, constraints)
Ejemplo n.º 3
0
    def __init__(self, fitdata, ivar=None, dvars=None, name="",
                 err_margin=None):

        self.fitdata = fitdata

        if ivar is None:
            with NamedVariables("fit"):
                dvars = VectorVariable(fitdata["d"], "u")
                ivar = Variable("w")

        self.dvars = dvars
        self.ivar = ivar
        self.rms_err = fitdata["rms_err"]
        self.max_err = fitdata["max_err"]

        monos = [fitdata["c%d" % k]*NomialArray(array(dvars).T**array(
            [fitdata["e%d%d" % (k, i)] for i in
             range(fitdata["d"])])).prod(NomialArray(dvars).ndim - 1)
            for k in range(fitdata["K"])]

        if err_margin == "Max":
            self.mfac = Variable("m_{fac-" + name + "-fit}",
                                 1 + self.max_err, "-", "max error of fit")
        elif err_margin == "RMS":
            self.mfac = Variable("m_{fac-" + name + "-fit}",
                                 1 + self.rms_err, "-", "RMS error of fit")
        elif err_margin is None:
            self.mfac = Variable("m_{fac-" + name + "-fit}", 1.0, "-",
                                 "fit factor")
        else:
            raise ValueError("Invalid name for err_margin: valid inputs Max, "
                             "RMS")

        if fitdata["ftype"] == "ISMA":
            # constraint of the form 1 >= c1*u1^exp1*u2^exp2*w^(-alpha) + ....
            alpha = array([fitdata["a%d" % k] for k in
                           range(fitdata["K"])])
            lhs, rhs = 1, NomialArray(monos/(ivar/self.mfac)**alpha).sum(0)
        elif fitdata["ftype"] == "SMA":
            # constraint of the form w^alpha >= c1*u1^exp1 + c2*u2^exp2 +....
            alpha = fitdata["a1"]
            lhs, rhs = (ivar/self.mfac)**alpha, NomialArray(monos).sum(0)
        elif fitdata["ftype"] == "MA":
            # constraint of the form w >= c1*u1^exp1, w >= c2*u2^exp2, ....
            lhs, rhs = (ivar/self.mfac), NomialArray(monos).T

        if fitdata["K"] == 1:
            # when possible, return an equality constraint
            if hasattr(rhs, "shape"):
                if rhs.ndim > 1:
                    self.constraint = [(lh == rh) for lh, rh in zip(lhs, rhs)]
                else:
                    self.constraint = (lhs == rhs)
            else:
                self.constraint = (lhs == rhs)
        else:
            if hasattr(rhs, "shape"):
                if rhs.ndim > 1:
                    self.constraint = [(lh >= rh) for lh, rh in zip(lhs, rhs)]
                else:
                    self.constraint = (lhs >= rhs)
            else:
                self.constraint = (lhs >= rhs)

        self.bounds = {}
        for i, dvar in enumerate(self.dvars):
            self.bounds[dvar] = [fitdata["lb%d" % i],
                                 fitdata["ub%d" % i]]

        ConstraintSet.__init__(self, [self.constraint])