Changeset 646 for branches/decorate/wrapper.py
- Timestamp:
- 01/18/13 06:20:57 (3 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/decorate/wrapper.py
r643 r646 41 41 42 42 43 from numpy import asarray, any, inf, vectorize , choose, zeros, ones, ndarray43 from numpy import asarray, any, inf, vectorize 44 44 def bounded(min=None, max=None): 45 45 """impose an infinite barrier box constraint on a function … … 118 118 119 119 120 #from random import sample, choice121 def discrete(samples, index=None):122 """impose a discrete set of input values for the selected function123 124 The function's input will be mapped to the given discrete set125 126 >>> @discrete([1.0, 2.0])127 ... def identity(x):128 ... return x129 130 >>> identity([0.123, 1.789, 4.000])131 [1.0, 2.0, 2.0]132 133 >>> @discrete([1,3,5,7], index=(0,3))134 ... def squared(x):135 .... return [i**2 for i in x]136 137 >>> squared([0,2,4,6,8,10])138 [1, 4, 16, 25, 64, 100]"""139 samples = [asarray(samples)]140 samples[0].sort()141 if isinstance(index, int): index = (index,)142 index = [index]143 144 #XXX: refactor to use points_factory(samples)145 def _points(alist):146 alist = asarray(alist)147 alist.sort()148 samples[0] = alist149 150 def _index(alist=None):151 index[0] = alist152 153 #XXX: refactor to use argnear_factory(samples)154 def _argnear(xi):155 arghi = sum(xi > samples[0])156 arglo = max(0, arghi - 1) # minimum = x[0]157 if arghi == len(samples[0]):158 arghi = arglo # maximum = x[-1]159 return arglo, arghi160 161 def _near(xi, lo, hi):162 if hi - xi < xi - lo:163 return hi164 return lo165 166 argnear = vectorize(_argnear)167 near = vectorize(_near)168 169 def dec(f):170 def func(x, *args, **kwds):171 if isinstance(x, ndarray): xtype = asarray172 else: xtype = type(x)173 arglo, arghi = argnear(x)174 xp = near(x, samples[0][arglo], samples[0][arghi])175 # create a choice array from given indices176 #FIXME: better ways to do the following177 if index[0] is None:178 mask = ones(xp.size, dtype=bool)179 else:180 mask = zeros(xp.size, dtype=bool)181 try: mask[sorted(index[0], key=abs)] = True182 except IndexError: pass183 xp = xtype(choose(mask, (x,xp)))184 return f(xp, *args, **kwds)185 func.samples = _points186 func.index = _index187 return func188 return dec189 190 191 120 #FIXME: the following should preserve the input type 192 121 def __clip_bound(x, amin, amax):
Note: See TracChangeset
for help on using the changeset viewer.