code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
rho = rho0 / r**gamma return rho
def density(self, r, rho0, gamma)
computes the density :param x: :param y: :param rho0: :param a: :param s: :return:
8.862754
27.532272
0.321904
x_ = x - center_x y_ = y - center_y r = np.sqrt(x_**2 + y_**2) sigma = np.sqrt(np.pi) * special.gamma(1./2*(-1+gamma))/special.gamma(gamma/2.) * r**(1-gamma) * rho0 return sigma
def density_2d(self, x, y, rho0, gamma, center_x=0, center_y=0)
projected density :param x: :param y: :param rho0: :param a: :param s: :param center_x: :param center_y: :return:
3.564559
3.84425
0.927244
sigma2_R_sum = 0 for i in range(0, self._num_sampling): sigma2_R = self.draw_one_sigma2(kwargs_mass, kwargs_light, kwargs_anisotropy, kwargs_apertur) sigma2_R_sum += sigma2_R sigma_s2_average = sigma2_R_sum / self._num_sampling # apply unit conversion from arc seconds and deflections to physical velocity disperison in (km/s) sigma_s2_average *= 2 * const.G # correcting for integral prefactor return np.sqrt(sigma_s2_average/(const.arcsec**2 * self.cosmo.D_d**2 * const.Mpc))/1000.
def vel_disp(self, kwargs_mass, kwargs_light, kwargs_anisotropy, kwargs_apertur)
computes the averaged LOS velocity dispersion in the slit (convolved) :param kwargs_mass: mass model parameters (following lenstronomy lens model conventions) :param kwargs_light: deflector light parameters (following lenstronomy light model conventions) :param kwargs_anisotropy: anisotropy parameters, may vary according to anisotropy type chosen. We refer to the Anisotropy() class for details on the parameters. :param kwargs_apertur: Aperture parameters, may vary depending on aperture type chosen. We refer to the Aperture() class for details on the parameters. :return: integrated LOS velocity dispersion in units [km/s]
5.254818
5.150832
1.020188
I_R_sigma2 = self.I_R_simga2(R, kwargs_mass, kwargs_light, kwargs_anisotropy) I_R = self.lightProfile.light_2d(R, kwargs_light) return I_R_sigma2 / I_R
def sigma2_R(self, R, kwargs_mass, kwargs_light, kwargs_anisotropy)
returns unweighted los velocity dispersion for a specified projected radius :param R: 2d projected radius (in angular units) :param kwargs_mass: mass model parameters (following lenstronomy lens model conventions) :param kwargs_light: deflector light parameters (following lenstronomy light model conventions) :param kwargs_anisotropy: anisotropy parameters, may vary according to anisotropy type chosen. We refer to the Anisotropy() class for details on the parameters. :return:
3.317477
4.083042
0.812501
R = max(R, self._min_integrate) if self._log_int is True: min_log = np.log10(R+0.001) max_log = np.log10(self._max_integrate) r_array = np.logspace(min_log, max_log, self._interp_grid_num) dlog_r = (np.log10(r_array[2]) - np.log10(r_array[1])) * np.log(10) IR_sigma2_dr = self._integrand_A15(r_array, R, kwargs_mass, kwargs_light, kwargs_anisotropy) * dlog_r * r_array else: r_array = np.linspace(R+0.001, self._max_integrate, self._interp_grid_num) dr = r_array[2] - r_array[1] IR_sigma2_dr = self._integrand_A15(r_array, R, kwargs_mass, kwargs_light, kwargs_anisotropy) * dr IR_sigma2 = np.sum(IR_sigma2_dr) return IR_sigma2
def I_R_simga2(self, R, kwargs_mass, kwargs_light, kwargs_anisotropy)
equation A15 in Mamon&Lokas 2005 as a logarithmic numerical integral (if option is chosen) modulo pre-factor 2*G :param R: 2d projected radius (in angular units) :param kwargs_mass: mass model parameters (following lenstronomy lens model conventions) :param kwargs_light: deflector light parameters (following lenstronomy light model conventions) :param kwargs_anisotropy: anisotropy parameters, may vary according to anisotropy type chosen. We refer to the Anisotropy() class for details on the parameters. :return: integral of A15 in Mamon&Lokas 2005
2.225985
2.210191
1.007146
k_r = self.anisotropy.K(r, R, kwargs_anisotropy) l_r = self.lightProfile.light_3d_interp(r, kwargs_light) m_r = self.massProfile.mass_3d_interp(r, kwargs_mass) out = k_r * l_r * m_r / r return out
def _integrand_A15(self, r, R, kwargs_mass, kwargs_light, kwargs_anisotropy)
integrand of A15 (in log space) in Mamon&Lokas 2005 :param r: 3d radius :param R: 2d projected radius :param kwargs_mass: mass model parameters (following lenstronomy lens model conventions) :param kwargs_light: deflector light parameters (following lenstronomy light model conventions) :param kwargs_anisotropy: anisotropy parameters, may vary according to anisotropy type chosen. We refer to the Anisotropy() class for details on the parameters. :return:
2.868605
2.944797
0.974127
x_ = x - center_x y_ = y - center_y r = np.sqrt(x_**2 + y_**2) if isinstance(r, int) or isinstance(r, float): r = max(self._s, r) else: r[r < self._s] = self._s alpha = -self.alpha_abs(x, y, n_sersic, R_sersic, k_eff, center_x, center_y) f_x = alpha * x_ / r f_y = alpha * y_ / r return f_x, f_y
def derivatives(self, x, y, n_sersic, R_sersic, k_eff, center_x=0, center_y=0)
returns df/dx and df/dy of the function
2.252402
2.280177
0.987819
x_ = x - center_x y_ = y - center_y r = np.sqrt(x_**2 + y_**2) if isinstance(r, int) or isinstance(r, float): r = max(self._s, r) else: r[r < self._s] = self._s d_alpha_dr = self.d_alpha_dr(x, y, n_sersic, R_sersic, k_eff, center_x, center_y) alpha = -self.alpha_abs(x, y, n_sersic, R_sersic, k_eff, center_x, center_y) #f_xx_ = d_alpha_dr * calc_util.d_r_dx(x_, y_) * x_/r + alpha * calc_util.d_x_diffr_dx(x_, y_) #f_yy_ = d_alpha_dr * calc_util.d_r_dy(x_, y_) * y_/r + alpha * calc_util.d_y_diffr_dy(x_, y_) #f_xy_ = d_alpha_dr * calc_util.d_r_dy(x_, y_) * x_/r + alpha * calc_util.d_x_diffr_dy(x_, y_) f_xx = -(d_alpha_dr/r + alpha/r**2) * x_**2/r + alpha/r f_yy = -(d_alpha_dr/r + alpha/r**2) * y_**2/r + alpha/r f_xy = -(d_alpha_dr/r + alpha/r**2) * x_*y_/r return f_xx, f_yy, f_xy
def hessian(self, x, y, n_sersic, R_sersic, k_eff, center_x=0, center_y=0)
returns Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy
1.97833
1.957955
1.010406
if q >= 1: q = 0.999999 psi = self._psi(x, y, q, s) f_x = theta_E / np.sqrt(1. - q ** 2) * np.arctan(np.sqrt(1. - q ** 2) * x / (psi+s)) f_y = theta_E / np.sqrt(1. - q ** 2) * np.arctanh(np.sqrt(1. - q ** 2) * y / (psi + q**2*s)) return f_x, f_y
def derivatives(self, x, y, theta_E, s, q)
returns df/dx and df/dy of the function
2.473557
2.549137
0.970351
alpha_ra, alpha_dec = self.derivatives(x, y, theta_E, s, q) diff = self._diff alpha_ra_dx, alpha_dec_dx = self.derivatives(x + diff, y, theta_E, s, q) alpha_ra_dy, alpha_dec_dy = self.derivatives(x, y + diff, theta_E, s, q) f_xx = (alpha_ra_dx - alpha_ra) / diff f_xy = (alpha_ra_dy - alpha_ra) / diff # f_yx = (alpha_dec_dx - alpha_dec)/diff f_yy = (alpha_dec_dy - alpha_dec) / diff return f_xx, f_yy, f_xy
def hessian(self, x, y, theta_E, s, q)
returns Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy
1.896198
1.880056
1.008586
return np.sqrt(q**2 * (s**2 + x**2) + y**2)
def _psi(self, x, y, q, s)
expression after equation (8) in Keeton&Kochanek 1998 :param x: :param y: :param q: :param s: :return:
4.677498
6.881603
0.67971
theta, phi = param_util.cart2polar(x - ra_0, y - dec_0) f_ = 1./2 * kappa_ext * theta**2 return f_
def function(self, x, y, kappa_ext, ra_0=0, dec_0=0)
lensing potential :param x: x-coordinate :param y: y-coordinate :param kappa_ext: external convergence :return: lensing potential
5.262747
5.698461
0.923538
x_ = x - ra_0 y_ = y - dec_0 f_x = kappa_ext * x_ f_y = kappa_ext * y_ return f_x, f_y
def derivatives(self, x, y, kappa_ext, ra_0=0, dec_0=0)
deflection angle :param x: x-coordinate :param y: y-coordinate :param kappa_ext: external convergence :return: deflection angles (first order derivatives)
2.149154
2.335962
0.920029
gamma1 = 0 gamma2 = 0 kappa = kappa_ext f_xx = kappa + gamma1 f_yy = kappa - gamma1 f_xy = gamma2 return f_xx, f_yy, f_xy
def hessian(self, x, y, kappa_ext, ra_0=0, dec_0=0)
Hessian matrix :param x: x-coordinate :param y: y-coordinate :param kappa_ext: external convergence :return: second order derivatives f_xx, f_yy, f_xy
3.016479
2.866952
1.052155
x, y = M.dot(np.array([ra, dec])) return x + x_0, y + y_0
def map_coord2pix(ra, dec, x_0, y_0, M)
this routines performs a linear transformation between two coordinate systems. Mainly used to transform angular into pixel coordinates in an image :param ra: ra coordinates :param dec: dec coordinates :param x_0: pixel value in x-axis of ra,dec = 0,0 :param y_0: pixel value in y-axis of ra,dec = 0,0 :param M: 2x2 matrix to transform angular to pixel coordinates :return: transformed coordnate systems of input ra and dec
2.514957
4.408794
0.570441
if nx == 0 or ny == 0: n = int(np.sqrt(len(array))) if n**2 != len(array): raise ValueError("lenght of input array given as %s is not square of integer number!" %(len(array))) nx, ny = n, n image = array.reshape(int(nx), int(ny)) return image
def array2image(array, nx=0, ny=0)
returns the information contained in a 1d array into an n*n 2d array (only works when lenght of array is n**2) :param array: image values :type array: array of size n**2 :returns: 2d array :raises: AttributeError, KeyError
3.389726
3.555559
0.95336
nx, ny = image.shape # find the size of the array imgh = np.reshape(image, nx*ny) # change the shape to be 1d return imgh
def image2array(image)
returns the information contained in a 2d array into an n*n 1d array :param array: image values :type array: array of size (n,n) :returns: 1d array :raises: AttributeError, KeyError
6.143789
6.017301
1.021021
x_grid, y_grid = make_grid(numPix, deltapix=1) ra_grid, dec_grid = map_coord2pix(x_grid, y_grid, 0, 0, Mpix2Angle) return ra_grid, dec_grid
def make_grid_transformed(numPix, Mpix2Angle)
returns grid with linear transformation (deltaPix and rotation) :param numPix: number of Pixels :param Mpix2Angle: 2-by-2 matrix to mat a pixel to a coordinate :return: coordinate grid
2.791094
2.94944
0.946313
numPix_eff = numPix*subgrid_res deltapix_eff = deltapix/float(subgrid_res) a = np.arange(numPix_eff) matrix = np.dstack(np.meshgrid(a, a)).reshape(-1, 2) if inverse is True: delta_x = -deltapix_eff else: delta_x = deltapix_eff if left_lower is True: x_grid = matrix[:, 0]*deltapix y_grid = matrix[:, 1]*deltapix else: x_grid = (matrix[:, 0] - (numPix_eff-1)/2.)*delta_x y_grid = (matrix[:, 1] - (numPix_eff-1)/2.)*deltapix_eff shift = (subgrid_res-1)/(2.*subgrid_res)*deltapix x_grid -= shift y_grid -= shift ra_at_xy_0 = x_grid[0] dec_at_xy_0 = y_grid[0] x_at_radec_0 = (numPix_eff - 1) / 2. y_at_radec_0 = (numPix_eff - 1) / 2. Mpix2coord = np.array([[delta_x, 0], [0, deltapix_eff]]) Mcoord2pix = np.linalg.inv(Mpix2coord) return x_grid, y_grid, ra_at_xy_0, dec_at_xy_0, x_at_radec_0, y_at_radec_0, Mpix2coord, Mcoord2pix
def make_grid_with_coordtransform(numPix, deltapix, subgrid_res=1, left_lower=False, inverse=True)
same as make_grid routine, but returns the transformaton matrix and shift between coordinates and pixel :param numPix: :param deltapix: :param subgrid_res: :param left_lower: sets the zero point at the lower left corner of the pixels :param inverse: bool, if true sets East as left, otherwise East is righrt :return:
1.85047
1.892362
0.977862
a = np.arange(numPix) matrix = np.dstack(np.meshgrid(a, a)).reshape(-1, 2) x_grid = matrix[:, 0] y_grid = matrix[:, 1] ra_grid = x_grid * Mpix2coord[0, 0] + y_grid * Mpix2coord[0, 1] + ra_at_xy_0 dec_grid = x_grid * Mpix2coord[1, 0] + y_grid * Mpix2coord[1, 1] + dec_at_xy_0 return ra_grid, dec_grid
def grid_from_coordinate_transform(numPix, Mpix2coord, ra_at_xy_0, dec_at_xy_0)
return a grid in x and y coordinates that satisfy the coordinate system :param numPix: :param Mpix2coord: :param ra_at_xy_0: :param dec_at_xy_0: :return:
1.524293
1.600045
0.952656
n=int(np.sqrt(len(x))) if n**2 != len(x): raise ValueError("lenght of input array given as %s is not square of integer number!" % (len(x))) x_image = x.reshape(n,n) y_image = y.reshape(n,n) x_axes = x_image[0,:] y_axes = y_image[:,0] return x_axes, y_axes
def get_axes(x, y)
computes the axis x and y of a given 2d grid :param x: :param y: :return:
3.030244
3.159916
0.958963
Nbig = numGrid Nsmall = numPix small = grid.reshape([int(Nsmall), int(Nbig/Nsmall), int(Nsmall), int(Nbig/Nsmall)]).mean(3).mean(1) return small
def averaging(grid, numGrid, numPix)
resize 2d pixel grid with numGrid to numPix and averages over the pixels :param grid: higher resolution pixel grid :param numGrid: number of pixels per axis in the high resolution input image :param numPix: lower number of pixels per axis in the output image (numGrid/numPix is integer number) :return:
4.07447
4.445448
0.916549
x_mapped = x - sourcePos_x y_mapped = y - sourcePos_y absmapped = np.sqrt(x_mapped**2+y_mapped**2) return absmapped
def displaceAbs(x, y, sourcePos_x, sourcePos_y)
calculates a grid of distances to the observer in angel :param mapped_cartcoord: mapped cartesian coordinates :type mapped_cartcoord: numpy array (n,2) :param sourcePos: source position :type sourcePos: numpy vector [x0,y0] :returns: array of displacement :raises: AttributeError, KeyError
2.493004
3.130448
0.796373
dist = np.zeros_like(x_1) for i in range(len(x_1)): dist[i] = np.min((x_1[i] - x_2)**2 + (y_1[i] - y_2)**2) return dist
def min_square_dist(x_1, y_1, x_2, y_2)
return minimum of quadratic distance of pairs (x1, y1) to pairs (x2, y2) :param x_1: :param y_1: :param x_2: :param y_2: :return:
1.795937
2.040733
0.880045
angle = np.linspace(0, 2*np.pi, points) x_coord = np.cos(angle)*radius y_coord = np.sin(angle)*radius return x_coord, y_coord
def points_on_circle(radius, points)
returns a set of uniform points around a circle :param radius: radius of the circle :param points: number of points on the circle :return:
1.958545
2.346034
0.834832
dim = int(np.sqrt(len(a))) values = [] x_mins = [] y_mins = [] for i in range(dim+1,len(a)-dim-1): if (a[i] < a[i-1] and a[i] < a[i+1] and a[i] < a[i-dim] and a[i] < a[i+dim] and a[i] < a[i-(dim-1)] and a[i] < a[i-(dim+1)] and a[i] < a[i+(dim-1)] and a[i] < a[i+(dim+1)]): if(a[i] < a[(i-2*dim-1)%dim**2] and a[i] < a[(i-2*dim+1)%dim**2] and a[i] < a[(i-dim-2)%dim**2] and a[i] < a[(i-dim+2)%dim**2] and a[i] < a[(i+dim-2)%dim**2] and a[i] < a[(i+dim+2)%dim**2] and a[i] < a[(i+2*dim-1)%dim**2] and a[i] < a[(i+2*dim+1)%dim**2]): if(a[i] < a[(i-3*dim-1)%dim**2] and a[i] < a[(i-3*dim+1)%dim**2] and a[i] < a[(i-dim-3)%dim**2] and a[i] < a[(i-dim+3)%dim**2] and a[i] < a[(i+dim-3)%dim**2] and a[i] < a[(i+dim+3)%dim**2] and a[i] < a[(i+3*dim-1)%dim**2] and a[i] < a[(i+3*dim+1)%dim**2]): x_mins.append(x[i]) y_mins.append(y[i]) values.append(a[i]) return np.array(x_mins), np.array(y_mins), np.array(values)
def neighborSelect(a, x, y)
finds (local) minima in a 2d grid :param a: 1d array of displacements from the source positions :type a: numpy array with length numPix**2 in float :returns: array of indices of local minima, values of those minima :raises: AttributeError, KeyError
1.395157
1.392369
1.002003
ra_array = array2image(ra_coord) dec_array = array2image(dec_coord) n = len(ra_array) d_ra_x = ra_array[0][1] - ra_array[0][0] d_ra_y = ra_array[1][0] - ra_array[0][0] d_dec_x = dec_array[0][1] - dec_array[0][0] d_dec_y = dec_array[1][0] - dec_array[0][0] ra_array_new = np.zeros((n*subgrid_res, n*subgrid_res)) dec_array_new = np.zeros((n*subgrid_res, n*subgrid_res)) for i in range(0, subgrid_res): for j in range(0, subgrid_res): ra_array_new[i::subgrid_res, j::subgrid_res] = ra_array + d_ra_x * (-1/2. + 1/(2.*subgrid_res) + j/float(subgrid_res)) + d_ra_y * (-1/2. + 1/(2.*subgrid_res) + i/float(subgrid_res)) dec_array_new[i::subgrid_res, j::subgrid_res] = dec_array + d_dec_x * (-1/2. + 1/(2.*subgrid_res) + j/float(subgrid_res)) + d_dec_y * (-1/2. + 1/(2.*subgrid_res) + i/float(subgrid_res)) ra_coords_sub = image2array(ra_array_new) dec_coords_sub = image2array(dec_array_new) return ra_coords_sub, dec_coords_sub
def make_subgrid(ra_coord, dec_coord, subgrid_res=2)
return a grid with subgrid resolution :param ra_coord: :param dec_coord: :param subgrid_res: :return:
1.49535
1.501835
0.995682
phi_G, q = param_util.ellipticity2phi_q(e1, e2) gamma, q = self._param_bounds(gamma, q) theta_E *= q x_shift = x - center_x y_shift = y - center_y E = theta_E / (((3 - gamma) / 2.) ** (1. / (1 - gamma)) * np.sqrt(q)) #E = phi_E eta = -gamma+3 xt1 = np.cos(phi_G)*x_shift+np.sin(phi_G)*y_shift xt2 = -np.sin(phi_G)*x_shift+np.cos(phi_G)*y_shift p2 = xt1**2+xt2**2/q**2 s2 = 0. # softening return 2 * E**2/eta**2 * ((p2 + s2)/E**2)**(eta/2)
def function(self, x, y, theta_E, gamma, e1, e2, center_x=0, center_y=0)
:param x: set of x-coordinates :type x: array of size (n) :param theta_E: Einstein radius of lense :type theta_E: float. :param gamma: power law slope of mass profifle :type gamma: <2 float :param q: Axis ratio :type q: 0<q<1 :param phi_G: position angel of SES :type q: 0<phi_G<pi/2 :returns: function :raises: AttributeError, KeyError
4.127111
4.190437
0.984888
return self.spp.mass_3d_lens(r, theta_E, gamma)
def mass_3d_lens(self, r, theta_E, gamma, e1, e2)
computes the spherical power-law mass enclosed (with SPP routiune) :param r: :param theta_E: :param gamma: :param q: :param phi_G: :return:
4.147538
5.306401
0.78161
if gamma < 1.4: gamma = 1.4 if gamma > 2.9: gamma = 2.9 if q < 0.01: q = 0.01 return float(gamma), q
def _param_bounds(self, gamma, q)
bounds parameters :param gamma: :param q: :return:
2.900014
3.143538
0.922532
dist = self._param.check_solver(kwargs_lens, kwargs_ps, kwargs_cosmo) if dist > tolerance: return dist * 10**10 return 0
def solver_penalty(self, kwargs_lens, kwargs_ps, kwargs_cosmo, tolerance)
test whether the image positions map back to the same source position :param kwargs_lens: :param kwargs_ps: :return: add penalty when solver does not find a solution
5.266978
5.292448
0.995188
ra_image_list, dec_image_list = self._pointSource.image_position(kwargs_ps=kwargs_ps, kwargs_lens=kwargs_lens) if len(ra_image_list) > 0: if len(ra_image_list[0]) > self._param.num_point_source_images: return True return False
def check_additional_images(self, kwargs_ps, kwargs_lens)
checks whether additional images have been found and placed in kwargs_ps :param kwargs_ps: point source kwargs :return: bool, True if more image positions are found than originally been assigned
3.431902
3.206147
1.070413
#if n_sersic < 0.2: # n_sersic = 0.2 #if R_sersic < 10.**(-6): # R_sersic = 10.**(-6) R_sersic = np.maximum(0, R_sersic) x_shift = x - center_x y_shift = y - center_y R = np.sqrt(x_shift*x_shift + y_shift*y_shift) if isinstance(R, int) or isinstance(R, float): R = max(self._smoothing, R) else: R[R < self._smoothing] = self._smoothing _, bn = self.k_bn(n_sersic, R_sersic) R_frac = R/R_sersic #R_frac = R_frac.astype(np.float32) if isinstance(R, int) or isinstance(R, float): if R_frac > 100: result = 0 else: exponent = -bn*(R_frac**(1./n_sersic)-1.) result = amp * np.exp(exponent) else: R_frac_real = R_frac[R_frac <= 100] exponent = -bn*(R_frac_real**(1./n_sersic)-1.) result = np.zeros_like(R) result[R_frac <= 100] = amp * np.exp(exponent) return np.nan_to_num(result)
def function(self, x, y, amp, R_sersic, n_sersic, center_x=0, center_y=0)
returns Sersic profile
2.36264
2.37725
0.993854
#if n_sersic < 0.2: # n_sersic = 0.2 #if R_sersic < 10.**(-6): # R_sersic = 10.**(-6) R_sersic = np.maximum(0, R_sersic) phi_G, q = param_util.ellipticity2phi_q(e1, e2) x_shift = x - center_x y_shift = y - center_y cos_phi = np.cos(phi_G) sin_phi = np.sin(phi_G) xt1 = cos_phi*x_shift+sin_phi*y_shift xt2 = -sin_phi*x_shift+cos_phi*y_shift xt2difq2 = xt2/(q*q) R_ = np.sqrt(xt1*xt1+xt2*xt2difq2) if isinstance(R_, int) or isinstance(R_, float): R_ = max(self._smoothing, R_) else: R_[R_ < self._smoothing] = self._smoothing k, bn = self.k_bn(n_sersic, R_sersic) R_frac = R_/R_sersic R_frac = R_frac.astype(np.float32) if isinstance(R_, int) or isinstance(R_, float): if R_frac > 100: result = 0 else: exponent = -bn*(R_frac**(1./n_sersic)-1.) result = amp * np.exp(exponent) else: R_frac_real = R_frac[R_frac <= 100] exponent = -bn*(R_frac_real**(1./n_sersic)-1.) result = np.zeros_like(R_) result[R_frac <= 100] = amp * np.exp(exponent) return np.nan_to_num(result)
def function(self, x, y, amp, R_sersic, n_sersic, e1, e2, center_x=0, center_y=0)
returns Sersic profile
2.478451
2.488928
0.995791
phi_G, q = param_util.ellipticity2phi_q(e1, e2) Rb = R_sersic x_shift = x - center_x y_shift = y - center_y cos_phi = np.cos(phi_G) sin_phi = np.sin(phi_G) xt1 = cos_phi*x_shift+sin_phi*y_shift xt2 = -sin_phi*x_shift+cos_phi*y_shift xt2difq2 = xt2/(q*q) R_ = np.sqrt(xt1*xt1+xt2*xt2difq2) #R_ = R_.astype(np.float32) if isinstance(R_, int) or isinstance(R_, float): R_ = max(self._smoothing, R_) else: R_[R_ < self._smoothing] = self._smoothing if isinstance(R_, int) or isinstance(R_, float): R = max(self._smoothing, R_) else: R=np.empty_like(R_) _R = R_[R_ > self._smoothing] #in the SIS regime R[R_ <= self._smoothing] = self._smoothing R[R_ > self._smoothing] = _R k, bn = self.k_bn(n_sersic, Re) result = amp * (1 + (Rb / R) ** alpha) ** (gamma / alpha) * np.exp(-bn * (((R ** alpha + Rb ** alpha) / Re ** alpha) ** (1. / (alpha * n_sersic)) - 1.)) return np.nan_to_num(result)
def function(self, x, y, amp, R_sersic, Re, n_sersic, gamma, e1, e2, center_x=0, center_y=0, alpha=3.)
returns Core-Sersic function
3.146851
3.120822
1.00834
x_shift = x - center_x y_shift = y - center_y dphi_dr = self._dphi_dr(x_shift, y_shift, theta_E, r_trunc) dr_dx, dr_dy = self._dr_dx(x_shift, y_shift) f_x = dphi_dr * dr_dx f_y = dphi_dr * dr_dy return f_x, f_y
def derivatives(self, x, y, theta_E, r_trunc, center_x=0, center_y=0)
returns df/dx and df/dy of the function
2.147821
2.140238
1.003543
x_shift = x - center_x y_shift = y - center_y dphi_dr = self._dphi_dr(x_shift, y_shift, theta_E, r_trunc) d2phi_dr2 = self._d2phi_dr2(x_shift, y_shift, theta_E, r_trunc) dr_dx, dr_dy = self._dr_dx(x, y) d2r_dx2, d2r_dy2, d2r_dxy = self._d2r_dx2(x_shift, y_shift) f_xx = d2r_dx2*dphi_dr + dr_dx**2*d2phi_dr2 f_yy = d2r_dy2*dphi_dr + dr_dy**2*d2phi_dr2 f_xy = d2r_dxy*dphi_dr + dr_dx*dr_dy*d2phi_dr2 return f_xx, f_yy, f_xy
def hessian(self, x, y, theta_E, r_trunc, center_x=0, center_y=0)
returns Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy
1.646458
1.606842
1.024654
r = np.sqrt(x**2 + y**2) if isinstance(r, int) or isinstance(r, float): if r == 0: r = 1 else: r[r == 0] = 1 return x/r, y/r
def _dr_dx(self, x, y)
derivative of dr/dx, dr/dy :param x: :param y: :return:
2.767422
2.818159
0.981996
phi_G, q = param_util.ellipticity2phi_q(e1, e2) x_shift = x - center_x y_shift = y - center_y cos_phi = np.cos(phi_G) sin_phi = np.sin(phi_G) e = abs(1 - q) x_ = (cos_phi*x_shift+sin_phi*y_shift)*np.sqrt(1 - e) y_ = (-sin_phi*x_shift+cos_phi*y_shift)*np.sqrt(1 + e) f_ = self.spherical.function(x_, y_, sigma0, Rs) return f_
def function(self, x, y, sigma0, Rs, e1, e2, center_x=0, center_y=0)
returns double integral of NFW profile
2.680347
2.612891
1.025817
phi_G, q = param_util.ellipticity2phi_q(e1, e2) x_shift = x - center_x y_shift = y - center_y cos_phi = np.cos(phi_G) sin_phi = np.sin(phi_G) e = abs(1 - q) x_ = (cos_phi*x_shift+sin_phi*y_shift)*np.sqrt(1 - e) y_ = (-sin_phi*x_shift+cos_phi*y_shift)*np.sqrt(1 + e) f_x_prim, f_y_prim = self.spherical.derivatives(x_, y_, sigma0, Rs) f_x_prim *= np.sqrt(1 - e) f_y_prim *= np.sqrt(1 + e) f_x = cos_phi*f_x_prim-sin_phi*f_y_prim f_y = sin_phi*f_x_prim+cos_phi*f_y_prim return f_x, f_y
def derivatives(self, x, y, sigma0, Rs, e1, e2, center_x=0, center_y=0)
returns df/dx and df/dy of the function (integral of NFW)
2.130121
2.059167
1.034457
c = 0.000001 if isinstance(x, np.ndarray): x[np.where(x<c)] = c nfwvals = np.ones_like(x) inds1 = np.where(x < 1) inds2 = np.where(x > 1) nfwvals[inds1] = (1 - x[inds1] ** 2) ** -.5 * np.arctanh((1 - x[inds1] ** 2) ** .5) nfwvals[inds2] = (x[inds2] ** 2 - 1) ** -.5 * np.arctan((x[inds2] ** 2 - 1) ** .5) return nfwvals elif isinstance(x, float) or isinstance(x, int): x = max(x, c) if x == 1: return 1 if x < 1: return (1 - x ** 2) ** -.5 * np.arctanh((1 - x ** 2) ** .5) else: return (x ** 2 - 1) ** -.5 * np.arctan((x ** 2 - 1) ** .5)
def _nfw_func(self, x)
Classic NFW function in terms of arctanh and arctan :param x: r/Rs :return:
1.843511
1.787906
1.031101
if b == 1: b = 1 + c prefac = (b - 1) ** -2 if isinstance(X, np.ndarray): X[np.where(X == 1)] = 1 - c output = np.empty_like(X) inds1 = np.where(np.absolute(X - b)<c) output[inds1] = prefac*(-2 - b + (1 + b + b ** 2) * self._nfw_func(b)) * (1 + b) ** -1 inds2 = np.where(np.absolute(X - b)>=c) output[inds2] = prefac * ((X[inds2] ** 2 - 1) ** -1 * (1 - b - (1 - b * X[inds2] ** 2) * self._nfw_func(X[inds2])) - \ self._nfw_func(X[inds2] * b ** -1)) else: if X == 1: X = 1-c if np.absolute(X - b)<c: output = prefac * (-2 - b + (1 + b + b ** 2) * self._nfw_func(b)) * (1 + b) ** -1 else: output = prefac * ((X ** 2 - 1) ** -1 * (1 - b - (1 - b * X ** 2) * self._nfw_func(X)) - \ self._nfw_func(X * b ** -1)) return output
def _F(self, X, b, c = 0.001)
analytic solution of the projection integral :param x: a dimensionless quantity, either r/rs or r/rc :type x: float >0
2.585412
2.641848
0.978637
M0 = 4*np.pi*rho0 * Rs ** 3 return (M0/4/np.pi) * ((r_core + R)*(R + Rs)**2) ** -1
def density(self, R, Rs, rho0, r_core)
three dimenstional truncated NFW profile :param R: radius of interest :type R: float/numpy array :param Rs: scale radius :type Rs: float :param rho0: density normalization (central core density) :type rho0: float :return: rho(R) density
6.342238
6.715705
0.944389
x_ = x - center_x y_ = y - center_y R = np.sqrt(x_ ** 2 + y_ ** 2) b = r_core * Rs ** -1 x = R * Rs ** -1 Fx = self._F(x, b) return 2 * rho0 * Rs * Fx
def density_2d(self, x, y, Rs, rho0, r_core, center_x=0, center_y=0)
projected two dimenstional NFW profile (kappa*Sigma_crit) :param R: radius of interest :type R: float/numpy array :param Rs: scale radius :type Rs: float :param rho0: density normalization (characteristic density) :type rho0: float :param r200: radius of (sub)halo :type r200: float>0 :return: Epsilon(R) projected density at radius R
3.810396
4.495814
0.847543
b = r_core * Rs ** -1 x = R * Rs ** -1 M_0 = 4 * np.pi * Rs**3 * rho0 return M_0 * (x * (1+x) ** -1 * (-1+b) ** -1 + (-1+b) ** -2 * ((2*b-1)*np.log(1/(1+x)) + b **2 * np.log(x / b + 1)))
def mass_3d(self, R, Rs, rho0, r_core)
mass enclosed a 3d sphere or radius r :param r: :param Ra: :param Rs: :return:
5.062238
5.587357
0.906017
if isinstance(R, int) or isinstance(R, float): R = max(R, 0.00001) else: R[R <= 0.00001] = 0.00001 x = R / Rs b = r_core * Rs ** -1 b = max(b, 0.000001) gx = self._G(x, b) a = 4*rho0*Rs*gx/x**2 return a * ax_x, a * ax_y
def cnfwAlpha(self, R, Rs, rho0, r_core, ax_x, ax_y)
deflection angel of NFW profile along the projection to coordinate axis :param R: radius of interest :type R: float/numpy array :param Rs: scale radius :type Rs: float :param rho0: density normalization (characteristic density) :type rho0: float :param r200: radius of (sub)halo :type r200: float>0 :param axis: projection to either x- or y-axis :type axis: same as R :return: Epsilon(R) projected density at radius R
3.660399
3.995929
0.916032
phi_G, q = param_util.ellipticity2phi_q(e1, e2) x_shift = x - center_x y_shift = y - center_y cos_phi = np.cos(phi_G) sin_phi = np.sin(phi_G) e = min(abs(1. - q), 0.99) xt1 = (cos_phi*x_shift+sin_phi*y_shift)*np.sqrt(1 - e) xt2 = (-sin_phi*x_shift+cos_phi*y_shift)*np.sqrt(1 + e) R_ = np.sqrt(xt1**2 + xt2**2) rho0_input = self.nfw._alpha2rho0(theta_Rs=theta_Rs, Rs=Rs) if Rs < 0.0000001: Rs = 0.0000001 f_ = self.nfw.nfwPot(R_, Rs, rho0_input) return f_
def function(self, x, y, Rs, theta_Rs, e1, e2, center_x=0, center_y=0)
returns double integral of NFW profile
2.996354
2.921661
1.025565
phi_G, q = param_util.ellipticity2phi_q(e1, e2) x_shift = x - center_x y_shift = y - center_y cos_phi = np.cos(phi_G) sin_phi = np.sin(phi_G) e = min(abs(1. - q), 0.99) xt1 = (cos_phi*x_shift+sin_phi*y_shift)*np.sqrt(1 - e) xt2 = (-sin_phi*x_shift+cos_phi*y_shift)*np.sqrt(1 + e) R_ = np.sqrt(xt1**2 + xt2**2) rho0_input = self.nfw._alpha2rho0(theta_Rs=theta_Rs, Rs=Rs) if Rs < 0.0000001: Rs = 0.0000001 f_x_prim, f_y_prim = self.nfw.nfwAlpha(R_, Rs, rho0_input, xt1, xt2) f_x_prim *= np.sqrt(1 - e) f_y_prim *= np.sqrt(1 + e) f_x = cos_phi*f_x_prim-sin_phi*f_y_prim f_y = sin_phi*f_x_prim+cos_phi*f_y_prim return f_x, f_y
def derivatives(self, x, y, Rs, theta_Rs, e1, e2, center_x=0, center_y=0)
returns df/dx and df/dy of the function (integral of NFW)
2.512427
2.419155
1.038555
init_pos = self.chain.get_args(self.chain.kwargs_data_init) num_param = self.chain.num_param lowerLimit = [lowerLimit] * num_param upperLimit = [upperLimit] * num_param if mpi is True: pso = MpiParticleSwarmOptimizer(self.chain, lowerLimit, upperLimit, n_particles, threads=1) else: pso = ParticleSwarmOptimizer(self.chain, lowerLimit, upperLimit, n_particles, threads=threadCount) if not init_pos is None: pso.gbest.position = init_pos pso.gbest.velocity = [0]*len(init_pos) pso.gbest.fitness, _ = self.chain.likelihood(init_pos) X2_list = [] vel_list = [] pos_list = [] time_start = time.time() if pso.isMaster(): print('Computing the %s ...' % print_key) num_iter = 0 for swarm in pso.sample(n_iterations): X2_list.append(pso.gbest.fitness*2) vel_list.append(pso.gbest.velocity) pos_list.append(pso.gbest.position) num_iter += 1 if pso.isMaster(): if num_iter % 10 == 0: print(num_iter) if not mpi: result = pso.gbest.position else: result = MpiUtil.mpiBCast(pso.gbest.position) kwargs_data = self.chain.update_data(result) if mpi is True and not pso.isMaster(): pass else: time_end = time.time() print("Shifts found: ", result) print(time_end - time_start, 'time used for PSO', print_key) return kwargs_data, [X2_list, pos_list, vel_list, []]
def pso(self, n_particles=10, n_iterations=10, lowerLimit=-0.2, upperLimit=0.2, threadCount=1, mpi=False, print_key='default')
returns the best fit for the lense model on catalogue basis with particle swarm optimizer
3.059926
3.007812
1.017326
#generate image and computes likelihood kwargs_data = self.update_data(args) imageModel = class_creator.create_image_model(kwargs_data, self._kwargs_psf, self._kwargs_numerics, self._kwargs_model) logL = imageModel.likelihood_data_given_model(self._kwargs_lens, self._kwargs_source, self._kwargs_lens_light, self._kwargs_else, source_marg=self._source_marg) return logL, None
def _likelihood(self, args)
routine to compute X2 given variable parameters for a MCMC/PSO chainF
5.636785
5.660324
0.995841
if restart < 0: raise ValueError("parameter 'restart' must be integer of value > 0") # particle swarm optimization penalties, parameters, src_pen_best = [],[], [] for run in range(0, restart): penalty, params = self._single_optimization(n_particles, n_iterations) penalties.append(penalty) parameters.append(params) src_pen_best.append(self._optimizer.src_pen_best) # select the best optimization best_index = np.argmin(penalties) # combine the optimized parameters with the parameters kept fixed during the optimization to obtain full kwargs_lens kwargs_varied = self._params.argstovary_todictionary(parameters[best_index]) kwargs_lens_final = kwargs_varied + self._params.argsfixed_todictionary() # solve for the optimized image positions srcx, srcy = self._optimizer.lensing._ray_shooting_fast(kwargs_varied) source_x, source_y = np.mean(srcx), np.mean(srcy) # if we have a good enough solution, no point in recomputing the image positions since this can be quite slow # and will give the same answer if src_pen_best[best_index] < self._tol_src_penalty: x_image, y_image = self.x_pos, self.y_pos else: # Here, the solver has the instance of "lensing_class" or "LensModel" for multiplane/singleplane respectively. print('Warning: possibly a bad fit.') x_image, y_image = self.solver.findBrightImage(source_x, source_y, kwargs_lens_final, arrival_time_sort=False) #x_image, y_image = self.solver.image_position_from_source(source_x, source_y, kwargs_lens_final, arrival_time_sort = False) if self._verbose: print('optimization done.') print('Recovered source position: ', (srcx, srcy)) return kwargs_lens_final, [source_x, source_y], [x_image, y_image]
def optimize(self, n_particles=50, n_iterations=250, restart=1)
the best result of all optimizations will be returned. total number of lens models sovled: n_particles*n_iterations :param n_particles: number of particle swarm particles :param n_iterations: number of particle swarm iternations :param restart: number of times to execute the optimization; :return: lens model keywords, [optimized source position], best fit image positions
5.343195
5.110281
1.045578
pso = ParticleSwarmOptimizer(optimizer, low=self._lower_limit, high=self._upper_limit, particleCount=n_particles) gBests = pso._optimize(maxIter=n_iterations,standard_dev=self._pso_convergence_standardDEV) likelihoods = [particle.fitness for particle in gBests] ind = np.argmax(likelihoods) return gBests[ind].position
def _pso(self, n_particles, n_iterations, optimizer)
:param n_particles: number of PSO particles :param n_iterations: number of PSO iterations :param optimizer: instance of SinglePlaneOptimizer or MultiPlaneOptimizer :return: optimized kwargs_lens
5.745327
6.06225
0.947722
amplitudes_3d = amplitudes / sigmas / np.sqrt(2*np.pi) return amplitudes_3d, sigmas
def de_projection_3d(amplitudes, sigmas)
de-projects a gaussian (or list of multiple Gaussians from a 2d projected to a 3d profile) :param amplitudes: :param sigmas: :return:
3.444631
4.537174
0.759202
self._pixel_size = deltaPix if self.psf_type == 'GAUSSIAN': try: del self._kernel_point_source except: pass
def set_pixel_size(self, deltaPix)
update pixel size :param deltaPix: :return:
4.862752
5.426239
0.896155
psf_type = self.psf_type if psf_type == 'NONE': return grid elif psf_type == 'GAUSSIAN': sigma = self._sigma_gaussian/grid_scale img_conv = ndimage.filters.gaussian_filter(grid, sigma, mode='nearest', truncate=self._truncation) return img_conv elif psf_type == 'PIXEL': if psf_subgrid: kernel = self.subgrid_pixel_kernel(subgrid_res) else: kernel = self._kernel_pixel img_conv1 = signal.fftconvolve(grid, kernel, mode='same') return img_conv1 else: raise ValueError('PSF type %s not valid!' % psf_type)
def psf_convolution(self, grid, grid_scale, psf_subgrid=False, subgrid_res=1)
convolves a given pixel grid with a PSF
2.447499
2.434414
1.005375
com_x = (Fm * center1_x + center2_x)/(Fm + 1.) com_y = (Fm * center1_y + center2_y)/(Fm + 1.) return com_x, com_y
def com(self, center1_x, center1_y, center2_x, center2_y, Fm)
:return: center of mass
1.95565
1.923795
1.016558
phi_G = np.arctan2(center2_y - center1_y, center2_x - center1_x) return phi_G
def angle(self, center1_x, center1_y, center2_x, center2_y)
compute the rotation angle of the dipole :return:
2.76149
3.08104
0.896285
x_pos, y_pos = self._pointSource.image_position(kwargs_ps=kwargs_ps, kwargs_lens=kwargs_lens) x_pos, y_pos = self._param.real_image_positions(x_pos[0], y_pos[0], kwargs_cosmo) x_source, y_source = self._lensModel.ray_shooting(x_pos, y_pos, kwargs_lens) delay_arcsec = self._lensModel.fermat_potential(x_pos, y_pos, x_source, y_source, kwargs_lens) D_dt_model = kwargs_cosmo['D_dt'] delay_days = const.delay_arcsec2days(delay_arcsec, D_dt_model) logL = self._logL_delays(delay_days, self._delays_measured, self._delays_errors) return logL
def logL(self, kwargs_lens, kwargs_ps, kwargs_cosmo)
routine to compute the log likelihood of the time delay distance :param kwargs_lens: lens model kwargs list :param kwargs_ps: point source kwargs list :param kwargs_cosmo: cosmology and other kwargs :return: log likelihood of the model given the time delay data
3.630469
3.477603
1.043957
delta_t_model = np.array(delays_model[1:]) - delays_model[0] logL = np.sum(-(delta_t_model - delays_measured) ** 2 / (2 * delays_errors ** 2)) return logL
def _logL_delays(self, delays_model, delays_measured, delays_errors)
log likelihood of modeled delays vs measured time delays under considerations of errors :param delays_model: n delays of the model (not relative delays) :param delays_measured: relative delays (1-2,1-3,1-4) relative to the first in the list :param delays_errors: gaussian errors on the measured delays :return: log likelihood of data given model
2.894579
3.296065
0.878192
if pixel_unit is True: ra_shift, dec_shift = self.map_pix2coord(x_shift, y_shift) else: ra_shift, dec_shift = x_shift, y_shift self._ra_at_xy_0 += ra_shift self._dec_at_xy_0 += dec_shift self._x_at_radec_0, self._y_at_radec_0 = util.map_coord2pix(-self._ra_at_xy_0, -self._dec_at_xy_0, 0, 0, self._Ma2pix)
def shift_coordinate_grid(self, x_shift, y_shift, pixel_unit=False)
shifts the coordinate system :param x_shif: shift in x (or RA) :param y_shift: shift in y (or DEC) :param pixel_unit: bool, if True, units of pixels in input, otherwise RA/DEC :return: updated data class with change in coordinate system
2.726533
2.739136
0.995399
if self._solver_type == 'PROFILE_SHEAR': e1 = kwargs_list[1]['e1'] e2 = kwargs_list[1]['e2'] phi_ext, gamma_ext = param_util.ellipticity2phi_gamma(e1, e2) else: phi_ext = 0 lens_model = self._lens_mode_list[0] if lens_model in ['SPEP', 'SPEMD', 'SIE', 'NIE']: e1 = kwargs_list[0]['e1'] e2 = kwargs_list[0]['e2'] center_x = kwargs_list[0]['center_x'] center_y = kwargs_list[0]['center_y'] theta_E = kwargs_list[0]['theta_E'] x = [theta_E, e1, e2, center_x, center_y, phi_ext] elif lens_model in ['NFW_ELLIPSE']: e1 = kwargs_list[0]['e1'] e2 = kwargs_list[0]['e2'] center_x = kwargs_list[0]['center_x'] center_y = kwargs_list[0]['center_y'] theta_Rs = kwargs_list[0]['theta_Rs'] x = [theta_Rs, e1, e2, center_x, center_y, phi_ext] elif lens_model in ['SHAPELETS_CART']: coeffs = list(kwargs_list[0]['coeffs']) [c10, c01, c20, c11, c02] = coeffs[1: 6] x = [c10, c01, c20, c11, c02, phi_ext] else: raise ValueError("Lens model %s not supported for 4-point solver!" % lens_model) return x
def _extract_array(self, kwargs_list)
inverse of _update_kwargs :param kwargs_list: :return:
2.383342
2.405708
0.990703
#self._check_interp(grid_interp_x, grid_interp_y, f_, f_x, f_y, f_xx, f_yy, f_xy) n = len(np.atleast_1d(x)) if n <= 1 and np.shape(x) == (): #if type(x) == float or type(x) == int or type(x) == type(np.float64(1)) or len(x) <= 1: f_x_out = self.f_x_interp(x, y, grid_interp_x, grid_interp_y, f_x) f_y_out = self.f_y_interp(x, y, grid_interp_x, grid_interp_y, f_y) return f_x_out[0][0], f_y_out[0][0] else: if self._grid and n >= self._min_grid_number: x_, y_ = util.get_axes(x, y) f_x_out = self.f_x_interp(x_, y_, grid_interp_x, grid_interp_y, f_x) f_y_out = self.f_y_interp(x_, y_, grid_interp_x, grid_interp_y, f_y) f_x_out = util.image2array(f_x_out) f_y_out = util.image2array(f_y_out) else: #n = len(x) f_x_out, f_y_out = np.zeros(n), np.zeros(n) for i in range(n): f_x_out[i] = self.f_x_interp(x[i], y[i], grid_interp_x, grid_interp_y, f_x) f_y_out[i] = self.f_y_interp(x[i], y[i], grid_interp_x, grid_interp_y, f_y) return f_x_out, f_y_out
def derivatives(self, x, y, grid_interp_x=None, grid_interp_y=None, f_=None, f_x=None, f_y=None, f_xx=None, f_yy=None, f_xy=None)
returns df/dx and df/dy of the function
1.752076
1.759797
0.995613
#self._check_interp(grid_interp_x, grid_interp_y, f_, f_x, f_y, f_xx, f_yy, f_xy) n = len(np.atleast_1d(x)) if n <= 1 and np.shape(x) == (): #if type(x) == float or type(x) == int or type(x) == type(np.float64(1)) or len(x) <= 1: f_xx_out = self.f_xx_interp(x, y, grid_interp_x, grid_interp_y, f_xx) f_yy_out = self.f_yy_interp(x, y, grid_interp_x, grid_interp_y, f_yy) f_xy_out = self.f_xy_interp(x, y, grid_interp_x, grid_interp_y, f_xy) return f_xx_out[0][0], f_yy_out[0][0], f_xy_out[0][0] else: if self._grid and n >= self._min_grid_number: x_, y_ = util.get_axes(x, y) f_xx_out = self.f_xx_interp(x_, y_, grid_interp_x, grid_interp_y, f_xx) f_yy_out = self.f_yy_interp(x_, y_, grid_interp_x, grid_interp_y, f_yy) f_xy_out = self.f_xy_interp(x_, y_, grid_interp_x, grid_interp_y, f_xy) f_xx_out = util.image2array(f_xx_out) f_yy_out = util.image2array(f_yy_out) f_xy_out = util.image2array(f_xy_out) else: #n = len(x) f_xx_out, f_yy_out, f_xy_out = np.zeros(n), np.zeros(n), np.zeros(n) for i in range(n): f_xx_out[i] = self.f_xx_interp(x[i], y[i], grid_interp_x, grid_interp_y, f_xx) f_yy_out[i] = self.f_yy_interp(x[i], y[i], grid_interp_x, grid_interp_y, f_yy) f_xy_out[i] = self.f_xy_interp(x[i], y[i], grid_interp_x, grid_interp_y, f_xy) return f_xx_out, f_yy_out, f_xy_out
def hessian(self, x, y, grid_interp_x=None, grid_interp_y=None, f_=None, f_x=None, f_y=None, f_xx=None, f_yy=None, f_xy=None)
returns Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy
1.528743
1.535251
0.995761
kwargs_data = sim_util.data_configure_simple(numPix, deltaPix) data = Data(kwargs_data) _frame_size = numPix * deltaPix _coords = data._coords x_grid, y_grid = data.coordinates lensModelExt = LensModelExtensions(lensModel) #ra_crit_list, dec_crit_list, ra_caustic_list, dec_caustic_list = lensModelExt.critical_curve_caustics( # kwargs_lens, compute_window=_frame_size, grid_scale=deltaPix/2.) x_grid1d = util.image2array(x_grid) y_grid1d = util.image2array(y_grid) kappa_result = lensModel.kappa(x_grid1d, y_grid1d, kwargs_lens) kappa_result = util.array2image(kappa_result) im = ax.matshow(np.log10(kappa_result), origin='lower', extent=[0, _frame_size, 0, _frame_size], cmap='Greys', vmin=-1, vmax=1) #, cmap=self._cmap, vmin=v_min, vmax=v_max) if with_caustics is True: ra_crit_list, dec_crit_list = lensModelExt.critical_curve_tiling(kwargs_lens, compute_window=_frame_size, start_scale=deltaPix, max_order=10) ra_caustic_list, dec_caustic_list = lensModel.ray_shooting(ra_crit_list, dec_crit_list, kwargs_lens) plot_line_set(ax, _coords, ra_caustic_list, dec_caustic_list, color='g') plot_line_set(ax, _coords, ra_crit_list, dec_crit_list, color='r') if point_source: from lenstronomy.LensModel.Solver.lens_equation_solver import LensEquationSolver solver = LensEquationSolver(lensModel) theta_x, theta_y = solver.image_position_from_source(sourcePos_x, sourcePos_y, kwargs_lens, min_distance=deltaPix, search_window=deltaPix*numPix) mag_images = lensModel.magnification(theta_x, theta_y, kwargs_lens) x_image, y_image = _coords.map_coord2pix(theta_x, theta_y) abc_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'] for i in range(len(x_image)): x_ = (x_image[i] + 0.5) * deltaPix y_ = (y_image[i] + 0.5) * deltaPix ax.plot(x_, y_, 'dk', markersize=4*(1 + np.log(np.abs(mag_images[i]))), alpha=0.5) ax.text(x_, y_, abc_list[i], fontsize=20, color='k') x_source, y_source = _coords.map_coord2pix(sourcePos_x, sourcePos_y) ax.plot((x_source + 0.5) * deltaPix, (y_source + 0.5) * deltaPix, '*k', markersize=10) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.autoscale(False) #image_position_plot(ax, _coords, self._kwargs_else) #source_position_plot(ax, self._coords, self._kwargs_source) return ax
def lens_model_plot(ax, lensModel, kwargs_lens, numPix=500, deltaPix=0.01, sourcePos_x=0, sourcePos_y=0, point_source=False, with_caustics=False)
plots a lens model (convergence) and the critical curves and caustics :param ax: :param kwargs_lens: :param numPix: :param deltaPix: :return:
2.316794
2.328132
0.99513
num_samples = len(samples_mcmc[:, 0]) num_average = int(num_average) n_points = int((num_samples - num_samples % num_average) / num_average) for i, param_name in enumerate(param_mcmc): samples = samples_mcmc[:, i] samples_averaged = np.average(samples[:int(n_points * num_average)].reshape(n_points, num_average), axis=1) end_point = np.mean(samples_averaged) samples_renormed = (samples_averaged - end_point) / np.std(samples_averaged) ax.plot(samples_renormed, label=param_name) dist_averaged = -np.max(dist_mcmc[:int(n_points * num_average)].reshape(n_points, num_average), axis=1) dist_normed = (dist_averaged - np.max(dist_averaged)) / (np.max(dist_averaged) - np.min(dist_averaged)) ax.plot(dist_normed, label="logL", color='k', linewidth=2) ax.legend() return ax
def plot_mcmc_behaviour(ax, samples_mcmc, param_mcmc, dist_mcmc, num_average=100)
plots the MCMC behaviour and looks for convergence of the chain :param samples_mcmc: parameters sampled 2d numpy array :param param_mcmc: list of parameters :param dist_mcmc: log likelihood of the chain :param num_average: number of samples to average (should coincide with the number of samples in the emcee process) :return:
2.267838
2.262043
1.002562
f, axes = plt.subplots(2, 3, figsize=(16, 8)) self.data_plot(ax=axes[0, 0]) self.model_plot(ax=axes[0, 1], image_names=True) self.normalized_residual_plot(ax=axes[0, 2], v_min=-6, v_max=6) self.source_plot(ax=axes[1, 0], deltaPix_source=0.01, numPix=100, with_caustics=with_caustics) self.convergence_plot(ax=axes[1, 1], v_max=1) self.magnification_plot(ax=axes[1, 2]) f.tight_layout() f.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0., hspace=0.05) return f, axes
def plot_main(self, with_caustics=False, image_names=False)
print the main plots together in a joint frame :return:
2.347707
2.397897
0.979069
f, axes = plt.subplots(2, 3, figsize=(16, 8)) self.decomposition_plot(ax=axes[0, 0], text='Lens light', lens_light_add=True, unconvolved=True) self.decomposition_plot(ax=axes[1, 0], text='Lens light convolved', lens_light_add=True) self.decomposition_plot(ax=axes[0, 1], text='Source light', source_add=True, unconvolved=True) self.decomposition_plot(ax=axes[1, 1], text='Source light convolved', source_add=True) self.decomposition_plot(ax=axes[0, 2], text='All components', source_add=True, lens_light_add=True, unconvolved=True) self.decomposition_plot(ax=axes[1, 2], text='All components convolved', source_add=True, lens_light_add=True, point_source_add=True) f.tight_layout() f.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0., hspace=0.05) return f, axes
def plot_separate(self)
plot the different model components separately :return:
1.960286
1.969809
0.995166
f, axes = plt.subplots(2, 3, figsize=(16, 8)) self.subtract_from_data_plot(ax=axes[0, 0], text='Data') self.subtract_from_data_plot(ax=axes[0, 1], text='Data - Point Source', point_source_add=True) self.subtract_from_data_plot(ax=axes[0, 2], text='Data - Lens Light', lens_light_add=True) self.subtract_from_data_plot(ax=axes[1, 0], text='Data - Source Light', source_add=True) self.subtract_from_data_plot(ax=axes[1, 1], text='Data - Source Light - Point Source', source_add=True, point_source_add=True) self.subtract_from_data_plot(ax=axes[1, 2], text='Data - Lens Light - Point Source', lens_light_add=True, point_source_add=True) f.tight_layout() f.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0., hspace=0.05) return f, axes
def plot_subtract_from_data_all(self)
subtract model components from data :return:
1.767119
1.807873
0.977457
shapelets = self._createShapelet(coeffs) r, phi = param_util.cart2polar(x, y, center=np.array([center_x, center_y])) alpha1_shapelets, alpha2_shapelets = self._alphaShapelets(shapelets, beta) f_x = self._shapeletOutput(r, phi, beta, alpha1_shapelets) f_y = self._shapeletOutput(r, phi, beta, alpha2_shapelets) return f_x, f_y
def derivatives(self, x, y, coeffs, beta, center_x=0, center_y=0)
returns df/dx and df/dy of the function
3.801294
3.6863
1.031195
shapelets = self._createShapelet(coeffs) r, phi = param_util.cart2polar(x, y, center=np.array([center_x, center_y])) kappa_shapelets=self._kappaShapelets(shapelets, beta) gamma1_shapelets, gamma2_shapelets=self._gammaShapelets(shapelets, beta) kappa_value=self._shapeletOutput(r, phi, beta, kappa_shapelets) gamma1_value=self._shapeletOutput(r, phi, beta, gamma1_shapelets) gamma2_value=self._shapeletOutput(r, phi, beta, gamma2_shapelets) f_xx = kappa_value + gamma1_value f_xy = gamma2_value f_yy = kappa_value - gamma1_value return f_xx, f_yy, f_xy
def hessian(self, x, y, coeffs, beta, center_x=0, center_y=0)
returns Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy
2.723349
2.713784
1.003525
n_coeffs = len(coeff) num_l = self._get_num_l(n_coeffs) shapelets=np.zeros((num_l+1,num_l+1),'complex') nl=0 k=0 i=0 while i < len(coeff): if i%2==0: shapelets[nl][k]+=coeff[i]/2. shapelets[k][nl]+=coeff[i]/2. if k==nl: nl+=1 k=0 i+=1 continue else: k+=1 i+=1 continue else: shapelets[nl][k] += 1j*coeff[i]/2. shapelets[k][nl] -= 1j*coeff[i]/2. i+=1 return shapelets
def _createShapelet(self,coeff)
returns a shapelet array out of the coefficients *a, up to order l :param num_l: order of shapelets :type num_l: int. :param coeff: shapelet coefficients :type coeff: floats :returns: complex array :raises: AttributeError, KeyError
2.68775
2.506196
1.072442
if type(r) == float or type(r) == int or type(r) == type(np.float64(1)) or len(r) <= 1: values = 0. else: values = np.zeros(len(r), 'complex') for nl in range(0,len(shapelets)): #sum over different shapelets for nr in range(0,len(shapelets)): value = shapelets[nl][nr]*self._chi_lr(r, phi, nl, nr, beta) values += value return values.real
def _shapeletOutput(self, r, phi, beta, shapelets)
returns the the numerical values of a set of shapelets at polar coordinates :param shapelets: set of shapelets [l=,r=,a_lr=] :type shapelets: array of size (n,3) :param coordPolar: set of coordinates in polar units :type coordPolar: array of size (n,2) :returns: array of same size with coords [r,phi] :raises: AttributeError, KeyError
4.085163
4.492147
0.909401
m=int((nr-nl).real) n=int((nr+nl).real) p=int((n-abs(m))/2) p2=int((n+abs(m))/2) q=int(abs(m)) if p % 2==0: #if p is even prefac=1 else: prefac=-1 prefactor=prefac/beta**(abs(m)+1)*np.sqrt(math.factorial(p)/(np.pi*math.factorial(p2))) poly=self.poly[p][q] return prefactor*r**q*poly((r/beta)**2)*np.exp(-(r/beta)**2/2)*np.exp(-1j*m*phi)
def _chi_lr(self,r, phi, nl,nr,beta)
computes the generalized polar basis function in the convention of Massey&Refregier eqn 8 :param nl: left basis :type nl: int :param nr: right basis :type nr: int :param beta: beta --the characteristic scale typically choosen to be close to the size of the object. :type beta: float. :param coord: coordinates [r,phi] :type coord: array(n,2) :returns: values at positions of coordinates. :raises: AttributeError, KeyError
4.456156
4.36764
1.020266
output=np.zeros((len(shapelets)+1,len(shapelets)+1),'complex') for nl in range(0,len(shapelets)): for nr in range(0,len(shapelets)): a_lr=shapelets[nl][nr] if nl>0: output[nl-1][nr+1]+=a_lr*np.sqrt(nl*(nr+1))/2 if nr>0: output[nl-1][nr-1]+=a_lr*np.sqrt(nl*nr)/2 output[nl+1][nr+1]+=a_lr*np.sqrt((nl+1)*(nr+1))/2 if nr>0: output[nl+1][nr-1]+=a_lr*np.sqrt((nl+1)*nr)/2 return output/beta**2
def _kappaShapelets(self, shapelets, beta)
calculates the convergence kappa given lensing potential shapelet coefficients (laplacian/2) :param shapelets: set of shapelets [l=,r=,a_lr=] :type shapelets: array of size (n,3) :returns: set of kappa shapelets. :raises: AttributeError, KeyError
2.45928
2.343776
1.049281
output_x = np.zeros((len(shapelets)+1, len(shapelets)+1), 'complex') output_y = np.zeros((len(shapelets)+1, len(shapelets)+1), 'complex') for nl in range(0,len(shapelets)): for nr in range(0,len(shapelets)): a_lr=shapelets[nl][nr] output_x[nl][nr+1]-=a_lr*np.sqrt(nr+1)/2 output_y[nl][nr+1]-=a_lr*np.sqrt(nr+1)/2*1j output_x[nl+1][nr]-=a_lr*np.sqrt(nl+1)/2 output_y[nl+1][nr]+=a_lr*np.sqrt(nl+1)/2*1j if nl>0: output_x[nl-1][nr]+=a_lr*np.sqrt(nl)/2 output_y[nl-1][nr]-=a_lr*np.sqrt(nl)/2*1j if nr>0: output_x[nl][nr-1]+=a_lr*np.sqrt(nr)/2 output_y[nl][nr-1]+=a_lr*np.sqrt(nr)/2*1j return output_x/beta,output_y/beta
def _alphaShapelets(self,shapelets, beta)
calculates the deflection angles given lensing potential shapelet coefficients (laplacian/2) :param shapelets: set of shapelets [l=,r=,a_lr=] :type shapelets: array of size (n,3) :returns: set of alpha shapelets. :raises: AttributeError, KeyError
1.824818
1.75032
1.042563
const_SI = const.c**2 / (4*np.pi * const.G) #c^2/(4*pi*G) in units of [kg/m] conversion = const.Mpc / const.M_sun # converts [kg/m] to [M_sun/Mpc] pre_const = const_SI*conversion #c^2/(4*pi*G) in units of [M_sun/Mpc] Epsilon_Crit = self.D_s/(self.D_d*self.D_ds) * pre_const #[M_sun/Mpc^2] return Epsilon_Crit
def epsilon_crit(self)
returns the critical projected mass density in units of M_sun/Mpc^2 (physical units)
4.867168
3.933411
1.237391
return np.log(x * (tau + np.sqrt(tau ** 2 + x ** 2)) ** -1)
def L(self, x, tau)
Logarithm that appears frequently :param x: r/Rs :param tau: t/Rs :return:
5.650598
5.616015
1.006158
if isinstance(x, np.ndarray): nfwvals = np.ones_like(x) inds1 = np.where(x < 1) inds2 = np.where(x > 1) nfwvals[inds1] = (1 - x[inds1] ** 2) ** -.5 * np.arctanh((1 - x[inds1] ** 2) ** .5) nfwvals[inds2] = (x[inds2] ** 2 - 1) ** -.5 * np.arctan((x[inds2] ** 2 - 1) ** .5) return nfwvals elif isinstance(x, float) or isinstance(x, int): if x == 1: return 1 if x < 1: return (1 - x ** 2) ** -.5 * np.arctanh((1 - x ** 2) ** .5) else: return (x ** 2 - 1) ** -.5 * np.arctan((x ** 2 - 1) ** .5)
def F(self, x)
Classic NFW function in terms of arctanh and arctan :param x: r/Rs :return:
1.709327
1.593889
1.072426
x_ = x - center_x y_ = y - center_y R = np.sqrt(x_ ** 2 + y_ ** 2) x = R * Rs ** -1 tau = float(r_trunc) * Rs ** -1 Fx = self._F(x, tau) return 2 * rho0 * Rs * Fx
def density_2d(self, x, y, Rs, rho0, r_trunc, center_x=0, center_y=0)
projected two dimenstional NFW profile (kappa*Sigma_crit) :param R: radius of interest :type R: float/numpy array :param Rs: scale radius :type Rs: float :param rho0: density normalization (characteristic density) :type rho0: float :param r200: radius of (sub)halo :type r200: float>0 :return: Epsilon(R) projected density at radius R
3.903711
4.622973
0.844416
x = R * Rs ** -1 func = (r_trunc ** 2 * (-2 * x * (1 + r_trunc ** 2) + 4 * (1 + x) * r_trunc * np.arctan(x / r_trunc) - 2 * (1 + x) * (-1 + r_trunc ** 2) * np.log(Rs) + 2 * (1 + x) * (-1 + r_trunc ** 2) * np.log(Rs * (1 + x)) + 2 * (1 + x) * (-1 + r_trunc ** 2) * np.log(Rs * r_trunc) - (1 + x) * (-1 + r_trunc ** 2) * np.log(Rs ** 2 * (x ** 2 + r_trunc ** 2)))) / (2. * (1 + x) * (1 + r_trunc ** 2) ** 2) m_3d = 4*np.pi*Rs ** 3 * rho0 * func return m_3d
def mass_3d(self, R, Rs, rho0, r_trunc)
mass enclosed a 3d sphere or radius r :param r: :param Ra: :param Rs: :return:
2.632994
2.696324
0.976512
x = R / Rs tau = float(r_trunc) / Rs hx = self._h(x, tau) return 2 * rho0 * Rs ** 3 * hx
def nfwPot(self, R, Rs, rho0, r_trunc)
lensing potential of NFW profile :param R: radius of interest :type R: float/numpy array :param Rs: scale radius :type Rs: float :param rho0: density normalization (characteristic density) :type rho0: float :return: Epsilon(R) projected density at radius R
7.271843
9.269162
0.78452
if isinstance(R, int) or isinstance(R, float): R = max(R, 0.00001) else: R[R <= 0.00001] = 0.00001 x = R / Rs tau = float(r_trunc) / Rs gx = self._g(x, tau) a = 4 * rho0 * Rs * gx / x ** 2 return a * ax_x, a * ax_y
def nfwAlpha(self, R, Rs, rho0, r_trunc, ax_x, ax_y)
deflection angel of NFW profile along the projection to coordinate axis :param R: radius of interest :type R: float/numpy array :param Rs: scale radius :type Rs: float :param rho0: density normalization (characteristic density) :type rho0: float :param r200: radius of (sub)halo :type r200: float>0 :param axis: projection to either x- or y-axis :type axis: same as R :return: Epsilon(R) projected density at radius R
3.422698
4.079462
0.839007
x = R / Rs tau = r_trunc / Rs gx = self._g(x,tau) m_2d = 4 * rho0 * Rs * R ** 2 * gx / x ** 2 * np.pi return m_2d
def mass_2d(self,R,Rs,rho0,r_trunc)
analytic solution of the projection integral (convergence) :param x: R/Rs :type x: float >0
5.120511
5.934815
0.862792
t2 = tau ** 2 #Fx = self.F(X) _F = self.F(X) a = t2*(t2+1)**-2 if isinstance(X, np.ndarray): #b = (t2 + 1) * (X ** 2 - 1) ** -1 * (1 - _F) b = np.ones_like(X) b[X == 1] = (t2+1) * 1./3 b[X != 1] = (t2 + 1) * (X[X != 1] ** 2 - 1) ** -1 * (1 - _F[X != 1]) elif isinstance(X, float) or isinstance(X, int): if X == 1: b = (t2+1)* 1./3 else: b = (t2+1)*(X**2-1)**-1*(1-_F) else: raise ValueError("The variable type is not compatible with the function, please use float, int or ndarray's.") c = 2*_F d = -np.pi*(t2+X**2)**-0.5 e = (t2-1)*(tau*(t2+X**2)**0.5)**-1*self.L(X,tau) result = a * (b + c + d + e) return result
def _F(self, X, tau)
analytic solution of the projection integral (convergence) :param x: R/Rs :type x: float >0
3.457586
3.554658
0.972692
return tau ** 2 * (tau ** 2 + 1) ** -2 * ( (tau ** 2 + 1 + 2 * (x ** 2 - 1)) * self.F(x) + tau * np.pi + (tau ** 2 - 1) * np.log(tau) + np.sqrt(tau ** 2 + x ** 2) * (-np.pi + self.L(x, tau) * (tau ** 2 - 1) * tau ** -1))
def _g(self, x, tau)
analytic solution of integral for NFW profile to compute deflection angel and gamma :param x: R/Rs :type x: float >0
4.18123
4.602838
0.908403
def cos_func(y): if isinstance(y, float) or isinstance(y, int): if y > 1: return np.arccosh(y) else: return np.arccos(y) else: values = np.ones_like(y) inds1 = np.where(y < 1) inds2 = np.where(y > 1) values[inds1] = np.arccos(y[inds1]) # values[inds2] = np.arccosh(y[inds2]) values[inds2] = np.arccos((1 - y[inds2]) ** .5) return values def nfw_func(x): if isinstance(x,float) or isinstance(x,int): if x<1: return np.log(x / 2.) ** 2 - np.arccosh(1. / x) ** 2 else: return np.log(x / 2.)**2 - np.arccos(1. /x)**2 else: inds1 = np.where(x < 1) inds2 = np.where(x >= 1) y = np.zeros_like(x) y[inds1] = np.log(x[inds1] / 2.) ** 2 - np.arccosh(1. / x[inds1]) ** 2 y[inds2] = np.log(x[inds2] / 2.) ** 2 - np.arccosh(1. / x[inds2]) ** 2 return y def tnfw_func(x,tau): u = x**2 t2 = tau**2 Lx = self.L(u**.5, tau) return (t2 + 1) ** -2 * ( 2 * t2 * np.pi * (tau - (t2 + u) ** .5 + tau * np.log(tau + (t2 + u) ** .5)) + 2 * (t2 - 1) * tau * (t2 + u) ** .5 * Lx + t2 * (t2 - 1) * Lx ** 2 + 4 * t2 * (u - 1) * self.F(u**.5) + t2 * (t2 - 1) * (cos_func(u ** -0.5)) ** 2 + t2 * ((t2 - 1) * np.log(tau) - t2 - 1) * np.log(u) - t2 * ( (t2 - 1) * np.log(tau) * np.log(4 * tau) + 2 * np.log(0.5 * tau) - 2 * tau * (tau - np.pi) * np.log( tau * 2))) c = 1e-9 rescale = 1 if np.any(X-c<1): warnings.warn('Truncated NFW potential not yet implemented for x<1. Using the expression for the NFW ' 'potential in this regime isntead.') rescale = tnfw_func(1.00001,tau)*nfw_func(1)**-1 if isinstance(X,float) or isinstance(X,int): if X<1: X = min(X,0.001) return nfw_func(X)*rescale else: return tnfw_func(X,tau) else: X[np.where(X<0.001)] = 0.001 values = np.zeros_like(X) inds1,inds2 = np.where(X<1),np.where(X>=1) values[inds1] = nfw_func(X[inds1])*rescale values[inds2] = tnfw_func(X[inds2],tau) return values
def _h(self, X, tau)
a horrible expression for the integral to compute potential :param x: R/Rs :param tau: t/Rs :type x: float >0
2.795165
2.781514
1.004908
coordShift_x = x - center[0] coordShift_y = y - center[1] r = np.sqrt(coordShift_x**2+coordShift_y**2) phi = np.arctan2(coordShift_y, coordShift_x) return r, phi
def cart2polar(x, y, center=np.array([0, 0]))
transforms cartesian coords [x,y] into polar coords [r,phi] in the frame of the lense center :param coord: set of coordinates :type coord: array of size (n,2) :param center: rotation point :type center: array of size (2) :returns: array of same size with coords [r,phi] :raises: AttributeError, KeyError
2.109694
2.436967
0.865704
x = r*np.cos(phi) y = r*np.sin(phi) return x - center[0], y - center[1]
def polar2cart(r, phi, center)
transforms polar coords [r,phi] into cartesian coords [x,y] in the frame of the lense center :param coord: set of coordinates :type coord: array of size (n,2) :param center: rotation point :type center: array of size (2) :returns: array of same size with coords [x,y] :raises: AttributeError, KeyError
1.991483
3.441973
0.578587
phi = np.arctan2(e2, e1)/2 gamma = np.sqrt(e1**2+e2**2) return phi, gamma
def ellipticity2phi_gamma(e1, e2)
:param e1: ellipticity component :param e2: ellipticity component :return: angle and abs value of ellipticity
2.111216
2.601074
0.811671
x_shift = x - center_x y_shift = y - center_y x_ = (1-e1) * x_shift - e2 * y_shift y_ = -e2 * x_shift + (1 + e1) * y_shift det = np.sqrt((1-e1)*(1+e1) + e2**2) return x_ / det, y_ / det
def transform_e1e2(x, y, e1, e2, center_x=0, center_y=0)
maps the coordinates x, y with eccentricities e1 e2 into a new elliptical coordiante system :param x: :param y: :param e1: :param e2: :param center_x: :param center_y: :return:
2.669987
2.828673
0.943901
phi = np.arctan2(e2, e1)/2 c = np.sqrt(e1**2+e2**2) if c > 0.999: c = 0.999 q = (1-c)/(1+c) return phi, q
def ellipticity2phi_q(e1, e2)
:param e1: :param e2: :return:
2.447891
2.621327
0.933837
fermat_pot = self.lens_analysis.fermat_potential(kwargs_lens, kwargs_ps) time_delay = self.lensCosmo.time_delay_units(fermat_pot, kappa_ext) return time_delay
def time_delays(self, kwargs_lens, kwargs_ps, kappa_ext=0)
predicts the time delays of the image positions :param kwargs_lens: lens model parameters :param kwargs_ps: point source parameters :param kappa_ext: external convergence (optional) :return: time delays at image positions for the fixed cosmology
4.448122
5.071663
0.877054
gamma = kwargs_lens[0]['gamma'] if 'center_x' in kwargs_lens_light[0]: center_x, center_y = kwargs_lens_light[0]['center_x'], kwargs_lens_light[0]['center_y'] else: center_x, center_y = 0, 0 if r_eff is None: r_eff = self.lens_analysis.half_light_radius_lens(kwargs_lens_light, center_x=center_x, center_y=center_y, model_bool_list=lens_light_model_bool_list) theta_E = kwargs_lens[0]['theta_E'] r_ani = aniso_param * r_eff sigma2 = self.analytic_kinematics.vel_disp(gamma, theta_E, r_eff, r_ani, R_slit, dR_slit, FWHM=psf_fwhm, rendering_number=num_evaluate) return sigma2
def velocity_dispersion(self, kwargs_lens, kwargs_lens_light, lens_light_model_bool_list=None, aniso_param=1, r_eff=None, R_slit=0.81, dR_slit=0.1, psf_fwhm=0.7, num_evaluate=1000)
computes the LOS velocity dispersion of the lens within a slit of size R_slit x dR_slit and seeing psf_fwhm. The assumptions are a Hernquist light profile and the spherical power-law lens model at the first position. Further information can be found in the AnalyticKinematics() class. :param kwargs_lens: lens model parameters :param kwargs_lens_light: deflector light parameters :param aniso_param: scaled r_ani with respect to the half light radius :param r_eff: half light radius, if not provided, will be computed from the lens light model :param R_slit: width of the slit :param dR_slit: length of the slit :param psf_fwhm: full width at half maximum of the seeing condition :param num_evaluate: number of spectral rendering of the light distribution that end up on the slit :return: velocity dispersion in units [km/s]
2.347839
2.194118
1.07006
x_ = x - center_x y_ = y - center_y r = np.sqrt(x_**2 + y_**2) sigma_x, sigma_y = sigma, sigma c = 1. / (2 * sigma_x * sigma_y) num_int = self._num_integral(r, c) amp_density = self._amp2d_to_3d(amp, sigma_x, sigma_y) amp2d = amp_density / (np.sqrt(np.pi) * np.sqrt(sigma_x * sigma_y * 2)) amp2d *= 2 * 1. / (2 * c) return num_int * amp2d
def function(self, x, y, amp, sigma, center_x=0, center_y=0)
returns Gaussian
3.234704
3.301679
0.979715
out = integrate.quad(lambda x: (1-np.exp(-c*x**2))/x, 0, r) return out[0]
def _num_integral(self, r, c)
numerical integral (1-e^{-c*x^2})/x dx [0..r] :param r: radius :param c: 1/2sigma^2 :return:
4.765389
2.951329
1.614658
x_ = x - center_x y_ = y - center_y R = np.sqrt(x_**2 + y_**2) sigma_x, sigma_y = sigma, sigma if isinstance(R, int) or isinstance(R, float): R = max(R, self.ds) else: R[R <= self.ds] = self.ds alpha = self.alpha_abs(R, amp, sigma) return alpha / R * x_, alpha / R * y_
def derivatives(self, x, y, amp, sigma, center_x=0, center_y=0)
returns df/dx and df/dy of the function
2.993526
2.958235
1.01193
x_ = x - center_x y_ = y - center_y r = np.sqrt(x_**2 + y_**2) sigma_x, sigma_y = sigma, sigma if isinstance(r, int) or isinstance(r, float): r = max(r, self.ds) else: r[r <= self.ds] = self.ds d_alpha_dr = -self.d_alpha_dr(r, amp, sigma_x, sigma_y) alpha = self.alpha_abs(r, amp, sigma) f_xx = -(d_alpha_dr/r + alpha/r**2) * x_**2/r + alpha/r f_yy = -(d_alpha_dr/r + alpha/r**2) * y_**2/r + alpha/r f_xy = -(d_alpha_dr/r + alpha/r**2) * x_*y_/r return f_xx, f_yy, f_xy
def hessian(self, x, y, amp, sigma, center_x=0, center_y=0)
returns Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy
2.354427
2.309131
1.019616
sigma_x, sigma_y = sigma, sigma amp_density = self._amp2d_to_3d(amp, sigma_x, sigma_y) alpha = self.mass_2d(R, amp_density, sigma) / np.pi / R return alpha
def alpha_abs(self, R, amp, sigma)
absolute value of the deflection :param R: :param amp: :param sigma_x: :param sigma_y: :return:
5.676695
6.561188
0.865193
return amp * np.sqrt(np.pi) * np.sqrt(sigma_x * sigma_y * 2)
def _amp3d_to_2d(self, amp, sigma_x, sigma_y)
converts 3d density into 2d density parameter :param amp: :param sigma_x: :param sigma_y: :return:
4.618087
5.2354
0.882089
return amp / (np.sqrt(np.pi) * np.sqrt(sigma_x * sigma_y * 2))
def _amp2d_to_3d(self, amp, sigma_x, sigma_y)
converts 3d density into 2d density parameter :param amp: :param sigma_x: :param sigma_y: :return:
4.086391
4.986748
0.81945