Changeset 603 for branches


Ignore:
Timestamp:
12/04/12 19:55:29 (3 years ago)
Author:
mmckerns
Message:

added outer wrapper 'wrap' as opposed to inner wrapper 'nested'
added tests of with_* decorators

Location:
branches/decorate
Files:
1 added
3 edited

Legend:

Unmodified
Added
Removed
  • branches/decorate/constraints.py

    r602 r603  
    11# XXX: provide the below from measures, which from bounded?, and ...generic? 
     2# XXX: with_*** is a 'wrap' constraint, what about 'nested' constraints? 
    23 
    34from mystic.math.measures import * 
  • branches/decorate/test_wrapper.py

    r602 r603  
    11from wrapper import * 
    22from mystic.math import almostEqual 
     3 
     4def test_wrap(): 
     5 
     6  def squared(x): 
     7    return x**2 
     8 
     9  @wrap(outer=squared)  
     10  def plus_one_squared(x): 
     11    return x+1 
     12 
     13  from numpy import array 
     14  x = array([1,2,3,4,5]) 
     15  assert all(plus_one_squared(x)) == all((x+1)**2) 
     16 
    317 
    418def test_nested(): 
     
    1428  x = array([1,2,3,4,5]) 
    1529  assert all(squared_plus_one(x)) == all(x**2 + 1) 
     30 
     31 
     32def test_wrap_constraint(): 
     33 
     34  from mystic.math.measures import impose_mean, mean 
     35 
     36  def impose_constraints(x, mean, weights=None): 
     37    return impose_mean(mean, x, weights) 
     38 
     39  @wrap(outer=impose_constraints, kwds={'mean':5.0}) 
     40  def mean_of_squared(x): 
     41    return [i**2 for i in x] 
     42 
     43  from numpy import array 
     44  x = array([1,2,3,4,5]) 
     45  y = impose_mean(5, [i**2 for i in x]) 
     46  assert mean(y) == 5.0 
     47  assert mean_of_squared(x) == y 
    1648 
    1749 
     
    249281 
    250282if __name__ == '__main__': 
     283  test_wrap() 
    251284  test_nested() 
     285  test_wrap_constraint() 
    252286  test_nested_constraint() 
    253287  test_proxified_constraint() 
  • branches/decorate/wrapper.py

    r602 r603  
    11#XXX: be mindful if the decorators restrict to functions that expect arrays 
    22#     compare against the originals for restrictions 
     3 
     4def wrap(outer=lambda x:x, args=None, kwds=None): #XXX: *args, **kwds ? 
     5    """wrap a function around another function: convert y = f(x) to y' = c(f(x)) 
     6 
     7This is useful, for example, in nesting one constraint in another constraint. 
     8    """ 
     9    if args is None: args=() 
     10    if kwds is None: kwds={} 
     11    def dec(f): 
     12        def func(x, *argz, **kwdz): 
     13            return outer(f(x, *argz, **kwdz), *args, **kwds) 
     14        return func 
     15    return dec 
     16 
    317 
    418def nested(inner=lambda x:x, args=None, kwds=None): #XXX: *args, **kwds ? 
Note: See TracChangeset for help on using the changeset viewer.