def setUp(self):
# real function
self.z_values = np.linspace(0, 1, 1000)
self.real_func = core.Function(lambda x: x)
self.real_func_handle = np.vectorize(self.real_func)
# approximation by lag1st
self.nodes, self.src_test_funcs = shapefunctions.cure_interval(shapefunctions.LagrangeFirstOrder, (0, 1),
node_count=2)
register_base("test_funcs", self.src_test_funcs, overwrite=True)
self.src_weights = core.project_on_base(self.real_func, self.src_test_funcs)
self.assertTrue(np.allclose(self.src_weights, [0, 1])) # just to be sure
self.src_approx_handle = core.back_project_from_base(self.src_weights, self.src_test_funcs)
# approximation by sin(w*x)
def trig_factory(freq):
def func(x):
return np.sin(freq*x)
return func
self.trig_test_funcs = np.array([core.Function(trig_factory(w), domain=(0, 1)) for w in range(1, 3)])
python类vectorize()的实例源码
def __init__(self, y0, y1, z0, z1, t0, dt, params):
SimulationInput.__init__(self)
# store params
self._tA = t0
self._dt = dt
self._dz = z1 - z0
self._m = params.m # []=kg mass at z=0
self._tau = params.tau # []=m/s speed of wave translation in string
self._sigma = params.sigma # []=kgm/s**2 pretension of string
# construct trajectory generator for yd
ts = max(t0, self._dz * self._tau) # never too early
self.trajectory_gen = SmoothTransition((y0, y1), (ts, ts + dt), method="poly", differential_order=2)
# create vectorized functions
self.control_input = np.vectorize(self._control_input, otypes=[np.float])
self.system_state = np.vectorize(self._system_sate, otypes=[np.float])
def __new__(cls, array):
array = asarray(array)
assert numpy.prod(array.shape)
# Handle children with shape
child_shape = array.flat[0].shape
assert all(elem.shape == child_shape for elem in array.flat)
if child_shape:
# Destroy structure
direct_array = numpy.empty(array.shape + child_shape, dtype=object)
for alpha in numpy.ndindex(array.shape):
for beta in numpy.ndindex(child_shape):
direct_array[alpha + beta] = Indexed(array[alpha], beta)
array = direct_array
# Constant folding
if all(isinstance(elem, Constant) for elem in array.flat):
return Literal(numpy.vectorize(attrgetter('value'))(array))
self = super(ListTensor, cls).__new__(cls)
self.array = array
return self
def _power_level_from_power_spectrogram(spectrogram: ndarray) -> ndarray:
# default value for min_decibel found by experiment (all values except for 0s were above this bound)
def power_to_decibel(x, min_decibel: float = -150) -> float:
if x == 0:
return min_decibel
l = 10 * math.log10(x)
return min_decibel if l < min_decibel else l
return vectorize(power_to_decibel)(spectrogram)
def _is_enum(feature_values, enum_threshold):
are_all_ints = np.vectorize(lambda val: float(val).is_integer())
return (
len(np.unique(feature_values)) <= enum_threshold and
np.all(are_all_ints(feature_values))
)
def __init__(self, M):
oprint(3, "Initializing bond objective")
self.M = M
self.matrix_function = self.get_matrix_function()
self.evaluate_score_matrix_vect = np.vectorize(self.evaluate_score_matrix, otypes=[np.float], excluded=['match'])
def normalize_to_zero(self, y_coordinates):
vertical_offset = y_coordinates[0]
if vertical_offset == 0:
return y_coordinates
fix_offset = np.vectorize(lambda x: x - vertical_offset)
y_coordinates = fix_offset(y_coordinates)
return y_coordinates
def calculate_target_coordinates(self):
def simple_function(x):
y = 0
x = float(x)
for i, c in enumerate(reversed(self.constants)):
y += c * (x / 2000) ** i
return (y * self.scaling)
calculate = np.vectorize(simple_function)
x_variables = np.arange(self.major_axis_span, dtype=float)
y_variables = calculate(x_variables)
return self.prepare_coordinates(x_variables, y_variables)
def calculate_target_coordinates(self):
amplitude = self.amplitude
coef = (2 * pi) / self.period
phase = radians(self.phase)
def simple_sine(x):
return (amplitude * sin((x * coef - phase)))
calculate = np.vectorize(simple_sine)
x_variables = np.arange(self.major_axis_span, dtype=float)
y_variables = calculate(x_variables)
y_variables = self.normalize_to_zero(y_variables)
return self.prepare_coordinates(x_variables, y_variables)
def test_mem_vectorise(self, level=rlevel):
# Ticket #325
vt = np.vectorize(lambda *args: args)
vt(np.zeros((1, 2, 1)), np.zeros((2, 1, 1)), np.zeros((1, 1, 2)))
vt(np.zeros((1, 2, 1)), np.zeros((2, 1, 1)), np.zeros((1,
1, 2)), np.zeros((2, 2)))
def test_refcount_vectorize(self, level=rlevel):
# Ticket #378
def p(x, y):
return 123
v = np.vectorize(p)
_assert_valid_refcount(v)
def test_simple(self):
def addsubtract(a, b):
if a > b:
return a - b
else:
return a + b
f = vectorize(addsubtract)
r = f([0, 3, 6, 9], [1, 3, 5, 7])
assert_array_equal(r, [1, 6, 1, 2])
def test_scalar(self):
def addsubtract(a, b):
if a > b:
return a - b
else:
return a + b
f = vectorize(addsubtract)
r = f([0, 3, 6, 9], 5)
assert_array_equal(r, [5, 8, 1, 4])
def test_large(self):
x = np.linspace(-3, 2, 10000)
f = vectorize(lambda x: x)
y = f(x)
assert_array_equal(y, x)
def test_keywords(self):
def foo(a, b=1):
return a + b
f = vectorize(foo)
args = np.array([1, 2, 3])
r1 = f(args)
r2 = np.array([2, 3, 4])
assert_array_equal(r1, r2)
r1 = f(args, 2)
r2 = np.array([3, 4, 5])
assert_array_equal(r1, r2)
def test_keywords_no_func_code(self):
# This needs to test a function that has keywords but
# no func_code attribute, since otherwise vectorize will
# inspect the func_code.
import random
try:
vectorize(random.randrange) # Should succeed
except:
raise AssertionError()
def test_keywords3_ticket_2100(self):
# Test excluded with mixed positional and kwargs: ticket 2100
def mypolyval(x, p):
_p = list(p)
res = _p.pop(0)
while _p:
res = res * x + _p.pop(0)
return res
vpolyval = np.vectorize(mypolyval, excluded=['p', 1])
ans = [3, 6]
assert_array_equal(ans, vpolyval(x=[0, 1], p=[1, 2, 3]))
assert_array_equal(ans, vpolyval([0, 1], p=[1, 2, 3]))
assert_array_equal(ans, vpolyval([0, 1], [1, 2, 3]))
def test_keywords4_ticket_2100(self):
# Test vectorizing function with no positional args.
@vectorize
def f(**kw):
res = 1.0
for _k in kw:
res *= kw[_k]
return res
assert_array_equal(f(a=[1, 2], b=[3, 4]), [3, 8])
def test_coverage1_ticket_2100(self):
def foo():
return 1
f = vectorize(foo)
assert_array_equal(f(), 1)
def test_assigning_docstring(self):
def foo(x):
return x
doc = "Provided documentation"
f = vectorize(foo, doc=doc)
assert_equal(f.__doc__, doc)