def create_cn_table(cent_dir='/scratch/hyihp/pang/ini/PbPb_Ini_b0_5_sig0p6', cent='0_5', num_of_events=100, Y=2.4, update_data=False): fout_name = 'cn_b%s.dat' % cent # load from file if data exists if os.path.exists(fout_name) and not update_data: return np.loadtxt(fout_name) event = get_neta_ebe(cent_dir, nevent=num_of_events, cent=cent, update_data=True) eta1 = np.linspace(-Y, Y, num_of_points, endpoint=True) eta2 = np.linspace(-Y, Y, num_of_points, endpoint=True) cn_table = np.empty((num_of_points, num_of_points)) for i, a in enumerate(eta1): for j, b in enumerate(eta2): cn_table[i, j] = Cn(a, b, event) print 'i, j=', i, j, 'finished' # renormalize cn_table to make its average = 1.0 cn_intp = RectBivariateSpline(eta1, eta2, cn_table) cn_tot = cn_intp.integral(-Y, Y, -Y, Y) area = 4.0 * Y * Y cn_table = cn_table / (cn_tot / area) np.savetxt(fout_name, cn_table) return np.array(cn_table)
def get_anm(n, m, cn_table, Y=2.4): '''Cacl a_{n,m}=\int Cn'(eta1, eta2)*(Tn(eta1)*Tm(eta2)+Tn(eta2)Tm(eta1))/2 deta1 deta2 Cn'(eta1, eta2) = cn_table / (cn_total/area) where cn_total=\int cn_table(eta1, eta2) deta1 deta2, and area=2Y*2Y ''' eta1 = np.linspace(-Y, Y, num_of_points, endpoint=True) eta2 = np.linspace(-Y, Y, num_of_points, endpoint=True) CT = np.empty((num_of_points, num_of_points)) for i, a in enumerate(eta1): for j, b in enumerate(eta2): CT[i, j] = cn_table[i, j] * 0.5 * (T(n, a) * T(m, b) + T(n, b) * T(m, a)) # 2d spline interpolation and integration for CT # CT=Cn*0.5*(Tn1*Tm2+Tn2*Tm1) ct_intp = RectBivariateSpline(eta1, eta2, CT) return ct_intp.integral(-Y, Y, -Y, Y)
def integral(self, xa, xb, ya, yb): assert xa <= xb assert ya <= yb total_area = (xb - xa) * (yb - ya) # adjusting interval to spline domain xa_f = np.max([xa, self.xbnds[0]]) xb_f = np.min([xb, self.xbnds[1]]) ya_f = np.max([ya, self.ybnds[0]]) yb_f = np.min([yb, self.ybnds[1]]) # Rectangle does not overlap with spline domain if xa_f >= xb_f or ya_f >= yb_f: return total_area * self.fill_value # Rectangle overlaps with spline domain else: spline_area = (xb_f - xa_f) * (yb_f - ya_f) outside_contribution = (total_area - spline_area) * self.fill_value return outside_contribution + RectBivariateSpline.integral(self, xa_f, xb_f, ya_f, yb_f)
def integral(self, xa, xb, ya, yb): assert xa <= xb assert ya <= yb total_area = (xb - xa) * (yb - ya) # adjusting interval to spline domain xa_f = np.max([xa, self.xbnds[0]]) xb_f = np.min([xb, self.xbnds[1]]) ya_f = np.max([ya, self.ybnds[0]]) yb_f = np.min([yb, self.ybnds[1]]) # Rectangle does not overlap with spline domain if xa_f >= xb_f or ya_f >= yb_f: return total_area * self.fill_value # Rectangle overlaps with spline domain else: spline_area = (xb_f - xa_f) * (yb_f - ya_f) outside_contribution = (total_area - spline_area) * self.fill_value return (outside_contribution + RectBivariateSpline.integral(self, xa_f, xb_f, ya_f, yb_f))
#Probability density for nuclei A and B. n_A = RectBivariateSpline(xx, yy, (Nc**2 - 1) / (32 * np.pi) * Q0_A**2 * T_A / T0_A * 1 / np.log(1 + Q0_A**2 / m**2 * T_A / T0_A)) n_B = RectBivariateSpline(xx, yy, (Nc**2 - 1) / (32 * np.pi) * Q0_B**2 * T_B / T0_B * 1 / np.log(1 + Q0_B**2 / m**2 * T_B / T0_B)) #Saturation scales ^2. Q2_A = RectBivariateSpline(xx, yy, Q0_A**2 * T_A / T0_A) Q2_B = RectBivariateSpline(xx, yy, Q0_B**2 * T_B / T0_B) #Choose size of box in which coords will be generated by the rejection method. #A box within -12 to 12 fm is good enough. lim = 12 #fm #Average number of sources in each nucleus. N_A = n_A.integral(-lim, lim, -lim, lim) N_B = n_B.integral(-lim, lim, -lim, lim) #choose number of events to generate nev = int(1000000) #matrix where we store observables, listed below. obs = np.zeros((nev, 12)) #Event number #impact parameter #tot number of sources #rho #total energy #tot energy*area #rms radius: sqrt(<r^2>)
class PSF(object): """ Point Spread Function (PSF). Attributes: camera (integer): TESS camera (1-4). ccd (integer): TESS CCD (1-4). stamp (tuple): The pixel sub-stamp used to generate PSF. shape (tuple): Shape of pixel sub-stamp. PSFfile (string): Path to PSF file that was interpolated in. ref_column (float): Reference CCD column that PSF is calculated for. ref_row (float): Reference CCD row that PSF is calculated for. splineInterpolation (:py:class:`scipy.interpolate.RectBivariateSpline`): 2D Interpolation to evaluate PSF on arbitrary position relative to center of PSF. .. codeauthor:: Rasmus Handberg <*****@*****.**> """ #---------------------------------------------------------------------------------------------- def __init__(self, sector, camera, ccd, stamp): """ Point Spread Function (PSF). Parameters: sector (integer): TESS Observation sector. camera (integer): TESS camera number (1-4). ccd (integer): TESS CCD number (1-4). stamp (4-tuple): Sub-stamp on CCD to load PSF for. .. codeauthor:: Rasmus Handberg <*****@*****.**> """ # Simple input checks: if sector < 1: raise ValueError("Sector number must be greater than zero") if camera not in (1, 2, 3, 4): raise ValueError("Camera must be 1, 2, 3 or 4.") if ccd not in (1, 2, 3, 4): raise ValueError("CCD must be 1, 2, 3 or 4.") if len(stamp) != 4: raise ValueError("Incorrect stamp provided.") # Store information given in call: self.sector = sector self.camera = camera self.ccd = ccd self.stamp = stamp # Target pixel file shape in pixels: self.shape = (int(stamp[1] - stamp[0]), int(stamp[3] - stamp[2])) # Get path to corresponding TESS PRF file: PSFdir = os.path.join(os.path.dirname(__file__), 'data', 'psf') SectorDir = 'start_s0004' if sector >= 4 else 'start_s0001' PSFglob = os.path.join( PSFdir, SectorDir, 'tess*-{camera:d}-{ccd:d}-characterized-prf.mat'.format( camera=camera, ccd=ccd)) self.PSFfile = glob.glob(PSFglob)[0] # Set minimum PRF weight to avoid dividing by almost 0 somewhere: minimum_prf_weight = 1e-6 # Interpolate the calibrated PRF shape to middle of the stamp: self.ref_column = 0.5 * (stamp[3] + stamp[2]) self.ref_row = 0.5 * (stamp[1] + stamp[0]) # Read the TESS PRF file, which is a MATLAB data file: mat = loadmat(self.PSFfile) mat = mat['prfStruct'] # Center around 0 and convert to PSF subpixel resolution: # We are just using the first one here, assuming they are all the same PRFx = np.asarray(mat['prfColumn'][0][0], dtype='float64').flatten() PRFy = np.asarray(mat['prfRow'][0][0], dtype='float64').flatten() # Find size of PSF images and # the pixel-scale of the PSF images: n_hdu = len(mat['values'][0]) xdim = len(PRFx) ydim = len(PRFy) cdelt1p = np.median(np.diff(PRFx)) cdelt2p = np.median(np.diff(PRFy)) # Preallocate prf array: prf = np.zeros((xdim, ydim), dtype='float64') # Loop through the PRFs measured at different positions: for i in range(n_hdu): prfn = mat['values'][0][i] crval1p = float(mat['ccdColumn'][0][i]) crval2p = float(mat['ccdRow'][0][i]) # Weight with the distance between each PRF sample and the target: prfWeight = np.sqrt((self.ref_column - crval1p)**2 + (self.ref_row - crval2p)**2) # Catch too small weights prfWeight = max(prfWeight, minimum_prf_weight) # Add the weighted values to the PRF array: prf += prfn / prfWeight # Normalize the PRF: prf /= (np.nansum(prf) * cdelt1p * cdelt2p) # Interpolation function over the PRF: self.splineInterpolation = RectBivariateSpline(PRFx, PRFy, prf) #---------------------------------------------------------------------------------------------- def integrate_to_image(self, params, cutoff_radius=5): """ Integrate the underlying high-res PSF onto pixels. Parameters: params (iterator, numpy.array): List of stars to add to image. Should be an iterator where each element is an numpy array with three elements: row, column and flux. cutoff_radius (float, optional): Maximal radius away from center of star in pixels to integrate PSF model. Returns: numpy.array: Image """ img = np.zeros(self.shape, dtype='float64') for i in range(self.shape[0]): for j in range(self.shape[1]): for star in params: star_row = star[0] star_column = star[1] if np.sqrt((j - star_column)**2 + (i - star_row)**2) < cutoff_radius: star_flux = star[2] column_cen = j - star_column row_cen = i - star_row img[i, j] += star_flux * self.splineInterpolation.integral( column_cen - 0.5, column_cen + 0.5, row_cen - 0.5, row_cen + 0.5) return img #---------------------------------------------------------------------------------------------- def plot(self): """ Create a plot of the shape of the PSF. """ stars = np.array([ [self.ref_row - self.stamp[0], self.ref_column - self.stamp[2], 1], ]) y = np.linspace(-6, 6, 500) x = np.linspace(-6, 6, 500) xx, yy = np.meshgrid(y, x) spline = self.splineInterpolation(x, y, grid=True) spline += np.abs(spline.min()) + 1e-14 spline = np.log10(spline) img = self.integrate_to_image(stars) fig = plt.figure() ax = fig.add_subplot(121) ax.contourf(yy, xx, spline, 20, cmap='bone_r') ax.set_xlim(-6, 6) ax.set_ylim(-6, 6) ax.axis('equal') ax = fig.add_subplot(122) plot_image(img, ax=ax) ax.scatter(stars[:, 1], stars[:, 0], c='r', alpha=0.5) plt.tight_layout() return fig
def integrate_to_image(self, stars, integration_time, angle_vel, speed = None, fwhm = 1., jitter = False, focus = False, superres = 10): """ Integrate a PSF that is smeared in one direction to an image. Parameters ---------- stars (list): List with an element for each star. Each element contains the elements ``[row, col, [flux_R, flux_G, flux_B]]`` which are used to generate the star. The row and column position corresponds to the star position at the midtime of exposure. integration_time (float): CCD integration time. angle_vel (float): Angle in radians of star CCD movement. speed (float): Speed of a star in pixels. Default is ``Ǹone```which yields the standard speed estimated from the speed of the ISS. fwhm (float): Full width at half maximum of PSF in pixels. Default is ``1.``. jitter (string): ``True`` if jitter is to be applied. Default is ``False``. Not implemented. focus (string): ``True`` if focus is to be applied. Default is ``False``. Not implemented. Returns ------- img (2D array, float): Smeared, pixel-integrated and Bayer filter scaled PSF. smearKernel (2D array, float): Kernel with a line that specifies the smear of a single PSF. PSFhighres (2D array, float): Subpixel resolution PSF that is convolved with the smear kernel. highresConvPSF (2D array, float): Normalised convolution of smear kernel and subpixel resolution PSF. highresImageInterp (interpolation object): Interpolated smeared PSF. Can be integrated efficiently. """ # Set speed to standard speed if not given as parameter: if speed is None: speed = self.speed # Set subpixel resolution of PSF: self.superres = superres # subpixel resolution # Define subpixel buffer. Needs to be large for correct interpolation: self.buffer = np.int(3*fwhm*self.superres) # Create smear kernel: smearKernel, r0, c0, r1, c1 = self.makeSmearKernel( integration_time, angle_vel, speed, fwhm) self.kernelShape = smearKernel.shape # Get highres PSF: PSFhighres = self.highresPSF(fwhm) # TODO: convolve highres PSF with focus and jitter here # Convolve the PSF with the smear kernel: highresConvPSF = self.convolvePSF(PSFhighres, smearKernel) # Normalise the PRF: highresConvPSF /= np.nansum(highresConvPSF) * self.superres**2 # Define pixel centered index arrays for the interpolater: PRFrow = np.arange(0.5, self.kernelShape[0] + 0.5) PRFcol = np.arange(0.5, self.kernelShape[1] + 0.5) # Center around 0: PRFrow = PRFrow - PRFrow.size / 2 PRFcol = PRFcol - PRFcol.size / 2 # Convert from subpixel to pixel resolution: PRFrow /= self.superres PRFcol /= self.superres # Interpolate highresImage: highresImageInterp = RectBivariateSpline(PRFrow, PRFcol, highresConvPSF) # Preallocate image array: img = np.zeros(self.imshape, dtype=np.float64) # Prepare Bayer filter scaling: Bayer_filter = make_bayer_filter(img.shape) # Integrate the interpolation object in each pixel: for star in stars: for row in range(self.imshape[0]): for col in range(self.imshape[1]): # Get star position in PSF(t=mid)-based coordinates: row_cen = row - star[0] col_cen = col - star[1] # Integrate only significant contributions to avoid artefacts: withinBoundary = highresImageInterp(row_cen, col_cen) > 1e-9 if withinBoundary: # Get flux value: # Red: if Bayer_filter[row,col] == 0: Bayer_flux = star[2][0] # Green: elif Bayer_filter[row,col] == 1: Bayer_flux = star[2][1] # Blue: elif Bayer_filter[row,col] == 2: Bayer_flux = star[2][2] else: raise ValueError( 'Bayer filter flag must be 0, 1 or 2.') # Integrate normalised interpolation in the current pixel: img[row,col] += Bayer_flux * integration_time * \ highresImageInterp.integral( row_cen-0.5, row_cen+0.5, col_cen-0.5, col_cen+0.5) return img, smearKernel, PSFhighres, highresConvPSF, highresImageInterp
mult = min(10,3000.0/nx) h0fine = np.ones((nx*mult,ny*mult)) *H xfine = pyclaw.Dimension('x',-10.0,10.0,nx*mult) yfine = pyclaw.Dimension('y',-10.0,10.0,ny*mult) rfine = np.sqrt(xfine.centers[:,None]**2 + yfine.centers[None,:]**2) h0fine -= eta*np.sign(rfine - R) inter = RectBivariateSpline(xfine.centers,yfine.centers,h0fine) del h0fine,xfine,yfine print("Constructing Initial Condition") # Averaging the interpolant onto the coarse cells h0 = np.zeros(state.grid.num_cells) for i in xrange(x.num_cells): for j in xrange(y.num_cells): h0[i,j] = inter.integral(x.edges[i],x.edges[i+1], y.edges[j],y.edges[j+1])/np.prod(state.grid.delta) r = np.sqrt(x.centers[:,None]**2 + y.centers[None,:]**2) h0[r > 4] = H-eta u0 = np.zeros(domain.grid.num_cells) v0 = np.zeros(domain.grid.num_cells) del inter # Figure out the time step dx,dy = state.grid.delta dt = min(dx,dy)/c/3 nt = int(T/dt)