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)
def test_relax_linked(self): x = Variable("x") x_max = Variable("x_max", 1) x_min = Variable("x_min", lambda c: 2 * c[x_max]) zero = Variable("zero", lambda c: 0 * c[x_max]) constraints = ConstraintSet([x_min + zero <= x, x + zero <= x_max]) _ = ConstantsRelaxed(constraints) NamedVariables.reset_modelnumbers() include_min = ConstantsRelaxed(constraints, include_only=["x_min"]) NamedVariables.reset_modelnumbers() exclude_max = ConstantsRelaxed(constraints, exclude=["x_max"]) self.assertEqual(str(include_min), str(exclude_max))
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)
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])
def setup(self): ConstraintSet([self, x <= 1])
def setup(self, m, sol, rob=False): r = 4 additional_constraints = [] slacks = [] thetas = [] for count in xrange((len(interesting_vars) - 1)): th = Variable("\\theta_%s" % count, np.linspace(0, 2 * np.pi, numberofsweeps), "-") thetas += [th] for i_set in xrange(len(interesting_vars)): if rob: eta_min_x, eta_max_x = RobustGPTools.generate_etas(interesting_vars[i_set], rmtype, rm.number_of_stds, rm.setting) else: eta_min_x, eta_max_x = 0, 0 center_x = (eta_min_x + eta_max_x) / 2.0 xo = mag(m.solution(interesting_vars[i_set])) x_center = np.log(xo) + center_x def f(c, index=i_set, x_val=x_center): product = 1 for j in xrange(index): product *= np.cos(c[thetas[j]]) if index != len(interesting_vars) - 1: product *= np.sin(c[thetas[index]]) return np.exp(x_val) * np.exp(r * product) if rmtype == 'box': def g(c, index=i_set, x_val=x_center, x_nom=xo, eta=eta_max_x): product = 1 for j in xrange(index): product *= np.cos(c[thetas[j]]) if index != len(interesting_vars) - 1: product *= np.sin(c[thetas[index]]) return np.exp(max(r*np.abs(product) - (np.log(x_nom) + eta - x_val), 0)) else: def g(c, index=i_set, x_val=x_center, x_nom=xo, eta=eta_max_x): product = 1 for j in xrange(index): product *= np.cos(c[thetas[j]]) if index != len(interesting_vars) - 1: product *= np.sin(c[thetas[index]]) return np.exp(np.abs((np.log(x_nom) + eta - x_val - r)*product)) x_i = Variable('x_%s' % i_set, f, interesting_vars[i_set].unitstr()) s_i = Variable("s_%s" % i_set) slacks += [s_i] uncertaintyset = Variable('uncertaintyset_%s' % i_set, g) var = RobustGPTools.variables_bynameandmodels(m, **interesting_vars[i_set].key.descr) if len(var) > 1: raise Exception("vector uncertain variables are not supported yet") else: var = var[0] additional_constraints += [s_i >= 1, s_i <= uncertaintyset*1.000001, var / s_i <= x_i, x_i <= var * s_i] cost_ref = Variable('cost_ref', 1, m.cost.unitstr(), "reference cost") self.cost = sum([sl ** 2 for sl in slacks]) * m.cost / cost_ref feas_slack = ConstraintSet(additional_constraints) if design_feasibility: return [m, feas_slack], {k: v for k, v in sol["freevariables"].items() if k in m.varkeys and k.key.fix is True} else: return [m, feas_slack], {k: v for k, v in sol["freevariables"].items() if k in m.varkeys}