def _rule_result(self, terms): coefficients = [c for c, _ in terms] children = [PE() for _ in terms] cvxs = [c for _, c in terms] ctx = ConvexityContext() for child, cvx in zip(children, cvxs): ctx.set_convexity(child, cvx) rule = LinearRule() return rule.checked_apply(PE(ET.Linear, children=children, coefficients=coefficients), ctx)
def test_linear_over_variable(coef): rule = FractionalRule() x = PE(ET.Variable) num = PE(ET.Linear, [x], coefficients=[coef], constant_term=0.0) ctx = FractionalContext({ x: I(0, None), }) result = rule.apply(PE(ET.Division, [num, x]), ctx) assert result == Convexity.Linear
def _rule_result(self, A): n = A.shape[0] var = [PE(ET.Variable) for _ in range(n)] terms = [] for i in range(n): for j in range(i + 1): terms.append(BilinearTerm(var[i], var[j], A[i, j])) expr = PE(ET.Quadratic, terms=terms, children=var) rule = QuadraticRule() return rule.apply(expr, None)
def _rule_result(self, cvx_f, cvx_g, mono_f, mono_g, bounds_f, bounds_g): rule = DivisionRule() f = PE() g = PE() convexity = ComponentMap() convexity[f] = cvx_f convexity[g] = cvx_g mono = ComponentMap() mono[f] = mono_f mono[g] = mono_g bounds = ComponentMap() bounds[f] = bounds_f bounds[g] = bounds_g return rule.apply(PE(ET.Division, [f, g]), convexity, mono, bounds)
def _result_with_terms(self, terms): rule = LinearRule() monotonicity = {} coefficients = [c for c, _ in terms] children = [PE(ET.Variable) for _ in terms] monos = [m for _, m in terms] for child, mono in zip(children, monos): monotonicity[child] = mono ctx = MonotonicityContext(monotonicity, {}) result = rule.checked_apply( PE(ET.Linear, children=children, coefficients=coefficients), ctx, ) return result
def test_linear_with_constant_over_variable(coef, const): assume(coef != 0.0) assume(coef < MAX_NUM and const < MAX_NUM) rule = FractionalRule() x = PE(ET.Variable) num = PE(ET.Linear, [x], coefficients=[coef], constant_term=const) ctx = FractionalContext({ x: I(0, None), }) result = rule.apply(PE(ET.Division, [num, x]), ctx) if almosteq(const, 0): expected = Convexity.Linear elif const > 0: expected = Convexity.Convex elif const < 0: expected = Convexity.Concave
def test_constant_is_constant(): rule = ConstantRule() result = rule.apply(PE(ET.Constant), None, None) assert result.is_constant()
def test_variable_is_nondecreasing(): rule = VariableRule() result = rule.apply(PE(ET.Variable), None, None) assert result.is_nondecreasing() and (not result.is_constant())
def test_l2_norm(children): rule = L2NormRule() sum_ = PE(ET.Sum, children) result = rule.checked_apply(PE(ET.UnaryFunction, [sum_], func_type=UFT.Sqrt), None) assert result.is_convex()
def products(draw): x = PE(ET.Variable) return PE(ET.Product, [x, x])
def powers(draw): base = PE(ET.Variable) expo = PE(ET.Constant, value=2.0) return PE(ET.Power, [base, expo])
def constants(draw): return PE(ET.Constant)