def test_as_constraint(): from mystic.math.measures import mean, spread def mean_constraint(x, target): return mean(x) - target def range_constraint(x, target): return spread(x) - target @quadratic_equality(condition=range_constraint, kwds={'target': 5.0}) @quadratic_equality(condition=mean_constraint, kwds={'target': 5.0}) def penalty(x): return 0.0 ndim = 3 constraints = as_constraint(penalty) #, solver='fmin') #XXX: this is expensive to evaluate, as there are nested optimizations from numpy import arange x = arange(ndim) _x = constraints(x) assert round(mean(_x)) == 5.0 assert round(spread(_x)) == 5.0 assert round(penalty(_x)) == 0.0 def cost(x): return abs(sum(x) - 5.0) npop = ndim * 3 from mystic.solvers import diffev y = diffev(cost, x, npop, constraints=constraints, disp=False, gtol=10) assert round(mean(y)) == 5.0 assert round(spread(y)) == 5.0 assert round(cost(y)) == 5.0 * (ndim - 1)
def test_as_constraint(): from mystic.math.measures import mean, spread def mean_constraint(x, target): return mean(x) - target def range_constraint(x, target): return spread(x) - target @quadratic_equality(condition=range_constraint, kwds={'target':5.0}) @quadratic_equality(condition=mean_constraint, kwds={'target':5.0}) def penalty(x): return 0.0 ndim = 3 constraints = as_constraint(penalty, solver='fmin') #XXX: this is expensive to evaluate, as there are nested optimizations from numpy import arange x = arange(ndim) _x = constraints(x) assert round(mean(_x)) == 5.0 assert round(spread(_x)) == 5.0 assert round(penalty(_x)) == 0.0 def cost(x): return abs(sum(x) - 5.0) npop = ndim*3 from mystic.solvers import diffev y = diffev(cost, x, npop, constraints=constraints, disp=False, gtol=10) assert round(mean(y)) == 5.0 assert round(spread(y)) == 5.0 assert round(cost(y)) == 5.0*(ndim-1)