def test_dep_shear(): """Test the deprecated methods in galsim/deprecated/shear.py """ import time t1 = time.time() s = galsim.Shear(g1=0.17, g2=0.23) np.testing.assert_almost_equal(s.g1, 0.17) np.testing.assert_almost_equal(s.g2, 0.23) check_dep(s.setE1E2, e1=0.4, e2=0.1) np.testing.assert_almost_equal(s.e1, 0.4) np.testing.assert_almost_equal(s.e2, 0.1) check_dep(s.setEBeta, e=0.17, beta=39 * galsim.degrees) np.testing.assert_almost_equal(s.e, 0.17) np.testing.assert_almost_equal(s.beta / galsim.degrees, 39) check_dep(s.setG1G2, g1=-0.23, g2=0.87) np.testing.assert_almost_equal(s.g1, -0.23) np.testing.assert_almost_equal(s.g2, 0.87) check_dep(s.setEta1Eta2, eta1=1.8, eta2=-1.1) np.testing.assert_almost_equal(s.e1 * s.eta / s.e, 1.8) np.testing.assert_almost_equal(s.e2 * s.eta / s.e, -1.1) check_dep(s.setEtaBeta, eta=0.19, beta=52 * galsim.degrees) np.testing.assert_almost_equal(s.eta, 0.19) np.testing.assert_almost_equal(s.beta / galsim.degrees, 52) t2 = time.time() print 'time for %s = %.2f' % (funcname(), t2 - t1)
def _GenerateFromE1E2(config, base, value_type): """@brief Return a Shear constructed from given (e1, e2) """ req = { 'e1' : float, 'e2' : float } kwargs, safe = GetAllParams(config, base, req=req) #print base['obj_num'],'Generate from E1E2: kwargs = ',kwargs return galsim.Shear(**kwargs), safe
def _GenerateFromG1G2(config, base, value_type): """@brief Return a Shear constructed from given (g1, g2) """ req = {'g1': float, 'g2': float} kwargs, safe = GetAllParams(config, base, req=req) #print(base['obj_num'],'Generate from G1G2: kwargs = ',kwargs) return galsim.Shear(**kwargs), safe
def _GenerateFromEta1Eta2(config, base, value_type): """Return a Shear constructed from given (eta1, eta2) """ req = {'eta1': float, 'eta2': float} kwargs, safe = GetAllParams(config, base, req=req) #print(base['obj_num'],'Generate from Eta1Eta2: kwargs = ',kwargs) return galsim.Shear(**kwargs), safe
def _GenerateFromEtaBeta(param, param_name, base, value_type): """@brief Return a Shear constructed from given (eta, beta) """ req = {'eta': float, 'beta': galsim.Angle} kwargs, safe = GetAllParams(param, param_name, base, req=req) #print base['obj_num'],'Generate from EtaBeta: kwargs = ',kwargs return galsim.Shear(**kwargs), safe
def _GenerateFromQBeta(config, base, value_type): """Return a Shear constructed from given (q, beta) """ req = {'q': float, 'beta': galsim.Angle} kwargs, safe = GetAllParams(config, base, req=req) #print(base['obj_num'],'Generate from QBeta: kwargs = ',kwargs) return galsim.Shear(**kwargs), safe
def _GenerateFromG1G2(param, param_name, base, value_type): """@brief Return a Shear constructed from given (g1, g2) """ req = {'g1': float, 'g2': float} kwargs, safe = GetAllParams(param, param_name, base, req=req) #print 'Generate from G1G2: kwargs = ',kwargs return galsim.Shear(**kwargs), safe
def test_gsparams(): """Test withGSParams with some non-default gsparams """ obj = galsim.Exponential(half_light_radius=1.7) gsp = galsim.GSParams(folding_threshold=1.e-4, maxk_threshold=1.e-4, maximum_fft_size=1.e4) gsp2 = galsim.GSParams(folding_threshold=1.e-2, maxk_threshold=1.e-2) tr = obj.shear(g1=0.2, g2=0.3) jac = galsim.Shear(g1=0.2, g2=0.3).getMatrix() tr1 = tr.withGSParams(gsp) assert tr.gsparams == galsim.GSParams() assert tr1.gsparams == gsp assert tr1.original.gsparams == gsp tr2 = galsim.Transformation(obj.withGSParams(gsp), jac=jac) tr3 = galsim.Transformation(galsim.Exponential(half_light_radius=1.7, gsparams=gsp), jac=jac) tr4 = galsim.Transform(obj, jac=jac, gsparams=gsp) assert tr != tr1 assert tr1 == tr2 assert tr1 == tr3 assert tr1 == tr4 print('stepk = ',tr.stepk, tr1.stepk) assert tr1.stepk < tr.stepk print('maxk = ',tr.maxk, tr1.maxk) assert tr1.maxk > tr.maxk tr5 = galsim.Transform(obj, jac=jac, gsparams=gsp, propagate_gsparams=False) assert tr5 != tr4 assert tr5.gsparams == gsp assert tr5.original.gsparams == galsim.GSParams() tr6 = tr5.withGSParams(gsp2) assert tr6 != tr5 assert tr6.gsparams == gsp2 assert tr6.original.gsparams == galsim.GSParams()
def test_smallshear(): """Test the application of a small shear to a Gaussian SBProfile against a known result. """ import time t1 = time.time() e1 = 0.02 e2 = 0.02 myShear = galsim.Shear(e1=e1, e2=e2) savedImg = galsim.fits.read(os.path.join(imgdir, "gauss_smallshear.fits")) dx = 0.2 myImg = galsim.ImageF(savedImg.bounds, scale=dx) myImg.setCenter(0, 0) gauss = galsim.Gaussian(flux=1, sigma=1) gauss2 = gauss.shear(myShear) gauss2.drawImage(myImg, scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg="Using GSObject shear disagrees with expected result") # Check with default_params gauss = galsim.Gaussian(flux=1, sigma=1, gsparams=default_params) gauss = gauss.shear(myShear) gauss.drawImage(myImg, scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg= "Using GSObject shear with default_params disagrees with expected result" ) gauss = galsim.Gaussian(flux=1, sigma=1, gsparams=galsim.GSParams()) gauss = gauss.shear(myShear) gauss.drawImage(myImg, scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg= "Using GSObject shear with GSParams() disagrees with expected result") # Test photon shooting. do_shoot(gauss, myImg, "sheared Gaussian") # Test kvalues do_kvalue(gauss, myImg, "sheared Gaussian") # Check picklability do_pickle( gauss.SBProfile, lambda x: (x.getJac().tolist(), x.getOffset(), x.getFluxScaling())) do_pickle(gauss, lambda x: x.drawImage()) do_pickle(gauss) do_pickle(gauss.SBProfile) t2 = time.time() print 'time for %s = %.2f' % (funcname(), t2 - t1)
def __init__(self, *args): # arg checking: require either a CppShapeData, or nothing if len(args) > 1: raise TypeError("Too many arguments to initialize ShapeData!") elif len(args) == 1: if not isinstance(args[0], _galsim._CppShapeData): raise TypeError( "Argument to initialize ShapeData must be a _CppShapeData!" ) self.image_bounds = args[0].image_bounds self.moments_status = args[0].moments_status self.observed_shape = galsim.Shear(args[0].observed_shape) self.moments_sigma = args[0].moments_sigma self.moments_amp = args[0].moments_amp self.moments_centroid = args[0].moments_centroid self.moments_rho4 = args[0].moments_rho4 self.moments_n_iter = args[0].moments_n_iter self.correction_status = args[0].correction_status self.corrected_e1 = args[0].corrected_e1 self.corrected_e2 = args[0].corrected_e2 self.corrected_g1 = args[0].corrected_g1 self.corrected_g2 = args[0].corrected_g2 self.meas_type = args[0].meas_type self.corrected_shape_err = args[0].corrected_shape_err self.correction_method = args[0].correction_method self.resolution_factor = args[0].resolution_factor self.error_message = args[0].error_message else: self.image_bounds = _galsim.BoundsD() self.moments_status = -1 self.observed_shape = galsim.Shear() self.moments_sigma = -1.0 self.moments_amp = -1.0 self.moments_centroid = _galsim.PositionD() self.moments_rho4 = -1.0 self.moments_n_iter = 0 self.correction_status = -1 self.corrected_e1 = -10. self.corrected_e2 = -10. self.corrected_g1 = -10. self.corrected_g2 = -10. self.meas_type = "None" self.corrected_shape_err = -1.0 self.correction_method = "None" self.resolution_factor = -1.0 self.error_message = ""
def test_shear_methods(): """Test that the most commonly-used methods of the Shear class give the expected results.""" import time t1 = time.time() for ind in range(n_shear): s = galsim.Shear(e1=e1[ind], e2=e2[ind]) # check negation s2 = -s all_shear_vals(s2, ind, mult_val = -1.0) # check addition s2 = s + s exp_e1, exp_e2 = add_distortions(s.e1, s.e2, s.e1, s.e2) np.testing.assert_array_almost_equal([s2.e1, s2.e2], [exp_e1, exp_e2], decimal=decimal, err_msg = "Failed to properly add distortions") # check subtraction s3 = s - s2 exp_e1, exp_e2 = add_distortions(s.e1, s.e2, -1.0*s2.e1, -1.0*s2.e2) np.testing.assert_array_almost_equal([s3.e1, s3.e2], [exp_e1, exp_e2], decimal=decimal, err_msg = "Failed to properly subtract distortions") # check += savee1 = s.e1 savee2 = s.e2 s += s2 exp_e1, exp_e2 = add_distortions(savee1, savee2, s2.e1, s2.e2) np.testing.assert_array_almost_equal([s.e1, s.e2], [exp_e1, exp_e2], decimal=decimal, err_msg = "Failed to properly += distortions") # check -= savee1 = s.e1 savee2 = s.e2 s -= s exp_e1, exp_e2 = add_distortions(savee1, savee2, -1.0*savee1, -1.0*savee2) np.testing.assert_array_almost_equal([s.e1, s.e2], [exp_e1, exp_e2], decimal=decimal, err_msg = "Failed to properly -= distortions") # check == s = galsim.Shear(g1 = g1[ind], g2 = g2[ind]) s2 = galsim.Shear(g1 = g1[ind], g2 = g2[ind]) np.testing.assert_equal(s == s2, True, err_msg = "Failed to check for equality") # check != np.testing.assert_equal(s != s2, False, err_msg = "Failed to check for equality") # note: we don't have to check all the getWhatever methods because they were implicitly checked # in test_shear_initialization, where we checked the values directly t2 = time.time() print 'time for %s = %.2f'%(funcname(),t2-t1)
def test_shearest_precomputed(): """Test that we can recover shears the same as before the code was put into GalSim.""" # loop over real galaxies for index in range(len(file_indices)): # define input filenames img_file = os.path.join(img_dir, gal_file_prefix + str(file_indices[index]) + img_suff) psf_file = os.path.join(img_dir, psf_file_prefix + str(file_indices[index]) + img_suff) # read in information for objects and expected results img = galsim.fits.read(img_file) img -= 1000 psf = galsim.fits.read(psf_file) psf -= 1000 # get PSF moments for later tests psf_mom = psf.FindAdaptiveMom() # loop over methods for method_index in range(len(correction_methods)): # call PSF correction result = galsim.hsm.EstimateShear( img, psf, sky_var = sky_var[index], shear_est = correction_methods[method_index], guess_centroid = galsim.PositionD(x_centroid[index], y_centroid[index])) # compare results with precomputed print(result.meas_type, correction_methods[method_index]) if result.meas_type == 'e': np.testing.assert_almost_equal( result.corrected_e1, e1_expected[index][method_index], decimal = decimal_shape) np.testing.assert_almost_equal( result.corrected_e2, e2_expected[index][method_index], decimal = decimal_shape) else: gval = np.sqrt(result.corrected_g1**2 + result.corrected_g2**2) if gval <= 1.0: s = galsim.Shear(g1=result.corrected_g1, g2=result.corrected_g2) np.testing.assert_almost_equal( s.e1, e1_expected[index][method_index], decimal = decimal_shape) np.testing.assert_almost_equal( s.e2, e2_expected[index][method_index], decimal = decimal_shape) # also compare resolutions and estimated errors np.testing.assert_almost_equal( result.resolution_factor, resolution_expected[index][method_index], decimal = decimal_shape) np.testing.assert_almost_equal( result.corrected_shape_err, sigma_e_expected[index][method_index], decimal = decimal_shape) # Also check that the PSF properties that come out of EstimateShear are the same as # what we would get from measuring directly. np.testing.assert_almost_equal( psf_mom.moments_sigma, result.psf_sigma, decimal=decimal_shape, err_msg = "PSF sizes from FindAdaptiveMom vs. EstimateShear disagree") np.testing.assert_almost_equal( psf_mom.observed_shape.e1, result.psf_shape.e1, decimal=decimal_shape, err_msg = "PSF e1 from FindAdaptiveMom vs. EstimateShear disagree") np.testing.assert_almost_equal( psf_mom.observed_shape.e2, result.psf_shape.e2, decimal=decimal_shape, err_msg = "PSF e2 from FindAdaptiveMom vs. EstimateShear disagree") first = False
def test_shearconvolve(): """Test the convolution of a sheared Gaussian and a Box profile against a known result. """ e1 = 0.04 e2 = 0.0 myShear = galsim.Shear(e1=e1, e2=e2) dx = 0.2 savedImg = galsim.fits.read( os.path.join(imgdir, "gauss_smallshear_convolve_box.fits")) myImg = galsim.ImageF(savedImg.bounds, scale=dx) myImg.setCenter(0, 0) psf = galsim.Gaussian(flux=1, sigma=1).shear(e1=e1, e2=e2) pixel = galsim.Pixel(scale=dx, flux=1.) conv = galsim.Convolve([psf, pixel]) conv.drawImage(myImg, scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg= "Using GSObject Convolve([psf,pixel]) disagrees with expected result") # Check with default_params conv = galsim.Convolve([psf, pixel], gsparams=default_params) conv.drawImage(myImg, scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg= "Using GSObject Convolve([psf,pixel]) with default_params disagrees with " "expected result") conv = galsim.Convolve([psf, pixel], gsparams=galsim.GSParams()) conv.drawImage(myImg, scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg= "Using GSObject Convolve([psf,pixel]) with GSParams() disagrees with " "expected result") # Other ways to do the convolution: conv = galsim.Convolve(psf, pixel) conv.drawImage(myImg, scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg= "Using GSObject Convolve(psf,pixel) disagrees with expected result") check_basic(conv, "sheared Gaussian * Pixel") # Test photon shooting. with assert_warns(galsim.GalSimWarning): do_shoot(conv, myImg, "sheared Gaussian * Pixel")
def run_hsm(self): """Use HSM to measure moments of star image. This usually isn't called directly. The results are accessible as star.hsm, which caches the results, so repeated access is efficient. :returns: (flux, cenu, cenv, sigma, g1, g2, flag) """ image, weight, image_pos = self.data.getImage() # Note that FindAdaptiveMom only respects the weight function in a binary sense. # I.e., pixels with non-zero weight will be included in the moment measurement, those # with weight=0.0 will be excluded. mom = image.FindAdaptiveMom(weight=weight, strict=False) sigma = mom.moments_sigma shape = mom.observed_shape # These are in pixel coordinates. Need to convert to world coords. jac = image.wcs.jacobian(image_pos=image_pos) scale, shear, theta, flip = jac.getDecomposition() # Fix sigma sigma *= scale # Fix shear. First the flip, if any. if flip: shape = galsim.Shear(g1=-shape.g1, g2=shape.g2) # Next the rotation shape = galsim.Shear(g=shape.g, beta=shape.beta + theta) # Finally the shear shape = shear + shape flux = mom.moments_amp localwcs = image.wcs.local(image_pos) center = localwcs.toWorld( mom.moments_centroid) - localwcs.toWorld(image_pos) # Do a few sanity checks and flag likely bad fits. flag = mom.moments_status if flag != 0: flag = 1 if flux < 0: flag |= 2 if center.x**2 + center.y**2 > 1: flag |= 4 return flux, center.x, center.y, sigma, shape.g1, shape.g2, flag
def construct_analytic_profile(self, res, fittype, truth=None): if fittype in sersic_indices.keys(): n = sersic_indices[fittype] elif fittype=="bord": n = 1 + res["is_bulge"].astype(int)*3 fittype = {4: "bulge", 1: "disc"} [n] if truth is not None: e1 = truth["intrinsic_e1"] e2 = truth["intrinsic_e2"] g1 = truth["true_g1"] g2 = truth["true_g2"] hlr = truth["hlr"] flux = truth["flux"] if (g1==-9999.) or (g2==-9999.): return None else: e1 = res["e1"][0,0] e2 = res["e2"][0,0] g1 = 0 g2 = 0 flux = res["%s_flux"%fittype][0,0] gal=galsim.Sersic(n=n,half_light_radius=hlr) gal=gal.withFlux(flux) e1 += g1 e2 += g2 if e1>1: e1=1 if e1<-1: e1=-1 if e2>1: e2=1 if e2<-1: e2=-1 try: shear = galsim.Shear(g1=e1, g2=e2) print "applying shear g1=%1.3f,g2=%1.3f"%(e1,e2) except: print "ERROR: unphysical shear" shear= galsim.Shear(g1=0, g2=0) gal.shear(shear) return gal
def test_gaussian(): """Test various ways to build a Gaussian """ config = { 'gal1' : { 'type' : 'Gaussian' , 'sigma' : 2 }, 'gal2' : { 'type' : 'Gaussian' , 'fwhm' : 2, 'flux' : 100 }, 'gal3' : { 'type' : 'Gaussian' , 'half_light_radius' : 2, 'flux' : 1.e6, 'ellip' : { 'type' : 'QBeta' , 'q' : 0.6, 'beta' : 0.39 * galsim.radians } }, 'gal4' : { 'type' : 'Gaussian' , 'sigma' : 1, 'flux' : 50, 'dilate' : 3, 'ellip' : galsim.Shear(e1=0.3), 'rotate' : 12 * galsim.degrees, 'magnify' : 1.03, 'shear' : galsim.Shear(g1=0.03, g2=-0.05), 'shift' : { 'type' : 'XY', 'x' : 0.7, 'y' : -1.2 } }, 'gal5' : { 'type' : 'Gaussian' , 'sigma' : 1.5, 'flux' : 72.5, 'rotate' : -34. * galsim.degrees, 'magnify' : 0.93, 'shear' : galsim.Shear(g1=-0.15, g2=0.2) }, } gal1a = galsim.config.BuildGSObject(config, 'gal1')[0] gal1b = galsim.Gaussian(sigma = 2) gsobject_compare(gal1a, gal1b) gal2a = galsim.config.BuildGSObject(config, 'gal2')[0] gal2b = galsim.Gaussian(fwhm = 2, flux = 100) gsobject_compare(gal2a, gal2b) gal3a = galsim.config.BuildGSObject(config, 'gal3')[0] gal3b = galsim.Gaussian(half_light_radius = 2, flux = 1.e6) gal3b = gal3b.shear(q = 0.6, beta = 0.39 * galsim.radians) gsobject_compare(gal3a, gal3b) gal4a = galsim.config.BuildGSObject(config, 'gal4')[0] gal4b = galsim.Gaussian(sigma = 1, flux = 50) gal4b = gal4b.dilate(3).shear(e1 = 0.3).rotate(12 * galsim.degrees).magnify(1.03) gal4b = gal4b.shear(g1 = 0.03, g2 = -0.05).shift(dx = 0.7, dy = -1.2) gsobject_compare(gal4a, gal4b) gal5a = galsim.config.BuildGSObject(config, 'gal5')[0] gal5b = galsim.Gaussian(sigma = 1.5, flux = 72.5) gal5b = gal5b.rotate(-34 * galsim.degrees).lens(-0.15, 0.2, 0.93) gsobject_compare(gal5a, gal5b)
def test_shape_g2e_galsim(g1, g2): e1, e2 = g1g2_to_e1e2(g1, g2) e1 = np.atleast_1d(e1) e2 = np.atleast_1d(e2) g1 = np.atleast_1d(g1) g2 = np.atleast_1d(g2) for _e1, _e2, _g1, _g2 in zip(e1, e2, g1, g2): s = galsim.Shear(g1=_g1, g2=_g2) assert np.allclose([s.e1, s.e2], [_e1, _e2])
def test_shape_g2eta_galsim(g1, g2): eta1, eta2 = g1g2_to_eta1eta2(g1, g2) eta1 = np.atleast_1d(eta1) eta2 = np.atleast_1d(eta2) g1 = np.atleast_1d(g1) g2 = np.atleast_1d(g2) for _eta1, _eta2, _g1, _g2 in zip(eta1, eta2, g1, g2): s = galsim.Shear(g1=_g1, g2=_g2) assert np.allclose([s.eta1, s.eta2], [_eta1, _eta2])
def test_shape_eta2g_galsim(eta1, eta2): g1, g2 = eta1eta2_to_g1g2(eta1, eta2) eta1 = np.atleast_1d(eta1) eta2 = np.atleast_1d(eta2) g1 = np.atleast_1d(g1) g2 = np.atleast_1d(g2) for _eta1, _eta2, _g1, _g2 in zip(eta1, eta2, g1, g2): s = galsim.Shear(eta1=_eta1, eta2=_eta2) assert np.allclose([s.g1, s.g2], [_g1, _g2])
def test_shape_e2eta_galsim(e1, e2): eta1, eta2 = e1e2_to_eta1eta2(e1, e2) eta1 = np.atleast_1d(eta1) eta2 = np.atleast_1d(eta2) e1 = np.atleast_1d(e1) e2 = np.atleast_1d(e2) for _eta1, _eta2, _e1, _e2 in zip(eta1, eta2, e1, e2): s = galsim.Shear(e1=_e1, e2=_e2) assert np.allclose([s.eta1, s.eta2], [_eta1, _eta2])
def test_shape_e2g_galsim(e1, e2): g1, g2 = e1e2_to_g1g2(e1, e2) e1 = np.atleast_1d(e1) e2 = np.atleast_1d(e2) g1 = np.atleast_1d(g1) g2 = np.atleast_1d(g2) for _e1, _e2, _g1, _g2 in zip(e1, e2, g1, g2): s = galsim.Shear(e1=_e1, e2=_e2) assert np.allclose([s.g1, s.g2], [_g1, _g2])
def _GenerateFromNFWHaloShear(param, param_name, base, value_type): """@brief Return a shear calculated from an NFWHalo object. """ if 'sky_pos' not in base: raise ValueError("NFWHaloShear requested, but no position defined.") pos = base['sky_pos'] #print 'nfw pos = ',pos if 'gal' not in base or 'redshift' not in base['gal']: raise ValueError( "NFWHaloShear requested, but no gal.redshift defined.") redshift = GetCurrentValue(base['gal'], 'redshift') if 'nfw_halo' not in base: raise ValueError( "NFWHaloShear requested, but no input.nfw_halo defined.") opt = {'num': int} kwargs = GetAllParams(param, param_name, base, opt=opt)[0] num = kwargs.get('num', 0) if num < 0: raise ValueError( "Invalid num < 0 supplied for NFWHalowShear: num = %d" % num) if num >= len(base['nfw_halo']): raise ValueError( "Invalid num supplied for NFWHaloShear (too large): num = %d" % num) nfw_halo = base['nfw_halo'][num] #print 'NFWHaloShear: pos = ',pos,' z = ',redshift try: g1, g2 = nfw_halo.getShear(pos, redshift) #print 'g1,g2 = ',g1,g2 shear = galsim.Shear(g1=g1, g2=g2) except Exception as e: #print e import warnings warnings.warn( "Warning: NFWHalo shear is invalid -- probably strong lensing! " + "Using shear = 0.") shear = galsim.Shear(g1=0, g2=0) #print 'shear = ',shear return shear, False
def test_largeshear(): """Test the application of a large shear to a Sersic SBProfile against a known result. """ import time t1 = time.time() e1 = 0.0 e2 = 0.5 myShear = galsim.Shear(e1=e1, e2=e2) # test the SBProfile version using applyShear savedImg = galsim.fits.read(os.path.join(imgdir, "sersic_largeshear.fits")) dx = 0.2 myImg = galsim.ImageF(savedImg.bounds, scale=dx) myImg.setCenter(0,0) devauc = galsim.DeVaucouleurs(flux=1, half_light_radius=1) devauc.applyShear(myShear) devauc.draw(myImg,scale=dx, normalization="surface brightness", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg="Using GSObject applyShear disagrees with expected result") devauc = galsim.DeVaucouleurs(flux=1, half_light_radius=1) devauc2 = devauc.createSheared(myShear) devauc2.draw(myImg,scale=dx, normalization="surface brightness", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg="Using GSObject createSheared disagrees with expected result") # Check with default_params devauc = galsim.DeVaucouleurs(flux=1, half_light_radius=1, gsparams=default_params) devauc.applyShear(myShear) devauc.draw(myImg,scale=dx, normalization="surface brightness", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg="Using GSObject applyShear with default_params disagrees with expected result") devauc = galsim.DeVaucouleurs(flux=1, half_light_radius=1, gsparams=galsim.GSParams()) devauc.applyShear(myShear) devauc.draw(myImg,scale=dx, normalization="surface brightness", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg="Using GSObject applyShear with GSParams() disagrees with expected result") # Test photon shooting. # Convolve with a small gaussian to smooth out the central peak. devauc2 = galsim.Convolve(devauc, galsim.Gaussian(sigma=0.3)) do_shoot(devauc2,myImg,"sheared DeVauc") # Test kvalues. # Testing a sheared devauc requires a rather large fft. What we really care about # testing though is the accuracy of the applyShear function. So just shear a Gaussian here. gauss = galsim.Gaussian(sigma=2.3) gauss.applyShear(myShear) do_kvalue(gauss, "sheared Gaussian") t2 = time.time() print 'time for %s = %.2f'%(funcname(),t2-t1)
def get_lsst_para(cat): """Create parametric bulge+disk galaxy for input parametrs form catsim. @cat: catsim row containig catsim galaxy parametrs """ # HST scale scale = 0.2 b_r, b_g = a_b2re_e(cat['a_b'], cat['b_b']) d_r, d_g = a_b2re_e(cat['a_d'], cat['b_d']) b_s = galsim.Shear(g=b_g, beta=cat['pa_bulge'] * galsim.degrees) d_s = galsim.Shear(g=d_g, beta=cat['pa_disk'] * galsim.degrees) input_p = cg_fn.LSST_Args(scale=scale, redshift=cat['redshift'], bulge_n=cat['disk_n'], disk_n=cat['bulge_n'], disk_HLR=d_r, bulge_HLR=b_r, bulge_e=[b_s.e1, b_s.e2], disk_e=[d_s.e1, d_s.e2], bulge_frac=0.5) input_p.T_flux = 2 gal, PSF, con = get_gal(input_p, cat) return gal
def test_pixel(): """Test various ways to build a Pixel """ config = { 'gal1' : { 'type' : 'Pixel' , 'scale' : 2 }, 'gal2' : { 'type' : 'Pixel' , 'scale' : 1.7, 'flux' : 100 }, 'gal3' : { 'type' : 'Box' , 'width' : 2, 'height' : 2.1, 'flux' : 1.e6, 'ellip' : { 'type' : 'QBeta' , 'q' : 0.6, 'beta' : 0.39 * galsim.radians } }, 'gal4' : { 'type' : 'Box' , 'width' : 1, 'height' : 1.2, 'flux' : 50, 'dilate' : 3, 'ellip' : galsim.Shear(e1=0.3), 'rotate' : 12 * galsim.degrees, 'magnify' : 1.03, 'shear' : galsim.Shear(g1=0.03, g2=-0.05), 'shift' : { 'type' : 'XY', 'x' : 0.7, 'y' : -1.2 } }, } gal1a = galsim.config.BuildGSObject(config, 'gal1')[0] gal1b = galsim.Pixel(scale = 2) gsobject_compare(gal1a, gal1b) gal2a = galsim.config.BuildGSObject(config, 'gal2')[0] gal2b = galsim.Pixel(scale = 1.7, flux = 100) gsobject_compare(gal2a, gal2b) # The config stuff emits a warning about the rectangular pixel. # We suppress that here, since we're doing it on purpose. import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") gal3a = galsim.config.BuildGSObject(config, 'gal3')[0] gal3b = galsim.Box(width = 2, height = 2.1, flux = 1.e6) gal3b = gal3b.shear(q = 0.6, beta = 0.39 * galsim.radians) # Drawing sheared Pixel without convolution doesn't work, so we need to # do the extra convolution by a Gaussian here gsobject_compare(gal3a, gal3b, conv=galsim.Gaussian(0.1)) gal4a = galsim.config.BuildGSObject(config, 'gal4')[0] gal4b = galsim.Box(width = 1, height = 1.2, flux = 50) gal4b = gal4b.dilate(3).shear(e1 = 0.3).rotate(12 * galsim.degrees).magnify(1.03) gal4b = gal4b.shear(g1 = 0.03, g2 = -0.05).shift(dx = 0.7, dy = -1.2) gsobject_compare(gal4a, gal4b, conv=galsim.Gaussian(0.1))
def test_realspace_shearconvolve(): """Test the real-space convolution of a sheared Gaussian and a Box SBProfile against a known result. """ import time t1 = time.time() e1 = 0.04 e2 = 0.0 myShear = galsim.Shear(e1=e1, e2=e2) dx = 0.2 saved_img = galsim.fits.read(os.path.join(imgdir, "gauss_smallshear_convolve_box.fits")) img = galsim.ImageF(saved_img.bounds, scale=dx) img.setCenter(0,0) psf = galsim.Gaussian(flux=1, sigma=1) psf = psf.shear(e1=e1,e2=e2) pixel = galsim.Pixel(scale=dx, flux=1.) conv = galsim.Convolve([psf,pixel],real_space=True) conv.drawImage(img,scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( img.array, saved_img.array, 5, err_msg="Using GSObject Convolve([psf,pixel]) disagrees with expected result") # Check with default_params conv = galsim.Convolve([psf,pixel],real_space=True,gsparams=default_params) conv.drawImage(img,scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( img.array, saved_img.array, 5, err_msg="Using GSObject Convolve([psf,pixel]) with default_params disagrees with " "expected result") conv = galsim.Convolve([psf,pixel],real_space=True,gsparams=galsim.GSParams()) conv.drawImage(img,scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( img.array, saved_img.array, 5, err_msg="Using GSObject Convolve([psf,pixel]) with GSParams() disagrees with " "expected result") # Other ways to do the convolution: conv = galsim.Convolve(psf,pixel,real_space=True) conv.drawImage(img,scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( img.array, saved_img.array, 5, err_msg="Using GSObject Convolve(psf,pixel) disagrees with expected result") # The real-space convolution algorithm is not (trivially) independent of the order of # the two things being convolved. So check the opposite order. conv = galsim.Convolve([pixel,psf],real_space=True) conv.drawImage(img,scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( img.array, saved_img.array, 5, err_msg="Using GSObject Convolve([pixel,psf]) disagrees with expected result") t2 = time.time() print 'time for %s = %.2f'%(funcname(),t2-t1)
def test_smallshear(): """Test the application of a small shear to a Gaussian profile against a known result. """ e1 = 0.02 e2 = 0.02 myShear = galsim.Shear(e1=e1, e2=e2) savedImg = galsim.fits.read(os.path.join(imgdir, "gauss_smallshear.fits")) dx = 0.2 myImg = galsim.ImageF(savedImg.bounds, scale=dx) myImg.setCenter(0,0) gauss = galsim.Gaussian(flux=1, sigma=1) gauss2 = gauss.shear(myShear) gauss2.drawImage(myImg,scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg="Using GSObject shear disagrees with expected result") np.testing.assert_almost_equal( myImg.array.max(), gauss2.max_sb, 5, err_msg="sheared profile max_sb did not match maximum pixel value") # Check with default_params gauss = galsim.Gaussian(flux=1, sigma=1, gsparams=default_params) gauss = gauss.shear(myShear) gauss.drawImage(myImg,scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg="Using GSObject shear with default_params disagrees with expected result") gauss = galsim.Gaussian(flux=1, sigma=1, gsparams=galsim.GSParams()) gauss = gauss._shear(myShear) gauss.drawImage(myImg,scale=dx, method="sb", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg="Using GSObject shear with GSParams() disagrees with expected result") check_basic(gauss, "sheared Gaussian") # Test photon shooting. do_shoot(gauss,myImg,"sheared Gaussian") # Test kvalues do_kvalue(gauss,myImg,"sheared Gaussian") # Check picklability do_pickle(gauss, lambda x: x.drawImage()) do_pickle(gauss) # Check really small shear (This mostly tests a branch in the str function.) do_pickle(galsim.Gaussian(sigma=2.3).shear(g1=1.e-13,g2=0)) assert_raises(TypeError, gauss.shear) assert_raises(TypeError, gauss.shear, 0.3) assert_raises(TypeError, gauss.shear, 0.1, 0.3) assert_raises(TypeError, gauss.shear, g1=0.1, g2=0.1, invalid=0.3) assert_raises(TypeError, gauss.shear, myShear, invalid=0.3)
def test_smallshear(): """Test the application of a small shear to a Gaussian SBProfile against a known result. """ import time t1 = time.time() e1 = 0.02 e2 = 0.02 myShear = galsim.Shear(e1=e1, e2=e2) # test the SBProfile version using applyShear savedImg = galsim.fits.read(os.path.join(imgdir, "gauss_smallshear.fits")) myImg = galsim.ImageF(savedImg.bounds, scale=0.2) mySBP = galsim.SBGaussian(flux=1, sigma=1) mySBP.applyShear(myShear._shear) mySBP.draw(myImg.view()) printval(myImg, savedImg) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg="Small-shear Gaussian profile disagrees with expected result") # Repeat with the GSObject version of this: gauss = galsim.Gaussian(flux=1, sigma=1) gauss.applyShear(myShear) gauss.draw(myImg,dx=0.2, normalization="surface brightness", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg="Using GSObject applyShear disagrees with expected result") gauss = galsim.Gaussian(flux=1, sigma=1) gauss2 = gauss.createSheared(myShear) gauss2.draw(myImg,dx=0.2, normalization="surface brightness", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg="Using GSObject createSheared disagrees with expected result") # Check with default_params gauss = galsim.Gaussian(flux=1, sigma=1, gsparams=default_params) gauss.applyShear(myShear) gauss.draw(myImg,dx=0.2, normalization="surface brightness", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg="Using GSObject applyShear with default_params disagrees with expected result") gauss = galsim.Gaussian(flux=1, sigma=1, gsparams=galsim.GSParams()) gauss.applyShear(myShear) gauss.draw(myImg,dx=0.2, normalization="surface brightness", use_true_center=False) np.testing.assert_array_almost_equal( myImg.array, savedImg.array, 5, err_msg="Using GSObject applyShear with GSParams() disagrees with expected result") # Test photon shooting. do_shoot(gauss,myImg,"sheared Gaussian") # Test kvalues do_kvalue(gauss,"sheared Gaussian") t2 = time.time() print 'time for %s = %.2f'%(funcname(),t2-t1)
def print_results(f, g1_list, g2_list, sigma_list, test_answer, first_index=0): """Print the results to a file specified either via outfile kwarg or chosen using test_answer.image_type. If you intend to use this with plot_test_interpolants.py, and you change the column order, make sure to change it in plot_test_interpolants.py as well--it's hard-coded both places! """ if test_answer.shear[0]!=0 or test_answer.shear[1]!=0: # If there's an applied shear, compute the value of the expected shear test_shear = galsim.Shear(g1=test_answer.shear[0], g2=test_answer.shear[1]) expected_shears = [test_shear+galsim.Shear(g1=tg[0], g2=tg[1]) if (tg[0]!=-10 and tg[1]!=-10) else -10 for tg in zip(g1_list,g2_list)] expected_g1 = [e.getG1() if isinstance(e,galsim.Shear) else -10 for e in expected_shears] expected_g2 = [e.getG2() if isinstance(e,galsim.Shear) else -10 for e in expected_shears] expected_size = numpy.sqrt(test_answer.magnification)*numpy.array(sigma_list) elif test_answer.angle!=0: # If there's an applied rotation, rotate the truth shears as well sin2theta = numpy.sin(2.*numpy.pi/180.*test_answer.angle) cos2theta = numpy.cos(2.*numpy.pi/180.*test_answer.angle) expected_g1 = g1_list*cos2theta-g2_list*sin2theta expected_g2 = g1_list*sin2theta+g2_list*cos2theta expected_size = sigma_list else: expected_g1 = g1_list expected_g2 = g2_list expected_size = sigma_list # Since we didn't want to cycle through 'default', but it's a used option, add it to the list tinterpolant_list = interpolant_list+['default'] # Write everything out as a number, so it can be loaded into python with numpy.loadtxt # (which yells at you if you use strings) for i in range(len(test_answer.g1obs)): f.write(str(i+first_index)+' '+str(tinterpolant_list.index(test_answer.x_interpolant))+' '+ str(tinterpolant_list.index(test_answer.k_interpolant))+' '+ str(test_answer.padding)+' '+str(test_answer.shear[0])+' '+ str(test_answer.shear[1])+' '+ str(test_answer.magnification)+' '+str(test_answer.angle)+' '+ str(test_answer.shiftx)+' '+str(test_answer.shifty)+' '+ str(g1_list[i])+' '+str(expected_g1[i])+' '+str(test_answer.g1obs[i]-expected_g1[i])+' '+ str(g2_list[i])+' '+str(expected_g2[i])+' '+str(test_answer.g2obs[i]-expected_g2[i])+' '+ str(sigma_list[i])+' '+str(expected_size[i])+' '+ str((test_answer.sigmaobs[i]-expected_size[i])/expected_size[i])+'\n')
def main(): z_offs = z_min**(z_powerlaw_slope+1) n_total_galaxies = int(extent_degrees**2*3600*n_galaxies_per_sq_arcmin) halo = galsim.NFWHalo(mass=1.E14, conc=4., redshift=z_lens) for i in range(n_total_galaxies): ra,dec = extent_degrees*numpy.random.rand(2)-0.5*extent_degrees z = ((z_powerlaw_slope+1)*numpy.random.random()+z_offs)**(1./(z_powerlaw_slope+1)) if use_noise: g_int = make_safe_shear(numpy.random.normal(scale=0.35,size=2)) g_int = galsim.Shear(g1=g_int[0], g2=g_int[1]) else: g_int = galsim.Shear(g1=0,g2=0) if z>z_lens: g_induced = halo.getShear(galsim.PositionD(3600*ra,3600*dec),z) # g_induced = (min(g_induced[0],1),min(g_induced[0],1)) g_induced = galsim.Shear(g1=g_induced[0],g2=g_induced[1]) g_total = g_induced+g_int else: g_total = g_int print i, ra, dec, z, g_total.getG1(), g_total.getG2()