def theta_ratio_bounds(theta, theta_tol, ratio, ratio_tol): """ Prepare last four arguments to blobs2features. Check bounds on theta so that zero is not crossed and on ration so that one is not crossed, either of which would indicate a feature flipped around its primary axis. """ # adjust tolerances down with small angles ratio_tol *= _sin(abs(theta)) theta_tol *= _sin(abs(theta)) if theta > 0.0: min_theta, max_theta = max(0.0, theta - theta_tol), theta + theta_tol elif theta < 0.0: min_theta, max_theta = theta - theta_tol, min(0.0, theta + theta_tol) else: # zero? weird. min_theta, max_theta = 0.0, 0.0 if ratio > 1.0: min_ratio, max_ratio = max(1.0, ratio - ratio_tol), ratio + ratio_tol elif ratio < 1.0: min_ratio, max_ratio = ratio - ratio_tol, min(1.0, ratio + ratio_tol) else: # one? weird. min_ratio, max_ratio = 1.0, 1.0 return min_theta, max_theta, min_ratio, max_ratio
def rel_rot(self, k_j, k_i, j_i): """ Especifica una serie de angulos para rotar la camara """ self.k = _cos(k_j) * self.k + _sin( k_j) * self.j # Posicion de los vectores en espacio 3D: self.j = self.k @ self.i # self.k = _cos(k_i) * self.k + _sin(k_i) * self.i # j k y z self.i = self.j @ self.k # |/ |/ self.j = _cos(j_i) * self.j + _sin(j_i) * self.i # -·-i -·-x self.i = self.j @ self.k # /| /| self.k /= abs(self.k) # self.i /= abs(self.i) # self.j /= abs(self.j) #
def _measure(p1, p2, p3): """ Return hypotenuse, ratio and theta for a trio of ordered points. """ ha, hb = _hypot(p3.x - p1.x, p3.y - p1.y), _hypot(p2.x - p1.x, p2.y - p1.y) va, vb = Vector(p1, p2), Vector(p1, p3) theta = _atan2(va.y, va.x) x = vb.x * _cos(-theta) - vb.y * _sin(-theta) y = vb.x * _sin(-theta) + vb.y * _cos(-theta) ratio = ha / hb theta = _atan2(y, x) return hb, ratio, theta
def gauss(self, mu, sigma): # When x and y are two variables from [0, 1), uniformly # distributed, then # # cos(2*pi*x)*sqrt(-2*log(1-y)) # sin(2*pi*x)*sqrt(-2*log(1-y)) # # are two *independent* variables with normal distribution # (mu = 0, sigma = 1). # (Lambert Meertens) # (corrected version; bug discovered by Mike Miller, fixed by LM) # Multithreading note: When two threads call this function # simultaneously, it is possible that they will receive the # same return value. The window is very small though. To # avoid this, you have to use a lock around all calls. (I # didn't want to slow this down in the serial case by using a # lock here.) random = self.random z = self.gauss_next self.gauss_next = None if z is None: x2pi = random() * TWOPI g2rad = _sqrt(-2.0 * _log(1.0 - random())) z = _cos(x2pi) * g2rad self.gauss_next = _sin(x2pi) * g2rad return mu + z * sigma
def rotozoom(self, surface, angle, size): """ Return Surface rotated and resized by the given angle and size. """ if not angle: width = int(surface.get_width()*size) height = int(surface.get_height()*size) return self.scale(surface, (width, height)) theta = angle*self.deg_rad width_i = int(surface.get_width()*size) height_i = int(surface.get_height()*size) cos_theta = _fabs( _cos(theta) ) sin_theta = _fabs( _sin(theta) ) width_f = int( _ceil((width_i*cos_theta)+(height_i*sin_theta)) ) if width_f % 2: width_f += 1 height_f = int( _ceil((width_i*sin_theta)+(height_i*cos_theta)) ) if height_f % 2: height_f += 1 surf = Surface((width_f,height_f)) surf.saveContext() surf.translate(width_f/2.0, height_f/2.0) surf.rotate(-theta) surf.drawImage(surface.canvas, 0, 0, surface.get_width(), surface.get_height(), -width_i/2, -height_i/2, width_i, height_i) surf.restoreContext() return surf
def rotate(m,angle,v): """ :param m: should be colunm major :param angle: in degree :param v: :return: in row major """ c = _cos(angle) s = _sin(angle) axis = normalize(v) temp =(1. - c) * axis Rotate = numpy.zeros((4, 4), 'f') Rotate[0][0] = c + temp[0] * axis[0] Rotate[0][1] = 0 + temp[0] * axis[1] + s * axis[2] Rotate[0][2] = 0 + temp[0] * axis[2] - s * axis[1] Rotate[1][0] = 0 + temp[1] * axis[0] - s * axis[2] Rotate[1][1] = c + temp[1] * axis[1] Rotate[1][2] = 0 + temp[1] * axis[2] + s * axis[0] Rotate[2][0] = 0 + temp[2] * axis[0] + s * axis[1] Rotate[2][1] = 0 + temp[2] * axis[1] - s * axis[0] Rotate[2][2] = c + temp[2] * axis[2] Result = numpy.zeros((4, 4), 'f') Result[0] = m[0] * Rotate[0][0] + m[1] * Rotate[0][1] + m[2] * Rotate[0][2] Result[1] = m[0] * Rotate[1][0] + m[1] * Rotate[1][1] + m[2] * Rotate[1][2] Result[2] = m[0] * Rotate[2][0] + m[1] * Rotate[2][1] + m[2] * Rotate[2][2] Result[3] = m[3] return Result.T
def rotozoom(self, surface, angle, size): """ Return Surface rotated and resized by the given angle and size. """ if not angle: width = int(surface.getWidth()*size) height = int(surface.getHeight()*size) return self.scale(surface, (width, height)) theta = angle*self.deg_rad width_i = int(surface.getWidth()*size) height_i = int(surface.getHeight()*size) cos_theta = _fabs( _cos(theta) ) sin_theta = _fabs( _sin(theta) ) width_f = int( _ceil((width_i*cos_theta)+(height_i*sin_theta)) ) if width_f % 2: width_f += 1 height_f = int( _ceil((width_i*sin_theta)+(height_i*cos_theta)) ) if height_f % 2: height_f += 1 surf = Surface((width_f,height_f), BufferedImage.TYPE_INT_ARGB) at = AffineTransform() at.translate(width_f/2, height_f/2) at.rotate(-theta) g2d = surf.createGraphics() ot = g2d.getTransform() g2d.setTransform(at) g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR) g2d.drawImage(surface, -width_i//2, -height_i//2, width_i, height_i, None) g2d.setTransform(ot) g2d.dispose() return surf
def rotozoom(surface, angle, size): """ Return Surface rotated and resized by the given angle and size. """ if not angle: width = int(surface.getWidth() * size) height = int(surface.getHeight() * size) return scale(surface, (width, height)) theta = angle * _deg_rad width_i = int(surface.getWidth() * size) height_i = int(surface.getHeight() * size) cos_theta = _fabs(_cos(theta)) sin_theta = _fabs(_sin(theta)) width_f = int(_ceil((width_i * cos_theta) + (height_i * sin_theta))) if width_f % 2: width_f += 1 height_f = int(_ceil((width_i * sin_theta) + (height_i * cos_theta))) if height_f % 2: height_f += 1 surf = Surface((width_f, height_f), BufferedImage.TYPE_INT_ARGB) at = AffineTransform() at.translate(width_f / 2.0, height_f / 2.0) at.rotate(-theta) g2d = surf.createGraphics() ot = g2d.getTransform() g2d.setTransform(at) g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR) g2d.drawImage(surface, -width_i // 2, -height_i // 2, width_i, height_i, None) g2d.setTransform(ot) g2d.dispose() return surf
def gauss(self, mu, sigma): # """Gaussian distribution. # mu is the mean, and sigma is the standard deviation. This is # slightly faster than the normalvariate() function. # Not thread-safe without a lock around calls. # """ # When x and y are two variables from [0, 1), uniformly # distributed, then # # cos(2*pi*x)*sqrt(-2*log(1-y)) # sin(2*pi*x)*sqrt(-2*log(1-y)) # # are two *independent* variables with normal distribution # (mu = 0, sigma = 1). # (Lambert Meertens) # (corrected version; bug discovered by Mike Miller, fixed by LM) # Multithreading note: When two threads call this function # simultaneously, it is possible that they will receive the # same return value. The window is very small though. To # avoid this, you have to use a lock around all calls. (I # didn't want to slow this down in the serial case by using a # lock here.) __random = self.random z = self.gauss_next self.gauss_next = None if z is None: x2pi = __random() * TWOPI g2rad = _sqrt(-2.0 * _log(1.0 - __random())) z = _cos(x2pi) * g2rad self.gauss_next = _sin(x2pi) * g2rad return mu + z*sigma
def rotate(surface, angle): """ Return Surface rotated by the given angle. """ if not angle: return surface.copy() theta = angle * _deg_rad width_i = surface.getWidth() height_i = surface.getHeight() cos_theta = _fabs(_cos(theta)) sin_theta = _fabs(_sin(theta)) width_f = int((width_i * cos_theta) + (height_i * sin_theta)) height_f = int((width_i * sin_theta) + (height_i * cos_theta)) surf = Surface((width_f, height_f), BufferedImage.TYPE_INT_ARGB) at = AffineTransform() at.translate(width_f / 2.0, height_f / 2.0) at.rotate(-theta) g2d = surf.createGraphics() ot = g2d.getTransform() g2d.setTransform(at) g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR) g2d.drawImage(surface, -width_i // 2, -height_i // 2, None) g2d.setTransform(ot) g2d.dispose() return surf
def rotozoom(self, surface, angle, size): """ Return Surface rotated and resized by the given angle and size. """ if not angle: width = int(surface.get_width() * size) height = int(surface.get_height() * size) return self.scale(surface, (width, height)) theta = angle * self.deg_rad width_i = int(surface.get_width() * size) height_i = int(surface.get_height() * size) cos_theta = _fabs(_cos(theta)) sin_theta = _fabs(_sin(theta)) width_f = int(_ceil((width_i * cos_theta) + (height_i * sin_theta))) if width_f % 2: width_f += 1 height_f = int(_ceil((width_i * sin_theta) + (height_i * cos_theta))) if height_f % 2: height_f += 1 surf = Surface((width_f, height_f)) surf.saveContext() surf.translate(width_f / 2.0, height_f / 2.0) surf.rotate(-theta) surf.drawImage(surface.canvas, 0, 0, surface.get_width(), surface.get_height(), -width_i / 2, -height_i / 2, width_i, height_i) surf.restoreContext() return surf
def rotate(self, surface, angle): """ Return Surface rotated by the given angle. """ if not angle: return surface.copy() theta = angle*self.deg_rad width_i = surface.getWidth() height_i = surface.getHeight() cos_theta = _fabs( _cos(theta) ) sin_theta = _fabs( _sin(theta) ) width_f = int( (width_i*cos_theta)+(height_i*sin_theta) ) height_f = int( (width_i*sin_theta)+(height_i*cos_theta) ) surf = Surface((width_f,height_f), BufferedImage.TYPE_INT_ARGB) at = AffineTransform() at.translate(width_f/2, height_f/2) at.rotate(-theta) g2d = surf.createGraphics() ot = g2d.getTransform() g2d.setTransform(at) g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR) g2d.drawImage(surface, -width_i//2, -height_i//2, None) g2d.setTransform(ot) g2d.dispose() return surf
def _integrand(self, theta, phi): """Integrand function.""" sin_theta = _sin(theta) cos_theta = _cos(theta) return sin_theta * cos_theta * self.spectrum(sin_theta, theta, phi) * \ _cexp(1j*self._phase(sin_theta, cos_theta, phi, self.x, self._ry, self._rz))
def abs_rot(self, k_j, k_i, j_i): """ Especifica una serie de angulos fijar la orientacion de la camara """ global i_vector, j_vector, k_vector i = +i_vector j = +j_vector k = +k_vector k = _cos(k_j) * k + _sin( k_j) * j # Posicion de los vectores en espacio 3D: j = k @ i # k = _cos(k_i) * k + _sin(k_i) * i # j k y z i = j @ k # |/ |/ j = _cos(j_i) * j + _sin(j_i) * i # -·-i -·-x i = j @ k # /| /| self.i = i # self.j = j # self.k = k #
def normal(self, mu=0, sigma=1.0): """ :param mu: mean :param sigma: standard deviation :return: random number under a normal distribution with specified mean and standard deviation """ u1, u2 = self.random(), self.random() z1 = _sqrt(-2.0 * _log(u1)) * _cos(2 * _pi * u2) z2 = _sqrt(-2.0 * _log(u1)) * _sin(2 * _pi * u2) return mu + z1 * sigma
def gauss(self, mu, sigma): random = self.random z = self.gauss_next self.gauss_next = None if z is None: x2pi = random() * TWOPI g2rad = _sqrt(-2.0 * _log(1.0 - random())) z = _cos(x2pi) * g2rad self.gauss_next = _sin(x2pi) * g2rad return mu + z * sigma
def gauss(self, mu, sigma): random = self.random z = self.gauss_next self.gauss_next = None if (z is None): x2pi = (random() * TWOPI) g2rad = _sqrt((-2.0 * _log((1.0 - random())))) z = (_cos(x2pi) * g2rad) self.gauss_next = (_sin(x2pi) * g2rad) return (mu + (z * sigma))
def rotate(a=0., x=0., y=0., z=1.): a = _radians(a) s, c = _sin(a), _cos(a) h = _sqrt(x * x + y * y + z * z) x, y, z = x / h, y / h, z / h sx, sy, sz = s * x, s * y, s * z oc = 1. - c return [[oc * x * x + c, oc * x * y - sz, oc * x * z + sy, 0.], [oc * x * y + sz, oc * y * y + c, oc * y * z - sx, 0.], [oc * x * z - sy, oc * y * z + sx, oc * z * z + c, 0.], [0., 0., 0., 1.]]
def exp(q: Quaternion or float) -> Quaternion: """Return the exponential of a quaternion.""" if isinstance(q, Quaternion): a = q.real if q.is_scalar(): return Quaternion(_exp(a), 0, 0, 0) theta = q.vector_norm % tau return _exp(a)*(_cos(theta) + q.unit_vector()*_sin(theta)) elif isinstance(q, (int, float)): return Quaternion(_exp(q), 0, 0, 0) else: return TypeError
def gauss(self, mu, sigma): """Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls. """ random = self.random z = self.gauss_next self.gauss_next = None if z is None: x2pi = random() * TWOPI g2rad = _sqrt(-2.0 * _log(1.0 - random())) z = _cos(x2pi) * g2rad self.gauss_next = _sin(x2pi) * g2rad return mu + z * sigma
def rotate(self, surface, angle): """ Return Surface rotated by the given angle. """ if not angle: return surface.copy() theta = angle * self.deg_rad width_i = surface.get_width() height_i = surface.get_height() cos_theta = _fabs(_cos(theta)) sin_theta = _fabs(_sin(theta)) width_f = int((width_i * cos_theta) + (height_i * sin_theta)) height_f = int((width_i * sin_theta) + (height_i * cos_theta)) surf = Surface((width_f, height_f)) surf.saveContext() surf.translate(width_f / 2.0, height_f / 2.0) surf.rotate(-theta) surf.drawImage(surface.canvas, -width_i / 2, -height_i / 2) surf.restoreContext() return surf
def rotate(self, surface, angle): """ Return Surface rotated by the given angle. """ if not angle: return surface.copy() theta = angle*self.deg_rad width_i = surface.get_width() height_i = surface.get_height() cos_theta = _fabs( _cos(theta) ) sin_theta = _fabs( _sin(theta) ) width_f = int( (width_i*cos_theta)+(height_i*sin_theta) ) height_f = int( (width_i*sin_theta)+(height_i*cos_theta) ) surf = Surface((width_f,height_f)) surf.saveContext() surf.translate(width_f/2.0, height_f/2.0) surf.rotate(-theta) surf.drawImage(surface.canvas, -width_i/2, -height_i/2) surf.restoreContext() return surf
def test_evalonarray_ctypes(): a = frange('lambda x: x', 10) evalonarray('lambda x: _sin(x)', a) for i, j in enumerate(a): if _sin(i) != j: raise ValueError("Values should be equal")
def sin(op1): return _sin(op1)
def benchmark(): """ Run some benchmarks for clambdify and frange. NumPy and Psyco are used as reference if available. """ from time import time from timeit import Timer def fbenchmark(f, var=[Symbol('x')]): """ Do some benchmarks with f using clambdify, lambdify and psyco. """ global cf, pf, psyf start = time() cf = clambdify(var, f) print('compile time (including sympy overhead): %f s' % ( time() - start)) pf = lambdify(var, f, 'math') psyf = None psyco = import_module('psyco') if psyco: psyf = lambdify(var, f, 'math') psyco.bind(psyf) code = '''for x in (i/1000. for i in range(1000)): f(%s)''' % ('x,'*len(var)).rstrip(',') t1 = Timer(code, 'from __main__ import cf as f') t2 = Timer(code, 'from __main__ import pf as f') if psyf: t3 = Timer(code, 'from __main__ import psyf as f') else: t3 = None print('for x = (0, 1, 2, ..., 999)/1000') print('20 times in 3 runs') print('compiled: %.4f %.4f %.4f' % tuple(t1.repeat(3, 20))) print('Python lambda: %.4f %.4f %.4f' % tuple(t2.repeat(3, 20))) if t3: print('Psyco lambda: %.4f %.4f %.4f' % tuple(t3.repeat(3, 20))) print('big function:') from sympy import _exp, _sin, _cos, pi x = Symbol('x') ## f1 = diff(_exp(x)**2 - _sin(x)**pi, x) \ ## * x**12-2*x**3+2*_exp(x**2)-3*x**7+4*_exp(123+x-x**5+2*x**4) \ ## * ((x + pi)**5).expand() f1 = 2*_exp(x**2) + x**12*(-pi*_sin(x)**((-1) + pi)*_cos(x) + 2*_exp(2*x)) \ + 4*(10*pi**3*x**2 + 10*pi**2*x**3 + 5*pi*x**4 + 5*x*pi**4 + pi**5 + x**5)*_exp(123 + x + 2*x**4 - x**5) - 2*x**3 - 3*x**7 fbenchmark(f1) print() print('simple function:') y = Symbol('y') f2 = sqrt(x*y) + x*5 fbenchmark(f2, [x, y]) times = 100000 fstr = '_exp(_sin(_exp(-x**2)) + sqrt(pi)*_cos(x**5/(x**3-x**2+pi*x)))' print print('frange with f(x) =') print(fstr) print('for x=1, ..., %i' % times) print('in 3 runs including full compile time') t4 = Timer("frange('lambda x: %s', 0, %i)" % (fstr, times), 'from __main__ import frange') numpy = import_module('numpy') print('frange: %.4f %.4f %.4f' % tuple(t4.repeat(3, 1))) if numpy: t5 = Timer('x = arange(%i); result = %s' % (times, fstr), 'from numpy import arange, sqrt, exp, sin, cos, exp, pi') print('numpy: %.4f %.4f %.4f' % tuple(t5.repeat(3, 1)))
def test_evalonarray_ctypes(): a = frange('lambda x: x', 10) evalonarray('lambda x: _sin(x)', a) for i, j in enumerate(a): assert _sin(i) == j
dab = _sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2) dbc = _sqrt((c.x - b.x) ** 2 + (c.y - b.y) ** 2) dac = _sqrt((c.x - a.x) ** 2 + (c.y - a.y) ** 2) ratios = {(0, 1, 2): dac/dab, (1, 0, 2): dbc/dab, (2, 1, 0): dac/dbc} tab = _atan2(b.y - a.y, b.x - a.x) tba = _atan2(a.y - b.y, a.x - b.x) tac = _atan2(c.y - a.y, c.x - a.x) tca = _atan2(a.y - c.y, a.x - c.x) tbc = _atan2(c.y - b.y, c.x - b.x) tcb = _atan2(b.y - c.y, b.x - c.x) thetas = { (0, 1, 2): _atan2((c.x - a.x) * _sin(-tab) + (c.y - a.y) * _cos(-tab), (c.x - a.x) * _cos(-tab) - (c.y - a.y) * _sin(-tab)), (1, 0, 2): _atan2((c.x - b.x) * _sin(-tba) + (c.y - b.y) * _cos(-tba), (c.x - b.x) * _cos(-tba) - (c.y - b.y) * _sin(-tba)), (0, 2, 1): _atan2((b.x - a.x) * _sin(-tac) + (b.y - a.y) * _cos(-tac), (b.x - a.x) * _cos(-tac) - (b.y - a.y) * _sin(-tac)), (2, 0, 1): _atan2((b.x - c.x) * _sin(-tca) + (b.y - c.y) * _cos(-tca), (b.x - c.x) * _cos(-tca) - (b.y - c.y) * _sin(-tca)), (1, 2, 0): _atan2((a.x - b.x) * _sin(-tbc) + (a.y - b.y) * _cos(-tbc), (a.x - b.x) * _cos(-tbc) - (a.y - b.y) * _sin(-tbc)), (2, 1, 0): _atan2((a.x - c.x) * _sin(-tcb) + (a.y - c.y) * _cos(-tcb),
def benchmark(): """ Run some benchmarks for clambdify and frange. NumPy and Psyco are used as reference if available. """ from time import time from timeit import Timer def fbenchmark(f, var=[Symbol('x')]): """ Do some benchmarks with f using clambdify, lambdify and psyco. """ global cf, pf, psyf start = time() cf = clambdify(var, f) print('compile time (including sympy overhead): %f s' % (time() - start)) pf = lambdify(var, f, 'math') psyf = None psyco = import_module('psyco') if psyco: psyf = lambdify(var, f, 'math') psyco.bind(psyf) code = '''for x in (i/1000. for i in range(1000)): f(%s)''' % ('x,' * len(var)).rstrip(',') t1 = Timer(code, 'from __main__ import cf as f') t2 = Timer(code, 'from __main__ import pf as f') if psyf: t3 = Timer(code, 'from __main__ import psyf as f') else: t3 = None print('for x = (0, 1, 2, ..., 999)/1000') print('20 times in 3 runs') print('compiled: %.4f %.4f %.4f' % tuple(t1.repeat(3, 20))) print('Python lambda: %.4f %.4f %.4f' % tuple(t2.repeat(3, 20))) if t3: print('Psyco lambda: %.4f %.4f %.4f' % tuple(t3.repeat(3, 20))) print('big function:') from sympy import _exp, _sin, _cos, pi, lambdify x = Symbol('x') ## f1 = diff(_exp(x)**2 - _sin(x)**pi, x) \ ## * x**12-2*x**3+2*_exp(x**2)-3*x**7+4*_exp(123+x-x**5+2*x**4) \ ## * ((x + pi)**5).expand() f1 = 2*_exp(x**2) + x**12*(-pi*_sin(x)**((-1) + pi)*_cos(x) + 2*_exp(2*x)) \ + 4*(10*pi**3*x**2 + 10*pi**2*x**3 + 5*pi*x**4 + 5*x*pi**4 + pi**5 + x**5)*_exp(123 + x + 2*x**4 - x**5) - 2*x**3 - 3*x**7 fbenchmark(f1) print() print('simple function:') y = Symbol('y') f2 = sqrt(x * y) + x * 5 fbenchmark(f2, [x, y]) times = 100000 fstr = '_exp(_sin(_exp(-x**2)) + sqrt(pi)*_cos(x**5/(x**3-x**2+pi*x)))' print print('frange with f(x) =') print(fstr) print('for x=1, ..., %i' % times) print('in 3 runs including full compile time') t4 = Timer("frange('lambda x: %s', 0, %i)" % (fstr, times), 'from __main__ import frange') numpy = import_module('numpy') print('frange: %.4f %.4f %.4f' % tuple(t4.repeat(3, 1))) if numpy: t5 = Timer('x = arange(%i); result = %s' % (times, fstr), 'from numpy import arange, sqrt, exp, sin, cos, exp, pi') print('numpy: %.4f %.4f %.4f' % tuple(t5.repeat(3, 1)))
for n in range(-nl,nr+1): sumV += f[n+nl] * y[i+n] g.append(sumV) return g if len(self.filter) > len(y): raise TypeError("timeseries size must be bigger than size of filter") # pad the signal at the extremes with values taken from the signal itself # OLD padding: # firstvals = mattranslate(matabs(mattranslate(y[1:self.nright+1][::-1],-y[0])),y[0]) # lastvals = mattranslate(matabs(mattranslate(y[-self.nleft-1:-1][::-1], - y[-1])),y[-1]) # NEW padding: should preserve 1st order derivative at extremes ystart = y[0] #sum(y[0:int(self.nright/4)]) yend = y[-1] #sum(y[-int(self.nleft/4):-1]) firstvals = mattranslate(matscalarprod(mattranslate(y[1:self.nright+1][::-1],-ystart), -1),ystart) lastvals = mattranslate(matscalarprod(mattranslate(y[-self.nleft-1:-1][::-1], - yend), -1),yend) y = firstvals + y + lastvals # convolve the padded signal with the filter list return fconv(self.filter, y, self.nleft, self.nright) if __name__ == '__main__': from math import sin as _sin from random import random as _rand TS = [_rand()*0.05+_sin(2*3.14*j/(25+175*j/1000)) for j in range(1000)] print TS SGfilter = Savgol(nleft=16, nright=16, order=4, deriv=0) print SGfilter.filterTS(TS) SGfilter = Savgol(nleft=16, nright=16, order=4, deriv=1) print SGfilter.filterTS(TS)
def update(self,time=1): distance = self.s*time y = (_sin(self.d))*distance x = (_cos(self.d))*distance self.x += x self.y += y
"""Random variable generators.
def sin(x): return _sin(x) if common._use_radians else _sin(_rad(x))
def update(self, time=1): distance = self.s * time y = (_sin(self.d)) * distance x = (_cos(self.d)) * distance self.x += x self.y += y
def blobs2features(blobs, min_hypot=0, min_theta=-pi, max_theta=pi, min_ratio=0, max_ratio=1): """ Generate a stream of features conforming to limits. Yields 5-element tuples: indexes for three blobs followed by feature ratio, theta. """ count = len(blobs) # one-dimensional arrays of simple positions xs = _array([blob.x for blob in blobs], dtype=float) ys = _array([blob.y for blob in blobs], dtype=float) # # two-dimensional arrays of component distances between each blob # dx = b.x - a.x, dy = b.y - a.y # xs_ = repeat(reshape(xs, (1, count)), count, 0) ys_ = repeat(reshape(ys, (1, count)), count, 0) dxs, dys = transpose(xs_) - xs_, transpose(ys_) - ys_ # # two-dimensional array of distances between each blob # distance = sqrt(dx^2 + dy^2) # distances = nsqrt(dxs ** 2 + dys ** 2) # # Make a list of eligible eligible blob pairs # hypoteni = distances.copy() hypoteni[distances < min_hypot] = 0 hypot_nonzero = nonzero(hypoteni) ## Prepend separation distance, longest-to-shortest #blobs_sorted = [(distances[i,j], i, j) for (i, j) in zip(*hypot_nonzero)] # Prepend combined pixel size, largest-to-smallest blobs_sorted = [(blobs[i].size + blobs[j].size, i, j) for (i, j) in zip(*hypot_nonzero)] blobs_sorted.sort(reverse=True) # # check each hypotenuse for an eligible third point # for (row, (sort_value, i, j)) in enumerate(blobs_sorted): # # vector theta for hypotenuse (i, j) # ij_theta = _atan2(dys[i,j], dxs[i,j]) # # rotate each blob[k] around blob[i] by -theta, to get a hypotenuse-relative theta for (i, k) # ik_xs = dxs[i,:] * _cos(-ij_theta) - dys[i,:] * _sin(-ij_theta) ik_ys = dxs[i,:] * _sin(-ij_theta) + dys[i,:] * _cos(-ij_theta) ik_thetas = arctan2(ik_ys, ik_xs) ik_thetas = [(blobs[k].size, k, theta) for (k, theta) in enumerate(ik_thetas)] ik_thetas.sort(reverse=True) # # check each blob[k] for correct distance ratio # for (size, k, theta) in ik_thetas: ratio = distances[i,k] / distances[i,j] if theta < min_theta or max_theta < theta: continue if ratio < min_ratio or max_ratio < ratio: continue if i == j or i == k or j == k: continue yield (i, j, k, ratio, theta)
def quaternion(theta=0, u=(1., 0., 0.)): w = _cos(theta/2.) x, y, z = (ui*_sin(theta/2.) for ui in u) return w, (x, y, z)
def _phase(self, sin_theta, cos_theta, phi, x, y, z): """Phase function.""" sin_phi = _sin(phi) cos_phi = _cos(phi) return self._k*(sin_theta*(y*sin_phi - z*cos_phi) + cos_theta*x)