def test_power_complex(self): x = np.array([1+2j, 2+3j, 3+4j]) assert_equal(x**0, [1., 1., 1.]) assert_equal(x**1, x) assert_equal(x**2, [-3+4j, -5+12j, -7+24j]) assert_equal(x**3, [(1+2j)**3, (2+3j)**3, (3+4j)**3]) assert_equal(x**4, [(1+2j)**4, (2+3j)**4, (3+4j)**4]) assert_almost_equal(x**(-1), [1/(1+2j), 1/(2+3j), 1/(3+4j)]) assert_almost_equal(x**(-2), [1/(1+2j)**2, 1/(2+3j)**2, 1/(3+4j)**2]) assert_almost_equal(x**(-3), [(-11+2j)/125, (-46-9j)/2197, (-117-44j)/15625]) assert_almost_equal(x**(0.5), [ncu.sqrt(1+2j), ncu.sqrt(2+3j), ncu.sqrt(3+4j)]) assert_almost_equal(x**14, [-76443+16124j, 23161315+58317492j, 5583548873 + 2465133864j]) # Ticket #836 def assert_complex_equal(x, y): assert_array_equal(x.real, y.real) assert_array_equal(x.imag, y.imag) for z in [complex(0, np.inf), complex(1, np.inf)]: z = np.array([z], dtype=np.complex_) assert_complex_equal(z**1, z) assert_complex_equal(z**2, z*z) assert_complex_equal(z**3, z*z*z)
def test_power_complex(self): x = np.array([1 + 2j, 2 + 3j, 3 + 4j]) assert_equal(x ** 0, [1.0, 1.0, 1.0]) assert_equal(x ** 1, x) assert_almost_equal(x ** 2, [-3 + 4j, -5 + 12j, -7 + 24j]) assert_almost_equal(x ** 3, [(1 + 2j) ** 3, (2 + 3j) ** 3, (3 + 4j) ** 3]) assert_almost_equal(x ** 4, [(1 + 2j) ** 4, (2 + 3j) ** 4, (3 + 4j) ** 4]) assert_almost_equal(x ** (-1), [1 / (1 + 2j), 1 / (2 + 3j), 1 / (3 + 4j)]) assert_almost_equal(x ** (-2), [1 / (1 + 2j) ** 2, 1 / (2 + 3j) ** 2, 1 / (3 + 4j) ** 2]) assert_almost_equal(x ** (-3), [(-11 + 2j) / 125, (-46 - 9j) / 2197, (-117 - 44j) / 15625]) assert_almost_equal(x ** (0.5), [ncu.sqrt(1 + 2j), ncu.sqrt(2 + 3j), ncu.sqrt(3 + 4j)]) norm = 1.0 / ((x ** 14)[0]) assert_almost_equal( x ** 14 * norm, [i * norm for i in [-76443 + 16124j, 23161315 + 58317492j, 5583548873 + 2465133864j]] ) # Ticket #836 def assert_complex_equal(x, y): assert_array_equal(x.real, y.real) assert_array_equal(x.imag, y.imag) for z in [complex(0, np.inf), complex(1, np.inf)]: err = np.seterr(invalid="ignore") z = np.array([z], dtype=np.complex_) try: assert_complex_equal(z ** 1, z) assert_complex_equal(z ** 2, z * z) assert_complex_equal(z ** 3, z * z * z) finally: np.seterr(**err)
def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): arr = asanyarray(a) is_float16_result = False ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims) # Cast bool, unsigned int, and int to float64 by default if dtype is None: if issubclass(arr.dtype.type, (nt.integer, nt.bool_)): dtype = mu.dtype('f8') elif issubclass(arr.dtype.type, nt.float16): dtype = mu.dtype('f4') is_float16_result = True if isinstance(ret, mu.ndarray): ret = um.sqrt(ret, out=ret) if is_float16_result and out is None: ret = arr.dtype.type(ret) elif hasattr(ret, 'dtype'): if is_float16_result: ret = arr.dtype.type(um.sqrt(ret)) else: ret = ret.dtype.type(um.sqrt(ret)) else: ret = um.sqrt(ret) return ret
def gauss_from_twiss(emit, beta, alpha): phi = 2 * pi * np.random.rand() u = np.random.rand() a = sqrt(-2 * np.log((1 - u)) * emit) x = a * sqrt(beta) * cos(phi) xp = -a / sqrt(beta) * (sin(phi) + alpha * cos(phi)) return (x, xp)
def moments(self, x, y, cut=0): n = len(x) inds = np.arange(n) mx = np.mean(x) my = np.mean(y) x = x - mx y = y - my x2 = x * x mxx = sum(x2) / n y2 = y * y myy = sum(y2) / n xy = x * y mxy = sum(xy) / n emitt = sqrt(mxx * myy - mxy * mxy) if cut > 0: inds = [] beta = mxx / emitt gamma = myy / emitt alpha = mxy / emitt emittp = gamma * x2 + 2. * alpha * xy + beta * y2 inds0 = np.argsort(emittp) n1 = np.round(n * (100 - cut) / 100) inds = inds0[0:n1] mx = np.mean(x[inds]) my = np.mean(y[inds]) x1 = x[inds] - mx y1 = y[inds] - my mxx = np.sum(x1 * x1) / n1 myy = np.sum(y1 * y1) / n1 mxy = np.sum(x1 * y1) / n1 emitt = sqrt(mxx * myy - mxy * mxy) return mx, my, mxx, mxy, myy, emitt
def _std(array, epsilon=1.0, bounds=None, axis=None, dtype=None, keepdims=False, accountant=None, nan=False): ret = _var(array, epsilon=epsilon, bounds=bounds, axis=axis, dtype=dtype, keepdims=keepdims, accountant=accountant, nan=nan) if isinstance(ret, mu.ndarray): ret = um.sqrt(ret) elif hasattr(ret, 'dtype'): ret = ret.dtype.type(um.sqrt(ret)) else: ret = um.sqrt(ret) return ret
def save_bessel_functions(N): """Generate N 2D shapelets and plot.""" beta2 = beta ** 2 B = empty((grid_size, grid_size)) # Don't want matrix behaviour here # --------------------------------------------------------------------------- # Basis function constants, and hermite polynomials # --------------------------------------------------------------------------- vals = [[n, 1.0 / sqrt((2 ** n) * sqrt(pi) * factorial(n, 1) * beta), 0, 0, 0] for n in xrange(N)] expreal = exp(-theta.real ** 2 / (2 * beta2)) expimag = exp(-theta.imag ** 2 / (2 * beta2)) for n, K, H, _, _ in vals: vals[n][3] = K * jn(n, theta.real) * expreal vals[n][4] = K * jn(n, theta.imag) * expimag pylab.figure() l = 0 for v1 in vals: for v2 in vals: B = v1[3] * v2[4] pylab.subplot(N, N, l + 1) pylab.axis("off") pylab.imshow(B.T) l += 1 pylab.suptitle("Shapelets N=%i Beta=%.4f" % (N, beta)) # pylab.savefig("B%i.png" % N) pylab.show()
def _std(a, epsilon=1.0, range=None, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, nan=False): ret = _var(a, epsilon=epsilon, range=range, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims, nan=nan) if isinstance(ret, mu.ndarray): ret = um.sqrt(ret, out=ret) elif hasattr(ret, 'dtype'): ret = ret.dtype.type(um.sqrt(ret)) else: ret = um.sqrt(ret) return ret
def model_two_basis_functions(): """ A test function that returns a model similar to model(), except that it uses the shapelet basis functions as the surface brightness and does not normalize. """ data = empty((nepochs, grid_size, grid_size)) beta2 = beta ** 2 for t, z in star_track(nepochs): if t == 0: x = raytrace() else: x = raytrace(rE_true, z) n = 0 K1 = 1.0 / sqrt(2 ** n * sqrt(pi) * factorial(n, 1) * beta) H1 = hermite(n) data[t] = (K1 * H1(x.real / beta) * exp(-x.real ** 2 / (2 * beta2))) * ( K1 * H1(x.imag / beta) * exp(-x.imag ** 2 / (2 * beta2)) ) # data[t] *= 100 # n = 1 # K1 = 1.0/sqrt(2**n * sqrt(pi) * factorial(n,1) * beta) # H1 = hermite(n) # # data[t] += (K1 * H1(x.real/beta) * exp(-x.real**2/(2*beta2))) * \ # (K1 * H1(x.imag/beta) * exp(-x.imag**2/(2*beta2))) return data
def test_power_complex(self): x = np.array([1 + 2j, 2 + 3j, 3 + 4j]) assert_equal(x**0, [1., 1., 1.]) assert_equal(x**1, x) assert_almost_equal(x**2, [-3 + 4j, -5 + 12j, -7 + 24j]) assert_almost_equal(x**3, [(1 + 2j)**3, (2 + 3j)**3, (3 + 4j)**3]) assert_almost_equal(x**4, [(1 + 2j)**4, (2 + 3j)**4, (3 + 4j)**4]) assert_almost_equal(x**(-1), [1 / (1 + 2j), 1 / (2 + 3j), 1 / (3 + 4j)]) assert_almost_equal( x**(-2), [1 / (1 + 2j)**2, 1 / (2 + 3j)**2, 1 / (3 + 4j)**2]) assert_almost_equal(x**(-3), [(-11 + 2j) / 125, (-46 - 9j) / 2197, (-117 - 44j) / 15625]) assert_almost_equal( x**(0.5), [ncu.sqrt(1 + 2j), ncu.sqrt(2 + 3j), ncu.sqrt(3 + 4j)]) norm = 1. / ((x**14)[0]) assert_almost_equal(x**14 * norm, [ i * norm for i in [-76443 + 16124j, 23161315 + 58317492j, 5583548873 + 2465133864j] ]) # Ticket #836 def assert_complex_equal(x, y): assert_array_equal(x.real, y.real) assert_array_equal(x.imag, y.imag) for z in [complex(0, np.inf), complex(1, np.inf)]: z = np.array([z], dtype=np.complex_) with np.errstate(invalid="ignore"): assert_complex_equal(z**1, z) assert_complex_equal(z**2, z * z) assert_complex_equal(z**3, z * z * z)
def gauss_from_twiss(emit, beta, alpha): phi = 2*pi * np.random.rand() u = np.random.rand() a = sqrt(-2*np.log( (1-u)) * emit) x = a * sqrt(beta) * cos(phi) xp = -a / sqrt(beta) * ( sin(phi) + alpha * cos(phi) ) return (x, xp)
def A_z_F(x, xi, xi2, h_nodes, z): return (-((xi + 1j * x**2)**2 - 0.5)**2 * P(xi2 * h_nodes * (xi + 1j * x**2)) / sqrt(2 * xi + 1j * x**2) * exp(-1j * pi / 4) * exp(xi * 1j * (z - 2 * xi2 * h_nodes)) + (1 + 1j * x**2)**2 * P(xi2 * h_nodes * (1 + 1j * x**2)) * sqrt(2 + 1j * x**2) * x**2 * exp(1j * pi / 4) * exp(1j * (z - 2 * xi2 * h_nodes))) * exp( -(z - 2 * xi2 * h_nodes) * x**2)
def check_power_complex(self): x = array([1 + 2j, 2 + 3j, 3 + 4j]) assert_equal(x ** 0, [1.0, 1.0, 1.0]) assert_equal(x ** 1, x) assert_equal(x ** 2, [-3 + 4j, -5 + 12j, -7 + 24j]) assert_almost_equal(x ** (-1), [1 / (1 + 2j), 1 / (2 + 3j), 1 / (3 + 4j)]) assert_almost_equal(x ** (-3), [(-11 + 2j) / 125, (-46 - 9j) / 2197, (-117 - 44j) / 15625]) assert_almost_equal(x ** (0.5), [ncu.sqrt(1 + 2j), ncu.sqrt(2 + 3j), ncu.sqrt(3 + 4j)]) assert_almost_equal(x ** 14, [-76443 + 16124j, 23161315 + 58317492j, 5583548873 + 2465133864j])
def test_power_float(self): x = np.array([1., 2., 3.]) assert_equal(x**0, [1., 1., 1.]) assert_equal(x**1, x) assert_equal(x**2, [1., 4., 9.]) y = x.copy() y **= 2 assert_equal(y, [1., 4., 9.]) assert_almost_equal(x**(-1), [1., 0.5, 1./3]) assert_almost_equal(x**(0.5), [1., ncu.sqrt(2), ncu.sqrt(3)])
def test_power_float(self): x = np.array([1., 2., 3.]) assert_equal(x**0, [1., 1., 1.]) assert_equal(x**1, x) assert_equal(x**2, [1., 4., 9.]) y = x.copy() y **= 2 assert_equal(y, [1., 4., 9.]) assert_almost_equal(x**(-1), [1., 0.5, 1. / 3]) assert_almost_equal(x**(0.5), [1., ncu.sqrt(2), ncu.sqrt(3)])
def test_power_float(self): x = np.array([1.0, 2.0, 3.0]) assert_equal(x ** 0, [1.0, 1.0, 1.0]) assert_equal(x ** 1, x) assert_equal(x ** 2, [1.0, 4.0, 9.0]) y = x.copy() y **= 2 assert_equal(y, [1.0, 4.0, 9.0]) assert_almost_equal(x ** (-1), [1.0, 0.5, 1.0 / 3]) assert_almost_equal(x ** (0.5), [1.0, ncu.sqrt(2), ncu.sqrt(3)])
def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims) if isinstance(ret, mu.ndarray): ret = um.sqrt(ret, out=ret) else: ret = um.sqrt(ret) return ret
def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims) if isinstance(ret, mu.ndarray): ret = um.sqrt(ret, out=ret) else: ret = ret.dtype.type(um.sqrt(ret)) return ret
def get_distance(locA, locB): # use haversine forumla print "ayyo" earth_rad = 6371.0 dlat = deg2rad(locB[0] - locA[0]) dlon = deg2rad(locB[1] - locA[1]) a = sin(dlat / 2) * sin(dlat / 2) + \ cos(deg2rad(locA[0])) * cos(deg2rad(locB[0])) * \ sin(dlon / 2) * sin(dlon / 2) c = 2 * arctan2(sqrt(a), sqrt(1 - a)) return earth_rad * c
def get_envelope(p_array, tws_i=Twiss()): tws = Twiss() p = p_array.p() dx = tws_i.Dx * p dy = tws_i.Dy * p dpx = tws_i.Dxp * p dpy = tws_i.Dyp * p x = p_array.x() - dx px = p_array.px() - dpx y = p_array.y() - dy py = p_array.py() - dpy if ne_flag: px = ne.evaluate('px * (1. - 0.5 * px * px - 0.5 * py * py)') py = ne.evaluate('py * (1. - 0.5 * px * px - 0.5 * py * py)') else: px = px * (1. - 0.5 * px * px - 0.5 * py * py) py = py * (1. - 0.5 * px * px - 0.5 * py * py) tws.x = mean(x) tws.y = mean(y) tws.px = mean(px) tws.py = mean(py) if ne_flag: tw_x = tws.x tw_y = tws.y tw_px = tws.px tw_py = tws.py tws.xx = mean(ne.evaluate('(x - tw_x) * (x - tw_x)')) tws.xpx = mean(ne.evaluate('(x - tw_x) * (px - tw_px)')) tws.pxpx = mean(ne.evaluate('(px - tw_px) * (px - tw_px)')) tws.yy = mean(ne.evaluate('(y - tw_y) * (y - tw_y)')) tws.ypy = mean(ne.evaluate('(y - tw_y) * (py - tw_py)')) tws.pypy = mean(ne.evaluate('(py - tw_py) * (py - tw_py)')) else: tws.xx = mean((x - tws.x) * (x - tws.x)) tws.xpx = mean((x - tws.x) * (px - tws.px)) tws.pxpx = mean((px - tws.px) * (px - tws.px)) tws.yy = mean((y - tws.y) * (y - tws.y)) tws.ypy = mean((y - tws.y) * (py - tws.py)) tws.pypy = mean((py - tws.py) * (py - tws.py)) tws.p = mean(p_array.p()) tws.E = p_array.E #tws.de = p_array.de tws.emit_x = sqrt(tws.xx * tws.pxpx - tws.xpx**2) tws.emit_y = sqrt(tws.yy * tws.pypy - tws.ypy**2) #print tws.emit_x, sqrt(tws.xx*tws.pxpx-tws.xpx**2), tws.emit_y, sqrt(tws.yy*tws.pypy-tws.ypy**2) tws.beta_x = tws.xx / tws.emit_x tws.beta_y = tws.yy / tws.emit_y tws.alpha_x = -tws.xpx / tws.emit_x tws.alpha_y = -tws.ypy / tws.emit_y return tws
def get_envelope(p_array, tws_i=Twiss()): tws = Twiss() p = p_array.p() dx = tws_i.Dx*p dy = tws_i.Dy*p dpx = tws_i.Dxp*p dpy = tws_i.Dyp*p x = p_array.x() - dx px = p_array.px() - dpx y = p_array.y() - dy py = p_array.py() - dpy if ne_flag: px = ne.evaluate('px * (1. - 0.5 * px * px - 0.5 * py * py)') py = ne.evaluate('py * (1. - 0.5 * px * px - 0.5 * py * py)') else: px = px*(1.-0.5*px*px - 0.5*py*py) py = py*(1.-0.5*px*px - 0.5*py*py) tws.x = mean(x) tws.y = mean(y) tws.px =mean(px) tws.py =mean(py) if ne_flag: tw_x = tws.x tw_y = tws.y tw_px = tws.px tw_py = tws.py tws.xx = mean(ne.evaluate('(x - tw_x) * (x - tw_x)')) tws.xpx = mean(ne.evaluate('(x - tw_x) * (px - tw_px)')) tws.pxpx =mean(ne.evaluate('(px - tw_px) * (px - tw_px)')) tws.yy = mean(ne.evaluate('(y - tw_y) * (y - tw_y)')) tws.ypy = mean(ne.evaluate('(y - tw_y) * (py - tw_py)')) tws.pypy =mean(ne.evaluate('(py - tw_py) * (py - tw_py)')) else: tws.xx = mean((x - tws.x)*(x - tws.x)) tws.xpx = mean((x-tws.x)*(px-tws.px)) tws.pxpx = mean((px-tws.px)*(px-tws.px)) tws.yy = mean((y-tws.y)*(y-tws.y)) tws.ypy = mean((y-tws.y)*(py-tws.py)) tws.pypy = mean((py-tws.py)*(py-tws.py)) tws.p = mean( p_array.p()) tws.E = p_array.E #tws.de = p_array.de tws.emit_x = sqrt(tws.xx*tws.pxpx-tws.xpx**2) tws.emit_y = sqrt(tws.yy*tws.pypy-tws.ypy**2) #print tws.emit_x, sqrt(tws.xx*tws.pxpx-tws.xpx**2), tws.emit_y, sqrt(tws.yy*tws.pypy-tws.ypy**2) tws.beta_x = tws.xx/tws.emit_x tws.beta_y = tws.yy/tws.emit_y tws.alpha_x = -tws.xpx/tws.emit_x tws.alpha_y = -tws.ypy/tws.emit_y return tws
def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True): ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims, where=where) if isinstance(ret, mu.ndarray): ret = um.sqrt(ret, out=ret) elif hasattr(ret, 'dtype'): ret = ret.dtype.type(um.sqrt(ret)) else: ret = um.sqrt(ret) return ret
def sizes(self): if self.beta_x != 0: self.gamma_x = (1. + self.alpha_x**2)/self.beta_x else: self.gamma_x = 0. if self.beta_y != 0: self.gamma_y = (1. + self.alpha_y**2)/self.beta_y else: self.gamma_y = 0. self.sigma_x = sqrt((self.sigma_E/self.E*self.Dx)**2 + self.emit_x*self.beta_x) self.sigma_y = sqrt((self.sigma_E/self.E*self.Dy)**2 + self.emit_y*self.beta_y) self.sigma_xp = sqrt((self.sigma_E/self.E*self.Dxp)**2 + self.emit_x*self.gamma_x) self.sigma_yp = sqrt((self.sigma_E/self.E*self.Dyp)**2 + self.emit_y*self.gamma_y)
def rv_pqw(k, p, ecc, nu): r"""Returns r and v vectors in perifocal frame. .. math:: \vec{r} = \frac{h^2}{\mu}\frac{1}{1 + e\cos(\theta)}\begin{bmatrix} \cos(\theta)\\ \sin(\theta)\\ 0 \end{bmatrix} \\\\\\ \vec{v} = \frac{h^2}{\mu}\begin{bmatrix} -\sin(\theta)\\ e+\cos(\theta)\\ 0 \end{bmatrix} Parameters ---------- k : float Standard gravitational parameter (km^3 / s^2). p : float Semi-latus rectum or parameter (km). ecc : float Eccentricity. nu: float True anomaly (rad). Returns ------- r: ndarray Position. Dimension 3 vector v: ndarray Velocity. Dimension 3 vector Examples -------- >>> from poliastro.constants import GM_earth >>> k = GM_earth #Earth gravitational parameter >>> ecc = 0.3 #Eccentricity >>> h = 60000e6 #Angular momentum of the orbit [m^2]/[s] >>> nu = np.deg2rad(120) #True Anomaly [rad] >>> p = h**2 / k #Parameter of the orbit >>> r, v = rv_pqw(k, p, ecc, nu) >>> #Printing the results r = [-5312706.25105345 9201877.15251336 0] [m] v = [-5753.30180931 -1328.66813933 0] [m]/[s] Note ---- These formulas can be checked at Curtis 3rd. Edition, page 110. Also the example proposed is 2.11 of Curtis 3rd Edition book. """ r_pqw = (np.array([cos(nu), sin(nu), 0 * nu]) * p / (1 + ecc * cos(nu))).T v_pqw = (np.array([-sin(nu), (ecc + cos(nu)), 0]) * sqrt(k / p)).T return r_pqw, v_pqw
def rv_pqw(k, p, ecc, nu): """Returns r and v vectors in perifocal frame. """ r_pqw = (np.array([cos(nu), sin(nu), 0 * nu]) * p / (1 + ecc * cos(nu))).T v_pqw = (np.array([-sin(nu), (ecc + cos(nu)), 0]) * sqrt(k / p)).T return r_pqw, v_pqw
def cartesian2cylindrical(vector, source_width, source_height, r_is_1=True): """Calculates the location on a equirectangular plane of a vector, Will work with numpy's 2D arrays of points :param vector: 3d tuple of the point the vector :param source_width: width and :param source_height: height of the equirectangular image :param r_is_1: boolean, denoting if vectors are normalized to 1 (default=True) :return: 3D tuple of the coordinates of the vector on the equirectangular plane """ middle = source_width / 2 x = vector[0] y = vector[1] z = vector[2] r = 1 if r_is_1 else sqrt(square(x) + square(y) + square(z)) theta = arccos(z / r) phi = arctan2(y, x) x1 = mod(middle + middle * phi / pi, source_width - 1) y1 = source_height * theta / pi return x1, y1
def check_power_complex(self): x = array([1 + 2j, 2 + 3j, 3 + 4j]) assert_equal(x**0, [1., 1., 1.]) assert_equal(x**1, x) assert_equal(x**2, [-3 + 4j, -5 + 12j, -7 + 24j]) assert_almost_equal(x**(-1), [1 / (1 + 2j), 1 / (2 + 3j), 1 / (3 + 4j)]) assert_almost_equal(x**(-3), [(-11 + 2j) / 125, (-46 - 9j) / 2197, (-117 - 44j) / 15625]) assert_almost_equal( x**(0.5), [ncu.sqrt(1 + 2j), ncu.sqrt(2 + 3j), ncu.sqrt(3 + 4j)]) assert_almost_equal( x**14, [-76443 + 16124j, 23161315 + 58317492j, 5583548873 + 2465133864j])
def kaiser(M,beta): """kaiser(M, beta) returns a Kaiser window of length M with shape parameter beta. """ from numpy.dual import i0 n = arange(0,M) alpha = (M-1)/2.0 return i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/i0(beta)
def get_phi_function(self, n): coeff = sqrt(2.0) / (self.RR * jn(abs(self.m) + 1, self.jzeros[n - 1])) def fun(r): return complex(coeff * jn(self.m, self.jzeros[n - 1] * r / self.RR)) return fun
def kaiser(M, beta): """kaiser(M, beta) returns a Kaiser window of length M with shape parameter beta. """ from numpy.dual import i0 n = arange(0, M) alpha = (M - 1) / 2.0 return i0(beta * sqrt(1 - ((n - alpha) / alpha)**2.0)) / i0(beta)
def m_from_twiss(Tw1, Tw2): #% Transport matrix M for two sets of Twiss parameters (alpha,beta,psi) b1 = Tw1[1] a1 = Tw1[0] psi1 = Tw1[2] b2 = Tw2[1] a2 = Tw2[0] psi2 = Tw2[2] psi = psi2-psi1 cosp = cos(psi) sinp = sin(psi) M = np.zeros((2, 2)) M[0, 0] = sqrt(b2/b1)*(cosp+a1*sinp) M[0, 1] = sqrt(b2*b1)*sinp M[1, 0] = ((a1-a2)*cosp-(1+a1*a2)*sinp)/sqrt(b2*b1) M[1, 1] = sqrt(b1/b2)*(cosp-a2*sinp) return M
def corrcoef(x, y=None, rowvar=1, bias=0): """The correlation coefficients """ c = cov(x, y, rowvar, bias) try: d = diag(c) except ValueError: # scalar covariance return 1 return c / sqrt(multiply.outer(d, d))
def fastGradientProjectionStream(f, g, gradf, proxg, x0, initLip=None): """The (fast) proximal gradient method requires a gradient of f, and a prox operator for g, supplied by gradf and proxg respectively.""" if initLip is None: Lipk = 1. else: Lipk = initLip eta = 2. xko = x0 xk = x0 yk = x0 tk = 1 def F(x): return f(x) + g(x) Fxko = F(xko) def Q(Lip, px, x): d = (px - x).flatten() # treat all matrices as vectors return f(x) + gradf(x).flatten().dot(d) + Lip * (norm(d) ** 2) / 2 + g(px) def P(Lip, x): return proxg(Lip, x - gradf(x) / Lip) """Non standard extension: expanding line search to find an initial estimate of Lipschitz constant""" for k in range(5): pyk = P(Lipk, yk) if F(pyk) > Q(Lipk, pyk, yk): break yield pyk Lipk = Lipk / (eta ** 4) """Start standard algorithm""" while True: yield xk while True: pyk = P(Lipk, yk) Fyk = F(pyk) if Fyk <= Q(Lipk, pyk, yk): break Lipk = Lipk * eta zk = pyk tkn = (1 + sqrt(1 + 4 * (tk ** 2))) / 2 if Fyk <= Fxko: # Fyk is F(zk)=F(pyk); Fxko is F(xko) xk = zk Fxk = Fyk else: xk = xko Fxk = Fxko yk = xk + (zk - xk) * tk / tkn + (xk - xko) * (tk - 1) / tkn Fxko = Fxk xko = xk tk = tkn
def normalize_by_diag(k): if k is None: return None diag_array = diag(k).copy() diag_array[diag_array == 0.] = 1. # will divide by 1 x = 1. / sqrt(repmat(as_column(diag_array), 1, len(k))) k = (k * x) * x.transpose() return k
def m_from_twiss(Tw1, Tw2): #% Transport matrix M for two sets of Twiss parameters (alpha,beta,psi) b1 = Tw1[1] a1 = Tw1[0] psi1 = Tw1[2] b2 = Tw2[1] a2 = Tw2[0] psi2 = Tw2[2] psi = psi2 - psi1 cosp = cos(psi) sinp = sin(psi) M = np.zeros((2, 2)) M[0, 0] = sqrt(b2 / b1) * (cosp + a1 * sinp) M[0, 1] = sqrt(b2 * b1) * sinp M[1, 0] = ((a1 - a2) * cosp - (1 + a1 * a2) * sinp) / sqrt(b2 * b1) M[1, 1] = sqrt(b1 / b2) * (cosp - a2 * sinp) return M
def corrcoef(x, y=None, rowvar=1, bias=0): """The correlation coefficients """ c = cov(x, y, rowvar, bias) try: d = diag(c) except ValueError: # scalar covariance return 1 return c/sqrt(multiply.outer(d,d))
def A_z(xi, xi2, h_nodes, num_nodes): # from fn_Qz_matrix # integral around branch point z_1 = xi2 * h_nodes * np.arange(num_nodes) # Pack arguments for LowLevelCallable. # data is updated at every loop. The main loop is NOT thread-safe. If the main loop # becomes parallel some day, make "data" local. data = np.array([xi, xi2, h_nodes, 0.0]) data_ptr = ctypes.cast(data.ctypes, ctypes.c_void_p) quad_args = dict(limit=200) # For num_nodes = 4, I_12 looks like [a3, a2, a1, a0, a1, a2, a3] (size: 2*num_nodes-1) # Build the second half first, then copy it to the first half I_12 = np.zeros(2 * num_nodes - 1, np.complex) for i, z in enumerate(z_1): data[3] = z if i < 2: # two first iterations, coefficients a0 and a1 int_F1_real = scipy.LowLevelCallable(A_z_F1_real.ctypes, data_ptr) int_F1_imag = scipy.LowLevelCallable(A_z_F1_imag.ctypes, data_ptr) int_F2_real = scipy.LowLevelCallable(A_z_F2_real.ctypes, data_ptr) int_F2_imag = scipy.LowLevelCallable(A_z_F2_imag.ctypes, data_ptr) I_12[i + num_nodes - 1] = 4j * ( si.quad(int_F1_real, 0, sqrt(xi), **quad_args)[0] + 1j * si.quad(int_F1_imag, 0, sqrt(xi), **quad_args)[0]) + 4 * ( si.quad(int_F2_real, 0, 50, **quad_args)[0] + 1j * si.quad(int_F2_imag, 0, 50, **quad_args)[0]) else: int_F_real = scipy.LowLevelCallable(A_z_F_real.ctypes, data_ptr) int_F_imag = scipy.LowLevelCallable(A_z_F_imag.ctypes, data_ptr) I_12[i + num_nodes - 1] = 4j * (si.quad(int_F_real, 0, 70, **quad_args)[0] + 1j * si.quad(int_F_imag, 0, 70, **quad_args)[0]) I_12[:num_nodes - 1] = I_12[:num_nodes - 1:-1] v_ind = np.arange(num_nodes) m_ind = (np.full( (num_nodes, num_nodes), num_nodes - 1) + v_ind[:, np.newaxis] - v_ind) return I_12[m_ind]
def ecef_to_lat_lon_alt1(R, deg=True): """ Fukushima implementation of the Bowring algorithm (2006), see [4] -- :param R: (X,Y,Z) -- coordinates in ECEF (numpy array) :param deg: if True then lat and lon are returned in degrees (rad otherwise) :return: (φ,θ,h) -- lat [deg], lon [deg], alt in WGS84 (numpy array) """ # WGS 84 constants a = 6378137.0 # Equatorial Radius [m] b = 6356752.314245 # Polar Radius [m] e = 0.08181919092890624 # e = sqrt(1-b²/a²) E = e**2 e1 = sqrt(1 - e**2) # e' = sqrt(1 - e²) if isinstance(R, list): R = np.array(R) p = sqrt(R[0]**2 + R[1]**2) # (1) - sqrt(X² + Y²) az = abs(R[2]) Z = e1 * az / a P = p / a S, C = Z or 1, e1 * P or 1 # (C8) - zero approximation max_iter = 5 for i in range(max_iter): A = sqrt(S**2 + C**2) Cn = P * A**3 - E * C**3 Sn = Z * A**3 + E * S**3 delta = abs(Sn / Cn - S / C) * C / S if isnan(delta): return ecef_to_lat_lon_alt1(R) if abs(delta) < 1e-10 or i == max_iter - 1: break S, C = Sn, Cn theta = np.math.atan2(R[1], R[0]) Cc = e1 * Cn phi = np.sign(R[2]) * np.math.atan2(Sn, Cc) h = (p * Cc + az * Sn - b * sqrt(Sn**2 + Cn**2)) / sqrt(Cc**2 + Sn**2) if deg: out = np.array([np.degrees(phi), np.degrees(theta), h]) else: out = np.array([phi, theta, h]) # if filter(isnan, out): # return ecef_to_lat_lon_alt1(R) return out
def ecef_to_lat_lon_alt1(R, deg=True): """ Fukushima implementation of the Bowring algorithm (2006), see [4] -- :param R: (X,Y,Z) -- coordinates in ECEF (numpy array) :param deg: if True then lat and lon are returned in degrees (rad otherwise) :return: (φ,θ,h) -- lat [deg], lon [deg], alt in WGS84 (numpy array) """ # WGS 84 constants a = 6378137.0 # Equatorial Radius [m] b = 6356752.314245 # Polar Radius [m] e = 0.08181919092890624 # e = sqrt(1-b²/a²) E = e ** 2 e1 = sqrt(1 - e ** 2) # e' = sqrt(1 - e²) if isinstance(R, list): R = np.array(R) p = sqrt(R[0] ** 2 + R[1] ** 2) # (1) - sqrt(X² + Y²) az = abs(R[2]) Z = e1 * az / a P = p / a S, C = Z or 1, e1 * P or 1 # (C8) - zero approximation max_iter = 5 for i in range(max_iter): A = sqrt(S ** 2 + C ** 2) Cn = P * A ** 3 - E * C ** 3 Sn = Z * A ** 3 + E * S ** 3 delta = abs(Sn / Cn - S / C) * C / S if isnan(delta): return ecef_to_lat_lon_alt1(R) if abs(delta) < 1e-10 or i == max_iter - 1: break S, C = Sn, Cn theta = np.math.atan2(R[1], R[0]) Cc = e1 * Cn phi = np.sign(R[2]) * np.math.atan2(Sn, Cc) h = (p * Cc + az * Sn - b * sqrt(Sn ** 2 + Cn ** 2)) / sqrt(Cc ** 2 + Sn ** 2) if deg: out = np.array([np.degrees(phi), np.degrees(theta), h]) else: out = np.array([phi, theta, h]) # if filter(isnan, out): # return ecef_to_lat_lon_alt1(R) return out
def normalize_by_diag(k: Optional[np.ndarray]) -> Optional[np.ndarray]: """ Given a kernel matrix, normalize the matrix by its diagonal making its diagonal 1s and the rest of values normalized accordingly. """ if k is None: return None diag_array = diag(k).copy() # TODO should we emit warnings? diag_array[diag_array == 0.] = 1. # will divide by 1 x = 1. / sqrt(np.repeat(diag_array[:, None], len(k), axis=1)) k = (k * x) * x.transpose() return k
def ecef_to_lat_lon_alt(R, deg=True): """ Fukushima implementation of the Bowring algorithm, see [3] -- equations (C7) - (C12) :param R: (X,Y,Z) -- coordinates in ECEF (numpy array) :param deg: if True then lat and lon are returned in degrees (rad otherwise) :return: (φ,θ,h) -- lat [deg], lon [deg], alt in WGS84 (numpy array) """ # WGS 84 constants a = 6378137.0 # Equatorial Radius [m] b = 6356752.314245 # Polar Radius [m] e = 0.08181919092890624 # e = sqrt(1-b²/a²) # e1 = sqrt(1 - e ** 2) # e' = sqrt(1 - e²) e1 = 0.99664718932816898 # c = a * e ** 2 # (6) c = 42697.67279723605 if isinstance(R, list): R = np.array(R) p = sqrt(R[0]**2 + R[1]**2) # (1) - sqrt(X² + Y²) T = R[2] / (e1 * p) or 1. # (C8) - zero approximation for i in range(10): C = np.power(1 + T**2, -0.5) # (C9) S = C * T # (C9) T_new = (e1 * R[2] + c * S**3) / (p - c * C**3) # (C7) delta = T_new - T T = T_new if abs(delta) / T < 1e-9: break theta = np.math.atan2(R[1], R[0]) phi = np.math.atan2(T, e1) # (C10) T1 = 1 + T**2 if p > R[2]: # (C11) h = sqrt(T1 - e**2) / e1 * (p - a / sqrt(T1)) else: # (C12) h = sqrt(T1 - e**2) * (R[2] / T - b / sqrt(T1)) if deg: out = np.array([np.degrees(phi), np.degrees(theta), h]) else: out = np.array([phi, theta, h]) return out
def ecef_to_lat_lon_alt(R, deg=True): """ Fukushima implementation of the Bowring algorithm, see [3] -- equations (C7) - (C12) :param R: (X,Y,Z) -- coordinates in ECEF (numpy array) :param deg: if True then lat and lon are returned in degrees (rad otherwise) :return: (φ,θ,h) -- lat [deg], lon [deg], alt in WGS84 (numpy array) """ # WGS 84 constants a = 6378137.0 # Equatorial Radius [m] b = 6356752.314245 # Polar Radius [m] e = 0.08181919092890624 # e = sqrt(1-b²/a²) # e1 = sqrt(1 - e ** 2) # e' = sqrt(1 - e²) e1 = 0.99664718932816898 # c = a * e ** 2 # (6) c = 42697.67279723605 if isinstance(R, list): R = np.array(R) p = sqrt(R[0] ** 2 + R[1] ** 2) # (1) - sqrt(X² + Y²) T = R[2] / (e1 * p) or 1. # (C8) - zero approximation for i in range(10): C = np.power(1 + T ** 2, -0.5) # (C9) S = C * T # (C9) T_new = (e1 * R[2] + c * S ** 3) / (p - c * C ** 3) # (C7) delta = T_new - T T = T_new if abs(delta) / T < 1e-9: break theta = np.math.atan2(R[1], R[0]) phi = np.math.atan2(T, e1) # (C10) T1 = 1 + T ** 2 if p > R[2]: # (C11) h = sqrt(T1 - e ** 2) / e1 * (p - a / sqrt(T1)) else: # (C12) h = sqrt(T1 - e ** 2) * (R[2] / T - b / sqrt(T1)) if deg: out = np.array([np.degrees(phi), np.degrees(theta), h]) else: out = np.array([phi, theta, h]) return out
def _quadratic_coeff(signal): zi = -3 + 2 * sqrt(2.0) K = len(signal) yplus = zeros((K, ), signal.dtype.char) powers = zi**arange(K) yplus[0] = signal[0] + zi * add.reduce(powers * signal) for k in range(1, K): yplus[k] = signal[k] + zi * yplus[k - 1] output = zeros((K, ), signal.dtype.char) output[K - 1] = zi / (zi - 1) * yplus[K - 1] for k in range(K - 2, -1, -1): output[k] = zi * (output[k + 1] - yplus[k]) return output * 8.0
def test_power_float(self): x = np.array([1.0, 2.0, 3.0]) assert_equal(x ** 0, [1.0, 1.0, 1.0]) assert_equal(x ** 1, x) assert_equal(x ** 2, [1.0, 4.0, 9.0]) y = x.copy() y **= 2 assert_equal(y, [1.0, 4.0, 9.0]) assert_almost_equal(x ** (-1), [1.0, 0.5, 1.0 / 3]) assert_almost_equal(x ** (0.5), [1.0, ncu.sqrt(2), ncu.sqrt(3)]) for out, inp, msg in _gen_alignment_data(dtype=np.float32, type="unary"): exp = [ncu.sqrt(i) for i in inp] assert_almost_equal(inp ** (0.5), exp, err_msg=msg) np.sqrt(inp, out=out) assert_equal(out, exp, err_msg=msg) for out, inp, msg in _gen_alignment_data(dtype=np.float64, type="unary"): exp = [ncu.sqrt(i) for i in inp] assert_almost_equal(inp ** (0.5), exp, err_msg=msg) np.sqrt(inp, out=out) assert_equal(out, exp, err_msg=msg)
def _quadratic_coeff(signal): zi = -3 + 2 * sqrt(2.0) K = len(signal) yplus = zeros((K,), signal.dtype.char) powers = zi ** arange(K) yplus[0] = signal[0] + zi * add.reduce(powers * signal) for k in range(1, K): yplus[k] = signal[k] + zi * yplus[k - 1] output = zeros((K,), signal.dtype.char) output[K - 1] = zi / (zi - 1) * yplus[K - 1] for k in range(K - 2, -1, -1): output[k] = zi * (output[k + 1] - yplus[k]) return output * 8.0
def plotfeaturemaps(y): # Init plt.ioff() f = plt.figure() # Determine Number of Features numfeatures = y.shape[1] # Determine Optimal Split sx = round(sqrt(numfeatures)) sy = ceil(numfeatures / sx) # Plot for k in range(numfeatures): f.add_subplot(sy, sx, k) plt.imshow(y[0, k, :, :]) plt.axis('off')
def calc_dist(self, pos_mat, j): #find distance of every particle from particle j using periodic boundary conditions ref_pos_vec = pos_mat[j] pbc_pos_mat = self.check_pbc(np.tile(ref_pos_vec, (self.N, 1)), pos_mat) dist_vec = np.zeros(self.N) dist_vec.fill(self.L * 10) mask1 = abs(ref_pos_vec[0] - pbc_pos_mat[:, 0]) < self.r mask2 = abs(ref_pos_vec[1] - pbc_pos_mat[:, 1]) < self.r mask = mask1 & mask2 dist_vec[mask] = sqrt((ref_pos_vec[0] - pbc_pos_mat[mask, 0])**2 + (ref_pos_vec[1] - pbc_pos_mat[mask, 1])**2) return (dist_vec)
def projectedSubgradientStream(sgf, proj, x0, theta=1.): """ Minimize a function f whose subgradient is sgf over a convex set of radius theta and orthogonal projection operator proj, starting at x0. """ theta = float(theta) xk = x0 # Using optimal step size for fixed number of iterations for k in count(1): yield xk gk = sgf(xk) 'Theoretically motivated step size, sometimes decays too slowly' tk = sqrt(2 * theta / k) / norm(gk) uncon = xk - tk * gk xk = proj(uncon)
def gauss_spline(x, n): r"""Gaussian approximation to B-spline basis function of order n. Parameters ---------- x : array a knot vector n : int The order of the spline. Must be non-negative, i.e., n >= 0 Returns ------- res : ndarray B-spline basis function values approximated by a zero-mean Gaussian function. Notes ----- The B-spline basis function can be approximated well by a zero-mean Gaussian function with standard-deviation equal to :math:`\sigma=(n+1)/12` for large `n` : .. math:: \frac{1}{\sqrt {2\pi\sigma^2}}exp(-\frac{x^2}{2\sigma}) References ---------- .. [1] Bouma H., Vilanova A., Bescos J.O., ter Haar Romeny B.M., Gerritsen F.A. (2007) Fast and Accurate Gaussian Derivatives Based on B-Splines. In: Sgallari F., Murli A., Paragios N. (eds) Scale Space and Variational Methods in Computer Vision. SSVM 2007. Lecture Notes in Computer Science, vol 4485. Springer, Berlin, Heidelberg .. [2] http://folk.uio.no/inf3330/scripting/doc/python/SciPy/tutorial/old/node24.html Examples -------- We can calculate B-Spline basis functions approximated by a gaussian distribution: >>> from scipy.signal import gauss_spline, bspline >>> knots = np.array([-1.0, 0.0, -1.0]) >>> gauss_spline(knots, 3) array([0.15418033, 0.6909883, 0.15418033]) # may vary >>> bspline(knots, 3) array([0.16666667, 0.66666667, 0.16666667]) # may vary """ x = asarray(x) signsq = (n + 1) / 12.0 return 1 / sqrt(2 * pi * signsq) * exp(-x**2 / 2 / signsq)
def lat_lon_alt_to_ecef_xyz(R): """ see [1] p. 512 :param R: (φ,θ,h) -- lat [deg], lon [deg], alt in WGS84 (numpy array) :return: (X,Y,Z) -- coordinates in ECEF (numpy array) """ # WGS 84 constants a2 = 6378137.0 ** 2 # Equatorial Radius [m] b2 = 6356752.314245 ** 2 # Polar Radius [m] radius = lambda phi: sqrt(a2 * (cos(phi)) ** 2 + b2 * (sin(phi)) ** 2) f, t, h = np.deg2rad(R[0]), np.deg2rad(R[1]), R[2] X = cos(t) * cos(f) * (h + a2 / radius(f)) Y = sin(t) * cos(f) * (h + a2 / radius(f)) Z = sin(f) * (h + b2 / radius(f)) return np.array([X, Y, Z])
def gauss_spline(x, n): """Gaussian approximation to B-spline basis function of order n. Parameters ---------- n : int The order of the spline. Must be nonnegative, i.e. n >= 0 References ---------- .. [1] Bouma H., Vilanova A., Bescos J.O., ter Haar Romeny B.M., Gerritsen F.A. (2007) Fast and Accurate Gaussian Derivatives Based on B-Splines. In: Sgallari F., Murli A., Paragios N. (eds) Scale Space and Variational Methods in Computer Vision. SSVM 2007. Lecture Notes in Computer Science, vol 4485. Springer, Berlin, Heidelberg """ signsq = (n + 1) / 12.0 return 1 / sqrt(2 * pi * signsq) * exp(-x ** 2 / 2 / signsq)
def gauss_spline(x,n): """Gaussian approximation to B-spline basis function of order n. """ signsq = (n+1) / 12.0 return 1/sqrt(2*pi*signsq) * exp(-x**2 / 2 / signsq)
def test_simple(self): assert_almost_equal(ncu.hypot(1, 1), ncu.sqrt(2)) assert_almost_equal(ncu.hypot(0, 0), 0)
def _coeff_smooth(lam): xi = 1 - 96 * lam + 24 * lam * sqrt(3 + 144 * lam) omeg = arctan2(sqrt(144 * lam - 1), sqrt(xi)) rho = (24 * lam - 1 - sqrt(xi)) / (24 * lam) rho = rho * sqrt((48 * lam + 24 * lam * sqrt(3 + 144 * lam)) / xi) return rho, omeg