def calculate_phase_factor_coeff(vj, freq, num_f, num_p, num_b): """Calculate the overall phase factor spectrum coefficients. Runs once per qtcurrent function call. Eqns. 5.7 and 5.12 in Kittara's thesis. Args: vj (ndarray): Voltage across the SIS junction freq (ndarray): Frequencies num_f (int): Number of non-harmonically related frequencies num_p (int): Number of harmonics num_b (int): Summation limits for phase factor coefficients Returns: ndarray: Phase factor spectrum coefficients (C_k(H) in Kittara) """ # Number of bias voltage points npts = len(vj[0, 0, :]) # Summation limits for phase factor coefficients if isinstance(num_b, int): num_b = tuple([num_b] * num_f) # Junction drive level: # alpha[f, p, i] in R^(num_f+1)(num_p+1)(npts) # Eqn. 5.5 in Kittara's thesis alpha = np.zeros_like(vj, dtype=float) for f in range(1, num_f + 1): for p in range(1, num_p + 1): alpha[f, p, :] = np.abs(vj[f, p, :]) / (p * freq[f]) # Junction voltage phase: # phi[f, p, i] in R^(num_f+1)(num_p+1)(npts) phi = np.angle(vj) # in radians # Complex coefficients from the Jacobi-Anger equality: # jac[f, p, n, i] in C^(num_f+1)(num_p+1)(num_b*2+1)(npts) # Equation 5.7 in Kittara's thesis # Note: This chunk of code dominates the computation time of this function # I tried using the recurrence relation, but ran into numerical errors jac = np.zeros((num_f + 1, num_p + 1, max(num_b) * 2 + 1, npts), dtype=complex) for f in range(1, num_f + 1): for p in range(1, num_p + 1): jac[f, p, 0] = bessel(0, alpha[f, p]) for n in range(1, num_b[f - 1] + 1): # using Bessel function identity jn = bessel(n, alpha[f, p]) jac[f, p, n] = jn * np.exp(-1j * n * phi[f, p]) jac[f, p, -n] = (-1)**n * np.conj(jac[f, p, n]) # Overall phase factor coefficients: # ckh[f, k, i] in C^(num_f+1)(num_b*2+1)(npts) ckh = _convolve_coefficients(jac) return ckh
def windolf_sampling(self, params, layer): a = np.abs(params) alpha = np.angle(params) if layer=='visible': rates = np.abs(self.clamp) phases = vm(alpha, a*rates / self.sigma_sq) return rates*np.exp(1j*phases) else: bessels = bessel(a - self.biases)/ self.sigma_sq custom_kernel = np.ones((self.pool_size, self.pool_size)) sum_bessels = conv(bessels, custom_kernel, mode='valid') # Downsample sum_bessels = sum_bessels[0::self.pool_stride, 0::self.pool_stride] bessel_sftmx_denom = 1.0 + sum_bessels upsampled_denom = bessel_sftmx_denom.repeat(self.pool_stride, axis=0).repeat(self.pool_stride, axis=1) hid_cat_P = bessels / upsampled_denom pool_P = 1.0 - 1.0 / bessel_sftmx_denom hid_rates, pool_rates = self._dbn_maxpool_sample_helper(hid_cat_P, pool_P) hid_phases = vm(alpha, a*hid_rates / self.sigma_sq) hid_samples = hid_rates*np.exp(1j*hid_phases) pool_phases = np.sum(imx.view_as_blocks(hid_phases, (self.pool_size, self.pool_size)), axis=(2,3)) pool_samples = pool_rates*np.exp(1j*pool_phases) return hid_samples, pool_samples
def get_FD_qT_space(self, x, y, z, Q2, mu2, zetaF, zetaD, qT, charge, method='FFT'): D = self.D # hint: # hankel transform for F*D (see Eq.75 of reference) # FD_qT_space = \int_0^inf dbT bT J0(qT*bT) F(bT) D(bT) <- change var: k = qT*bT # = (1/qT**2) * \int_0^inf dk J0(k) [k F(k/bT) D(k/qT)] FD_bT_space = lambda bT: self.get_FD_bT_space(x, y, z, Q2, mu2, zetaF, zetaD, bT**2, charge) f = lambda k: k * FD_bT_space(k / qT) if method == 'FFT': f = np.vectorize(f) FD_qT_space = D['hankel'].transform( f, ret_err=False)[0] / qT**2 * 2 * np.pi elif method == 'quad': integrand = lambda k: bessel(0, k) * f(k) FD_qT_space = quad(integrand, 1e-4, np.inf)[0] / qT**2 * 2 * np.pi return FD_qT_space
def plot_sample_image(image, image_parameters, figsize=(15, 5)): """ Plot a sample image. Inputs: image: image of the particles image_parameters: list with the values of the image parameters figsize: figure size [list of two positive numbers] """ ### CALCULATE BACKGROUND # initialize the image at the background level image_background = ones((image_size, image_size)) * image_background_level # add gradient to image background if gradient_intensity!=0: image_background = image_background + gradient_intensity * (image_coordinate_x * sin(gradient_direction) + image_coordinate_y * cos(gradient_direction) ) / (sqrt(2) * image_size) ### CALCULATE IMAGE PARTICLES image_particles = zeros((image_size, image_size)) for particle_center_x, particle_center_y, particle_radius, particle_bessel_orders, particle_intensities, ellipsoidal_orientation in zip(particle_center_x_list, particle_center_y_list, particle_radius_list, particle_bessel_orders_list, particle_intensities_list, ellipsoidal_orientation_list): # calculate the radial distance from the center of the particle # normalized by the particle radius radial_distance_from_particle = sqrt((image_coordinate_x - particle_center_x)**2 + (image_coordinate_y - particle_center_y)**2 + .001**2) / particle_radius # for elliptical particles rotated_distance_x = (image_coordinate_x - particle_center_x)*cos(ellipsoidal_orientation) + (image_coordinate_y - particle_center_y)*sin(ellipsoidal_orientation) rotated_distance_y = -(image_coordinate_x - particle_center_x)*sin(ellipsoidal_orientation) + (image_coordinate_y - particle_center_y)*cos(ellipsoidal_orientation) elliptical_distance_from_particle = sqrt((rotated_distance_x)**2 + (rotated_distance_y / ellipticity)**2 + .001**2) / particle_radius # calculate particle profile for particle_bessel_order, particle_intensity in zip(particle_bessel_orders, particle_intensities): image_particle = 4 * particle_bessel_order**2.5 * (bessel(particle_bessel_order, elliptical_distance_from_particle) / elliptical_distance_from_particle)**2 image_particles = image_particles + particle_intensity * image_particle # calculate image without noise as background image plus particle image image_particles_without_noise = clip(image_background + image_particles, 0, 1) ### ADD NOISE image_particles_with_noise = poisson(image_particles_without_noise * signal_to_noise_ratio**2) / signal_to_noise_ratio**2 return image_particles_with_noise
def compute_log_bessel(n, x): bessel_val = bessel(n, x) if (bessel_val == 0.0): return -np.inf log_bessel_val = np.log(bessel_val) if (np.isnan(log_bessel_val) or np.isinf(log_bessel_val)): raise ValueError return log_bessel_val
def windolf_sampling(self, params, layer): a = np.abs(params) alpha = np.angle(params) if layer == 'visible': rates = np.abs(self.clamp) elif layer == 'hidden': ipdb.set_trace() b = bessel(a - self.biases) / self.sigma_sq ber_P = b / (1.0 + b) rates = 1 * (np.random.rand(3, self.out_shape, self.out_shape) < ber_P) elif layer == 'final': b = bessel(a - self.f_biases) / self.sigma_sq ber_P = b / (1.0 + b) rates = 1 * (np.random.rand(3) < ber_P) phases = vm(alpha, a * rates / self.sigma_sq) return rates * np.exp(1j * phases)
def __init__(self, T, normalization, beta=32, m=32, init="von_mises", normalize_l1=False): """ Temporal Match Kernel Layer :param T: Periods (list) :param beta: beta param of the modified Bessel function of the first kind :param m: number of Fourier coefficients per period :param init: type of initialization ('von_mises' or 'uniform': random from uniform distribution) :param normalize_l1: Whether to L1 normalize Fourier coefficents before each forward pass """ super(TemporalMatchKernel, self).__init__() self.T = T self.beta = beta self.m = m self.normalize_l1 = normalize_l1 self.normalization = normalization # Initialization if init == "von_mises": np_a = [(bessel(0, self.beta) - np.exp(-self.beta)) / (2 * np.sinh(self.beta))] + [ bessel(i, self.beta) / np.sinh(self.beta) for i in range(1, self.m) ] np_a = np.asarray(np_a).reshape(1, -1) np_a = np.repeat(np_a, len(T), 0) elif init == "uniform": np_a = np.random.uniform(0, 1, (len(T), self.m)) else: raise NotImplementedError self.a = nn.Parameter(torch.from_numpy(np_a).float()) # (T, m) self.ms = 2 * np.pi * torch.arange(0, self.m).float() self.Ts = torch.tensor(self.T, dtype=torch.float32, requires_grad=False)
def windolf_sampling(self, params, layer): a = np.abs(params) alpha = np.angle(params) if layer=='visible': rates = np.abs(self.clamp) else: b = bessel(a - self.biases) / self.sigma_sq ber_P = b / (1.0 + b) rates = 1*(np.random.rand(1, self.out_shape, self.out_shape) < ber_P) phases = vm(alpha, a*rates / self.sigma_sq) return rates*np.exp(1j*phases)
def windolf_sampling(self, params, layer): a = np.abs(params) alpha = np.angle(params) if layer=='visible': rates = np.abs(self.clamp) #phases = np.where(rates>0, vm(alpha, rates*a / self.sigma_sq), np.angle(self.v_run[-1])) else: b = bessel(a - self.biases) / self.sigma_sq ber_P = b / (1.0 + b) rates = 1*(np.random.rand(self.out_shape) < ber_P) #phases = np.where(rates > 0, vm(alpha, rates*a / self.sigma_sq), np.angle(self.h_run[-1])) phases = vm(alpha, rates*a / self.sigma_sq) return rates*np.exp(1j*phases)
def particle_bessel_response(S:int, p:Tuple[float,float], p_r:float, orders:list, intensities:list, elip_d:float=0, ellipticity:float=1): """ Returns square array of size `S` containing response to particle a `p` """ r=radial_grid(S, p, p_r=p_r, elip_d=elip_d, ellipticity=ellipticity) if type(intensities) is Tensor: response = torch.zeros_like(r) else: response = np.zeros_like(r) for I,o in zip(intensities,orders): if type(I) is Tensor: I=I.numpy() response+=(I * 4 * o**2.5 * (bessel(o,r) / r)**2) return response
def correlation_function(r, a, mu_0): """ Correlation function :math:`B(r)`. :param r: :math:`r` :param a: :math:`a` :param mu_0: :math:`\\mu_0` The correlation function is given by .. math:: B(r) = \\mu_0^2 \\frac{2^{2/3}}{\\Gamma(1/3)} \\left(\\frac{r}{a}\\right)^{1/3} K_{1/3} \\left(\\frac{r}{a}\\right) See Salomons, equation I.39. """ return mu_0**2.0 * 2.0**(2.0/3.0) / gamma(1.0/3.0) * (r/a)**(1.0/3.0) * bessel(1.0/3.0, r/a)
def _pelectrostatic_atom(atom, r): try: _, a1, b1, a2, b2, a3, b3, c1, d1, c2, d2, c3, d3 = scattering_params[ atom.atomic_number] except KeyError: raise ValueError( 'Scattering information for element {} is unavailable.'.format( atom.element)) potential = np.zeros_like(r, dtype=np.float) for a, b, c, d in zip((a1, a2, a3), (b1, b2, b3), (c1, c2, c3), (d1, d2, d3)): potential += 2 * a * bessel(2 * pi * r * sqrt(b)) + (c / d) * np.exp( -(r * pi)**2 / d) return 2 * a0 * e * (pi**2) * potential
def correlation_function(r, a, mu_0): """ Correlation function :math:`B(r)`. :param r: :math:`r` :param a: :math:`a` :param mu_0: :math:`\\mu_0` The correlation function is given by .. math:: B(r) = \\mu_0^2 \\frac{2^{2/3}}{\\Gamma(1/3)} \\left(\\frac{r}{a}\\right)^{1/3} K_{1/3} \\left(\\frac{r}{a}\\right) See Salomons, equation I.39. """ return mu_0**2.0 * 2.0**(2.0 / 3.0) / gamma( 1.0 / 3.0) * (r / a)**(1.0 / 3.0) * bessel(1.0 / 3.0, r / a)
def r2kappa(R): """ recalulate kappa from R for von Misses function """ if R < 0.53: kappa = 2 * R + R**3 + 5 / 6 * R**5 elif R >= 0.53 and R < 0.85: kappa = -0.4 + 1.39 * R + 0.43 / (1 - R) elif R >= 0.85: kappa = 1 / (3 * R - 4 * R**2 + R**3) I0 = bessel(kappa) return kappa, I0
def MED(p,m,c,T,numparticls): theta = (k*T/(m*c**2)) c = 1/(theta*bessel(theta/2)) p = p/m gamma = zeros([1,numparticles]) for i in range(numparticles): gamma[i] = 1/sqrt((1-(p[i].dot(p[i])/c**2))) gf = 100 dg = 0.1 GammaDist = arange(0,100,df) Juttner = theta*GammaDist**2*(sqrt(1-(1-(1/GammaDist))))*e**(-GammaDist/theta) plot(GammaDist,Juttner)
def Bessel_Function(self, m, R, Vc, fc, fm): bessel_list = [] # Components for x in range(0, 10000): lateral = np.round(bessel(x, m), 2) if x > 0: if lateral == 0.0: break else: bessel_list.append(lateral) else: bessel_list.append(lateral) # Numpy Array new_bessel_list = np.array(bessel_list) # Voltage voltage_bessel_list = new_bessel_list * Vc # Average carrier power average_carrier_power = np.round((Vc**2)/(2*R), 3) # bessel power bessel_power = np.round( np.append((voltage_bessel_list[0]**2/(2*R)), voltage_bessel_list[1:]**2/R), 3) # Total power total_power = np.round(bessel_power.sum(), 3) # graph_power graph_power = np.append( voltage_bessel_list[:0:-1], voltage_bessel_list[1:]) long = int(len(graph_power)/2) graph_power = np.insert(graph_power, long, voltage_bessel_list[0]) # Frecuency frecuency = np.unique(np.append(np.array([x for x in range( fc, fc+1+fm*long, fm)]), np.array([x for x in range(fc, fc-1-fm*long, -fm)]))) return [voltage_bessel_list, average_carrier_power, bessel_power, total_power, graph_power, frecuency, long, new_bessel_list]
def _convolution_coefficient(vj, vph, num_f, num_p, num_b): """ Calculate the convolution coefficients for each tone. Eqn. 5.12 in Kittara's thesis. """ npts = np.alen(vj[0, 0, :]) if isinstance(num_b, tuple): num_b = max(num_b) # Junction drive level: alpha[f, p, i] in R^(num_f+1)(num_p+1)(npts) alpha = np.zeros((num_f + 1, num_p + 1, npts)) for f in range(1, num_f + 1): for p in range(1, num_p + 1): alpha[f, p, :] = np.abs(vj[f, p, :]) / (p * vph[f]) # Junction voltage phase: phi[f, p, i] in R^(num_f+1)(num_p+1)(npts) phi = np.angle(vj) # in radians # Jacobi-Angers coefficients: # jac[f, p, n, i] in C^(num_f+1)(num_p+1)(num_b*2+1)(npts) jac = np.zeros((num_f + 1, num_p + 1, num_b * 2 + 1, npts), dtype=complex) for f in range(1, num_f + 1): for p in range(1, num_p + 1): for n in range(-num_b, num_b + 1): jac[f, p, n] = bessel(n, alpha[f, p]) * np.exp(-1j * n * phi[f, p]) # Convolution coefficients: cc[f, k, i] in C^(num_f+1)(num_b*2+1)(npts) cc_out = _calculate_coeff(jac) # cc_out.flags.writeable = False # # DEBUG # import matplotlib.pyplot as plt # plt.figure() # for f in range(1, num_f+1): # plt.plot(vph[f]*np.arange(-num_b, num_b+1), cc_out[f, :, 70]) # plt.show() return cc_out
def get_FD_qT_space(self,x,y,z,Q2,mu2,zetaF,zetaD,qT,charge,method='FFT'): D=self.D # hint: # hankel transform for F*D (see Eq.75 of reference) # FD_qT_space = \int_0^inf dbT bT J0(qT*bT) F(bT) D(bT) <- change var: k = qT*bT # = (1/qT**2) * \int_0^inf dk J0(k) [k F(k/bT) D(k/qT)] FD_bT_space=lambda bT: self.get_FD_bT_space(x,y,z,Q2,mu2,zetaF,zetaD,bT**2,charge) f=lambda k: k*FD_bT_space(k/qT) if method=='FFT': f=np.vectorize(f) FD_qT_space = D['hankel'].transform(f,ret_err=False)[0] / qT**2 * 2*np.pi elif method=='quad': integrand=lambda k: bessel(0,k)*f(k) FD_qT_space = quad(integrand,1e-4,np.inf)[0] / qT**2 *2*np.pi return FD_qT_space
def windolf_sampling(self, params, layer): a = np.abs(params) alpha = np.angle(params) if layer=='visible': rates = np.abs(self.clamp) phases = vm(alpha, a*rates / self.sigma_sq) return rates * np.exp(1j * phases) else: b = bessel(a - self.biases) / self.sigma_sq sum_bessels = np.array([np.sum(b[i*int(self.hid_shape / 2.0):(i+1)*int(self.hid_shape / 2.0), :]) for i in range(2)]) bessel_sftmx_denom = 1.0 + sum_bessels upsampled_denom = np.ones((self.hid_shape, self.hid_shape)) for i in range(2): upsampled_denom[i*int(self.hid_shape / 2.0):(i+1)*int(self.hid_shape / 2.0), :] *= bessel_sftmx_denom[i] hid_cat_P = b / upsampled_denom pool_P = 1.0 - 1.0 / bessel_sftmx_denom hid_rates, pool_rates = self._dbn_maxpool_sample_helper(hid_cat_P, pool_P) hid_phases = vm(alpha, a*hid_rates / self.sigma_sq) hid_samples = hid_rates*np.exp(1j*hid_phases) pool_phases = np.array([np.sum(hid_phases[:,i*(self.hid_shape / 2):(i+1)*(self.hid_shape / 2)], axis=(1,2)) for i in range(2)]) pool_samples = pool_rates*np.exp(1j*pool_phases) return hid_samples, pool_samples
for n in np.arange(1, 5): plt.plot(x, J(n, x), label=n) plt.xlim([0, x.max()]) plt.legend(title=r'Zernike order $n$') plt.xlabel(r'$x$') plt.title(r'$J_{n+1}^2(2\pi x)/x^2$') plt.show() # Parity of Bessel functions plt.figure() x0 = 5 x = np.linspace(-x0, x0, 1000) styles = ['--', ':', '-.'] for i, nu in enumerate([0, 1, 2, 3, 4, 5]): y = bessel(nu, x) if nu % 2 == 0: color = 'blue' else: color = 'red' plt.plot(x, y, label=nu, linestyle=styles[i // 2], color=color) plt.legend(title=r'Bessel order $\nu$') plt.grid(True) plt.xlabel('x') plt.xlim([-x0, x0]) plt.title(r'$J_{\nu}(x)$') # ================================================================================================================== """ Trigonometric factors """
def airy_func(x,y): "A function to fit the Airy Disk for the given input" X = sqrt((x - center_x)**2/widthx + (y - center_y)**2/widthy) return offset + height * (bessel(1,X)/(X+1e-6)) **2
def get_PDF(self, x, mu2, zetaF, qT, flav): integrand=lambda bT: bT*bessel(0,bT*qT)*\ self.get_PDF_bT_space(x,bT**2,mu2,zetaF,flav) tgral = quad(integrand, 1e-4, 20)[0] return tgral
def structure_function(r, a, mu_0, smaller_than_factor=0.1): """ Structure function :math:`D(r)`. :param r: :math:`r` :param a: :math:`a` :param mu_0: :math:`\\mu_0` :param smaller_than_factor: Factor .. math:: D(r) = 2 \\mu_0^2 \\left[ 1 - \\frac{2^{2/3}}{\\Gamma(1/3)} \\left(\\frac{r}{a}\\right)^{1/3} K_{1/3} \\left(\\frac{r}{a}\\right) \\right] When :math:`a \\ll r`, or 'r < smaller_than_factor * a' .. math:: D(r) \\approx \\mu_0^2 \\frac{\\sqrt{\\pi}}{\\Gamma(7/6)} \\left( \\frac{r}{a} \\right)^{2/3} See Salomons, equation I.40. """ return (r < smaller_than_factor * a) * \ ( mu_0**2.0 * np.sqrt(np.pi)/gamma(7.0/6.0) * (r/a)**(2.0/3.0) ) + \ (r >= smaller_than_factor * a) * \ ( mu_0**2.0 * (1.0 - 2.0**(2.0/3.0) / gamma(1.0/3.0) * (r/a)**(1.0/3.0) * bessel(1.0/3.0, r/a) ) )
def get_FF(self, x, mu2, zetaD, qT, flav, charge): integrand=lambda bT: bT*bessel(0,bT*qT)*\ self.get_FF_bT_space(x,bT**2,mu2,zetaD) tgral = quad(integrand, 1e-4, 20)[0] return tgral
def bes(x): return bessel(0, x)
def get_FF(self,x,mu2,zetaD,qT,flav,charge): integrand=lambda bT: bT*bessel(0,bT*qT)*\ self.get_FF_bT_space(x,bT**2,mu2,zetaD) tgral=quad(integrand,1e-4,20)[0] return tgral
def get_image(image_parameters): """Generate image with particles. Input: image_parameters: list with the values of the image parameters in a dictionary: image_parameters['Particle Center X List'] image_parameters['Particle Center Y List'] image_parameters['Particle Radius List'] image_parameters['Particle Bessel Orders List'] image_parameters['Particle Intensities List'] image_parameters['Image Size'] image_parameters['Image Background Level'] image_parameters['Signal to Noise Ratio'] image_parameters['Gradient Intensity'] image_parameters['Gradient Direction'] image_parameters['Ellipsoid Orientation'] image_parameters['Ellipticity'] Note: image_parameters is typically obained from the function get_image_parameters() Output: image: image of the particle [2D numpy array of real numbers betwen 0 and 1] """ from numpy import meshgrid, arange, ones, zeros, sin, cos, sqrt, clip, array, ceil, mean, amax, asarray, amin from numpy.random import normal, poisson from math import e from scipy.special import jv as bessel import warnings particle_center_x_list = image_parameters['Particle Center X List'] particle_center_y_list = image_parameters['Particle Center Y List'] particle_radius_list = image_parameters['Particle Radius List'] particle_bessel_orders_list = image_parameters[ 'Particle Bessel Orders List'] particle_intensities_list = image_parameters['Particle Intensities List'] image_size = image_parameters['Image Size'] image_background_level = image_parameters['Image Background Level'] signal_to_noise_ratio = image_parameters['Signal to Noise Ratio'] gradient_intensity = image_parameters['Gradient Intensity'] gradient_direction = image_parameters['Gradient Direction'] ellipsoidal_orientation_list = image_parameters['Ellipsoid Orientation'] ellipticity = image_parameters['Ellipticity'] ### CALCULATE BACKGROUND # initialize the image at the background level image_background = ones((image_size, image_size)) * image_background_level # calculate matrix coordinates from the center of the image image_coordinate_x, image_coordinate_y = meshgrid(arange(0, image_size), arange(0, image_size), sparse=False, indexing='ij') # add gradient to image background image_background = image_background + gradient_intensity * ( image_coordinate_x * sin(gradient_direction) + image_coordinate_y * cos(gradient_direction)) / (sqrt(2) * image_size) ### CALCULATE IMAGE PARTICLES image_particles = zeros((image_size, image_size)) particle_intensities_for_SNR = [] # calculate the particle profiles of all particles and add them to image_particles for particle_center_x, particle_center_y, particle_radius, particle_bessel_orders, particle_intensities, ellipsoidal_orientation in zip( particle_center_x_list, particle_center_y_list, particle_radius_list, particle_bessel_orders_list, particle_intensities_list, ellipsoidal_orientation_list): # calculate coordinates of cutoff window start_x = int(max(ceil(particle_center_x - particle_radius * 3), 0)) stop_x = int( min(ceil(particle_center_x + particle_radius * 3), image_size)) start_y = int(max(ceil(particle_center_y - particle_radius * 3), 0)) stop_y = int( min(ceil(particle_center_y + particle_radius * 3), image_size)) # calculate matrix coordinates from the center of the image image_coordinate_x, image_coordinate_y = meshgrid( arange(start_x, stop_x), arange(start_y, stop_y), sparse=False, indexing='ij') # calculate the elliptical distance from the center of the particle normalized by the particle radius rotated_distance_x = (image_coordinate_x - particle_center_x) * cos( ellipsoidal_orientation) + (image_coordinate_y - particle_center_y ) * sin(ellipsoidal_orientation) rotated_distance_y = -(image_coordinate_x - particle_center_x) * sin( ellipsoidal_orientation) + (image_coordinate_y - particle_center_y ) * cos(ellipsoidal_orientation) # The factor 2 is because the particle radius is defined as the point where the intensity reaches 1/3 of # the intensity in the middle of the particle when Bessel order = 0. When Bessel order = 1, the middle of # the particle is black, and at the radius the intensity is approximately at its maximum. For higher # Bessel orders, there is no clear definition of the radius. elliptical_distance_from_particle = 2 * sqrt( (rotated_distance_x)**2 + (rotated_distance_y / ellipticity)**2 + .001**2) / particle_radius # calculate particle profile. for particle_bessel_order, particle_intensity in zip( particle_bessel_orders, particle_intensities): image_particle = 4 * particle_bessel_order**2.5 * ( bessel(particle_bessel_order, elliptical_distance_from_particle) / elliptical_distance_from_particle)**2 image_particles[start_x:stop_x, start_y:stop_y] = image_particles[ start_x:stop_x, start_y:stop_y] + particle_intensity * image_particle # calculate image without noise as background image plus particle image image_particles_without_noise = clip(image_background + image_particles, 0, 1) ### ADD NOISE image_particles_with_noise = poisson( image_particles_without_noise * signal_to_noise_ratio**2) / signal_to_noise_ratio**2 cut_off_pixels = tuple([image_particles_with_noise > 1]) percentage_of_pixels_that_were_cut_off = image_particles_with_noise[ cut_off_pixels].size / (image_size**2) * 100 # warn if there is a pixel brighter than 1 def custom_formatwarning(msg, *args, **kwargs): # ignore everything except the message return str(msg) + '\n' if percentage_of_pixels_that_were_cut_off > 0: warnings.formatwarning = custom_formatwarning warn_message = ( "Warning: %.5f%% of the pixels in the generated image are brighter than the 1 (%d pixels)! " "These were cut-off to the max value 1. Consider adjusting your gradient intensity, particle " "intensity, background level, or signal to noise ratio." % (percentage_of_pixels_that_were_cut_off, image_particles_with_noise[cut_off_pixels].size)) warnings.warn(warn_message) # print("After poisson: Min is %.4f, Max is %.4f" % (amin(image_particles_with_noise), # amax(image_particles_with_noise))) return clip(image_particles_with_noise, 0, 1)
def Test_3(x): return bessel(0,x)
def get_L(self,x,y,z,Q2,mu2,zetaF,zetaD,qT,charge): integrand=lambda bT: bT*bessel(0,bT*qT)*self.get_L_bT_space(x,y,z,Q2,mu2,zetaF,zetaD,bT**2,charge)/qT #tgral=quad(integrand,1e-4,20)[0] tgral=quad(integrand,0,np.inf)[0] return tgral*qT/(2*np.pi)
def get_image(image_parameters, use_gpu=False): """Generate image with particles. Input: image_parameters: list with the values of the image parameters in a dictionary: image_parameters['Particle Center X List'] image_parameters['Particle Center Y List'] image_parameters['Particle Radius List'] image_parameters['Particle Bessel Orders List'] image_parameters['Particle Intensities List'] image_parameters['Image Size'] image_parameters['Image Background Level'] image_parameters['Signal to Noise Ratio'] image_parameters['Gradient Intensity'] image_parameters['Gradient Direction'] image_parameters['Ellipsoid Orientation'] image_parameters['Ellipticity'] Note: image_parameters is typically obained from the function get_image_parameters() Output: image: image of the particle [2D numpy array of real numbers betwen 0 and 1] """ from numpy import meshgrid, arange, ones, zeros, sin, cos, sqrt, clip, array from numpy.random import poisson as poisson particle_center_x_list = image_parameters['Particle Center X List'] particle_center_y_list = image_parameters['Particle Center Y List'] particle_radius_list = image_parameters['Particle Radius List'] particle_bessel_orders_list = image_parameters['Particle Bessel Orders List'] particle_intensities_list = image_parameters['Particle Intensities List'] image_size = image_parameters['Image Size'] image_background_level = image_parameters['Image Background Level'] signal_to_noise_ratio = image_parameters['Signal to Noise Ratio'] gradient_intensity = image_parameters['Gradient Intensity'] gradient_direction = image_parameters['Gradient Direction'] ellipsoidal_orientation_list = image_parameters['Ellipsoid Orientation'] ellipticity = image_parameters['Ellipticity'] ### CALCULATE BACKGROUND # initialize the image at the background level image_background = ones((image_size, image_size)) * image_background_level # calculate matrix coordinates from the center of the image image_coordinate_x, image_coordinate_y = meshgrid(arange(0, image_size), arange(0, image_size), sparse=False, indexing='ij') # add gradient to image background if gradient_intensity!=0: image_background = image_background + gradient_intensity * (image_coordinate_x * sin(gradient_direction) + image_coordinate_y * cos(gradient_direction) ) / (sqrt(2) * image_size) ### CALCULATE IMAGE PARTICLES image_particles = zeros((image_size, image_size)) # calculate the particle profiles of all particles and add them to image_particles if(use_gpu): print('No GPU!') #calc_particle_profile_gpu(particle_center_x_list, particle_center_y_list,particle_radius_list, image_particles,particle_intensities_list) else: from scipy.special import jv as bessel for particle_center_x, particle_center_y, particle_radius, particle_bessel_orders, particle_intensities, ellipsoidal_orientation in zip(particle_center_x_list, particle_center_y_list, particle_radius_list, particle_bessel_orders_list, particle_intensities_list, ellipsoidal_orientation_list): # calculate the radial distance from the center of the particle # normalized by the particle radius radial_distance_from_particle = sqrt((image_coordinate_x - particle_center_x)**2 + (image_coordinate_y - particle_center_y)**2 + .001**2) / particle_radius # for elliptical particles rotated_distance_x = (image_coordinate_x - particle_center_x)*cos(ellipsoidal_orientation) + (image_coordinate_y - particle_center_y)*sin(ellipsoidal_orientation) rotated_distance_y = -(image_coordinate_x - particle_center_x)*sin(ellipsoidal_orientation) + (image_coordinate_y - particle_center_y)*cos(ellipsoidal_orientation) elliptical_distance_from_particle = sqrt((rotated_distance_x)**2 + (rotated_distance_y / ellipticity)**2 + .001**2) / particle_radius # calculate particle profile for particle_bessel_order, particle_intensity in zip(particle_bessel_orders, particle_intensities): image_particle = 4 * particle_bessel_order**2.5 * (bessel(particle_bessel_order, elliptical_distance_from_particle) / elliptical_distance_from_particle)**2 image_particles = image_particles + particle_intensity * image_particle # calculate image without noise as background image plus particle image image_particles_without_noise = clip(image_background + image_particles, 0, 1) ### ADD NOISE image_particles_with_noise = poisson(image_particles_without_noise * signal_to_noise_ratio**2) / signal_to_noise_ratio**2 return image_particles_with_noise
def integrand(self,Q,Q0,bT,x,z,qT): return bT*bessel(0,qT*bT)*self.WL_bT(Q,Q0,x,z,bT)
def J(n, x): f = (bessel(n + 1, 2 * np.pi * x) / x)**2 return f
def get_L(self, x, y, z, Q2, mu2, zetaF, zetaD, qT, charge): integrand = lambda bT: bT * bessel(0, bT * qT) * self.get_L_bT_space( x, y, z, Q2, mu2, zetaF, zetaD, bT**2, charge) / qT #tgral=quad(integrand,1e-4,20)[0] tgral = quad(integrand, 0, np.inf)[0] return tgral * qT / (2 * np.pi)
#!/usr/bin/env python import sys, os import numpy as np import pylab as py from hankel import HankelTransform from scipy.special import jv as bessel from scipy.integrate import quad, quadrature, fixed_quad BT = np.linspace(0, 10, 100) W = lambda bT: np.exp(-0.5 * bT**2) qT = 2.0 integrand = lambda bT: bT * bessel(0, bT * qT) * W(bT) tgral = quad(integrand, 1e-4, np.inf)[0] print tgral f = lambda x: x * W(x / qT) #h = HankelTransform(nu=0,N=120,h=0.03) h = HankelTransform(nu=0, N=120, h=0.003) print h.transform(f, ret_err=False)[0] / qT**2 #f = lambda x: 1 #Define the input function f(x) #h = HankelTransform(nu=0,N=120,h=0.03) #Create the HankelTransform instance #print h.transform(f)