def set_admom(self): c=self['filternum'] self['skysig'] = self.psfield['skysig'][0,c] Tguess = admom.sigma2mom(self.psfield['psf_sigma1'][0,c]) self['amguess'] = Tguess/2. row,col=self['cen'] self.amres = admom.admom(self.psf, row, col, sky=0., guess=self['amguess'], sigsky=self['skysig'])
def process_image_cat(imfile, catfile, get_meta=False): """ Process the input image and cat files. If get_meta=True, a tuple of (array, meta) is returned. meta is a dictionary with 'shiftmax' and 'nsub' """ im, ivar_im, cat = read_image_cat(imfile, catfile) col=cat['x_image']-1 row=cat['y_image']-1 sky=cat['background'] colint=col.astype('i4') rowint=row.astype('i4') ivar = ivar_im[rowint,colint] sigsky = zeros(cat.size) w=where1(ivar > 0) wbad=where1(ivar <= 0) if w.size > 0: sigsky[w] = 1.0/sqrt(ivar[w]) print >>stderr,'running admom' tmp=admom.admom(im, row[w], col[w], sky=sky[w], sigsky=sigsky[w]) print >>stderr,'copying to array output' a,h=as_array(cat, w, wbad, tmp) if get_meta: out=(a,h) else: out=a else: out=None return out
def test_admom(covar, ntrial=1, s2n=35.0): print 'covar:',covar,'s2n:',s2n import admom nsub=1 ngauss=1 dims=array([21,21]) cen=(dims-1)/2. det = covar[0]*covar[2] - covar[1]**2 counts=1.0 sky=0.0 # weighted admom s2n of about 35 #skysig=0.004 skysig = counts/s2n/sqrt(4*pi*det) s2n_exp = counts/skysig/sqrt(4*pi*det) im0 = model_image('gauss', dims, cen,covar, counts=counts, nsub=nsub) allmeans = zeros( (ntrial, 3) ) for j in xrange(ntrial): im = im0 + skysig*randn(dims[0]*dims[1]).reshape(dims) guess = (covar[1]+covar[2])/2 + 0.1*(random(2)-0.5) res = admom.admom(im, cen[0], cen[1], sigsky=skysig, nsub=nsub) #print s2n_exp,res['s2n'] allmeans[j,:] = [res['Irr'],res['Irc'],res['Icc']] return allmeans
def make_psf_stats(self): """ Either generate moments from inputs or read an SDSS PSF """ psfmodel = self['psfmodel'] if isinstance(psfmodel, (str,unicode)): # generate a random orientation theta = 360.0*numpy.random.random() Irr, Irc, Icc = admom.ellip2mom(self['Tpsf'], e=self['psf_ellip'], theta=theta) self['Irr_psf'] = Irr self['Irc_psf'] = Irc self['Icc_psf'] = Icc self.psf = None else: # this is a psf generator. We assume the psf has the center at # the image middle, is normalized psf = psfmodel.next() cen = [(psf.shape[0]-1)/2., (psf.shape[1]-1)/2.] out = admom.admom(psf, cen[0], cen[1]) if out['whyflag'] != 0: raise RuntimeError("failure measuring psf admom") self.psf=psf self['Irr_psf'] = out['Irr'] self['Irc_psf'] = out['Irc'] self['Icc_psf'] = out['Icc'] self['Tpsf'] = out['Irr'] + out['Icc']
def _stat_image_psf(self): import admom # measure the moments using admom if they were # not sent psf = self['psfmodel'] self.psf = psf # note we assume the center is the middle. cen = [(psf.shape[0]-1)/2., (psf.shape[1]-1)/2.] self['psfcen'] = cen if self['Irr_psf'] is None: import admom if (psf.shape[0] % 2) == 0 or (psf.shape[1] % 2) == 0: raise ValueError("psf must be odd size in each dim") out = admom.admom(psf, cen[0], cen[1]) if out['whyflag'] != 0: raise ValueError("Failed to characterize PSF") self['Irr_psf'] = out['Irr'] self['Irc_psf'] = out['Irc'] self['Icc_psf'] = out['Icc'] if self.verbose: print("Input PSF model stats:") print(" Irr_psf:",self['Irr_psf']) print(" Irc_psf:",self['Irc_psf']) print(" Icc_psf:",self['Icc_psf']) print(" dims: ",self.psf.shape)
def _measure_psf_admom(self): import admom cen=array(self.psf_stack.shape)/2. ares = admom.admom(self.psf_stack, cen[0], cen[1], sigsky=sqrt(self.psf_skyvar), guess=4.0, nsub=self.nsub) self.psf_ares=ares pprint.pprint(self.psf_ares)
def _process_star(self, iobj, icutout): from gmix_image import GMixEMBoot import admom defres=({'whyflag':ZERO_WEIGHT_PIXELS}, {'flags':ZERO_WEIGHT_PIXELS}, {'flags':ZERO_WEIGHT_PIXELS}, numpy.zeros(len(WIDTHS)) - 9999, -9999.0) im,ivar,cen_guess=self._get_star_data(iobj,icutout) if im is None: return defres max_pixel = im.max() widths = measure_image_width(im, WIDTHS) cen1_guess=cen_guess sig1_guess=sqrt(2) ares = admom.admom(im, cen_guess[0], cen_guess[1], guess=sig1_guess) gm1=GMixEMBoot(im, 1, cen1_guess, sigma_guess=sig1_guess) res1=gm1.get_result() if res1['flags'] == 0: #print cen_guess #print res1['pars'] sig2_guess=sqrt( (res1['pars'][3] + res1['pars'][5])/2. ) cen2_guess=[res1['pars'][1], res1['pars'][2] ] else: sig2_guess=sig1_guess cen2_guess=cen1_guess gm2=GMixEMBoot(im, 2, cen2_guess, sigma_guess=sig2_guess) res2=gm2.get_result() if False and res2['flags'] != 0: import images images.multiview(im) resp=raw_input('hit enter (q to quit): ') if resp.lower() == 'q': stop return ares,res1,res2,widths,max_pixel
def do_psf_admom(self): out = admom.admom(self.psf, self.psf_row, self.psf_col, sky=0, guess=self.guess_psf) self['psfstats'] = out if self.verbose: print("psf stats:") pprint(out)
def add_psf_stats(self): self['cen_psf'] = self.psf_gmix.get_cen() self['cen_psf_uw'] = self['cen_psf'] res = admom.admom(self.psf,self['cen_psf'][0],self['cen_psf'][1], guess=self['Ttrue_psf']/2.) cov_admom = array([res['Irr'],res['Irc'],res['Icc']]) cen_admom = array([res['wrow'], res['wcol']]) self['cov_psf_admom'] = cov_admom self['cen_psf_admom'] = cen_admom self['a4_psf'] = res['a4']
def add_image_stats(self): self['cen_uw'] = self.obj0_gmix.get_cen() res = admom.admom(self.image, self['cen'][0],self['cen'][1], guess=self['Ttrue']/2.) cov_admom = array([res['Irr'],res['Irc'],res['Icc']]) cen_admom = array([res['wrow'], res['wcol']]) self['cov_admom'] = cov_admom self['cen_admom'] = cen_admom self['a4'] = res['a4'] self['e1_admom'] = res['e1'] self['e2_admom'] = res['e2']
def _run_admom(self): import admom ntry = self.maxtry_admom for i in xrange(ntry): ares = admom.admom( self.image, self.cen_guess[0], self.cen_guess[1], sigsky=sqrt(1 / self.ivar), guess=2.0, nsub=1 ) if ares["whyflag"] == 0: break if i == (ntry - 1): self.ares = None else: self.ares = ares
def do_regauss(self): self['rgstats'] = None if 'imstats' not in self or 'psfstats' not in self: raise ValueError("run admom on image and psf first") if self['imstats']['whyflag'] != 0: if self.verbose: print("admom failed, cannot run regauss") return self.make_f0() if self.f0 == None: self['rgstats'] = {'f0flags':2**0} return self.make_epsilon() self.make_f0conv() self.iprime = self.image - self.f0conv if self.debug: import images images.compare_images(self.image, self.iprime, label1='original', label2='minus f0conv') k=raw_input('hit a key (q to quit): ') if k=='q': stop guess = (self['imstats']['Irr'] + self['imstats']['Irr'])/2 wrow = self['imstats']['wrow'] wcol = self['imstats']['wcol'] out = admom.admom(self.iprime, wrow, wcol, sky=0.0, sigsky=self.sigsky, guess=guess) out['f0flags'] = 0 self['rgstats'] = out if self.verbose: print("rgstats:") pprint(self['rgstats'])
def run_admom(self, image, cen_guess, T_guess): """ Run adaptive moments on the image """ from nsim.sim import srandu ntry = self["ntry"] for i in xrange(ntry): amres = admom.admom(image, cen_guess[0], cen_guess[1], guess=0.5 * T_guess, sigsky=self.skysig) if amres["whyflag"] == 0: break else: T_guess = T_guess * (1.0 + 0.05 * srandu()) cen_guess = cen_guess + 0.1 * srandu(2) amres["ntry"] = i + 1 return amres
def _run_admom(self, image, skyvar): import admom cen_guess=numpy.array(image.shape,dtype='f8')/2. n=0 while n < 100: ares = admom.admom(image, cen_guess[0]+0.1*srandu(), cen_guess[1]+0.1*srandu(), sigsky=sqrt(skyvar), guess=4.0*(1+0.1*srandu()), nsub=self.nsub) if ares['whyflag'] == 0: break n += 1 return ares
def _run_admom(self, image, ivar, cen, Tguess): import admom ntry=10 for i in xrange(ntry): ares = admom.admom(image, cen[0], cen[1], sigsky=sqrt(1/ivar), guess=Tguess/2, nsub=1) if ares['whyflag']==0: break if i==(ntry-1): raise ValueError("admom failed %s times" % ntry) return ares
def _run_admom(self, im, row, col, guess0, skysig): i = 0 res = None while i < self["admom_ntry"]: guess = guess0 * (1.0 + 0.05 * srandu()) row = row + 0.4 * srandu() col = col + 0.4 * srandu() tmp = admom.admom(im, row, col, sigsky=skysig, guess=guess) if tmp["whyflag"] == 0: res = tmp break i += 1 return res
def test_fit_exp_simple(s2n=1.e5): import biggles import admom import fimage numpy.random.seed(35) e = 0.2 theta = 23.7 e1,e2 = etheta2e1e2(e,theta) sigma=4.0 sigma_psf = sigma/2. fwhm_psf = 2.35*sigma_psf print >>stderr,"e:",e,"e1:",e1,"e2:",e2 print '-'*70 print 'sigma:',sigma T = 2*sigma**2 cov = ellip2mom(T, e=e, theta=theta) ci=fimage.convolved.ConvolverTurbulence({'model':'exp', 'cov':cov}, {'model':'turb','psf_fwhm':fwhm_psf}) cin=fimage.convolved.NoisyConvolvedImage(ci, s2n, 1.e6) cen=cin['cen'] gmpsf=gmix_image.gmix_em.GMixEMBoot(cin.psf, 2, cen) gmix_psf=gmpsf.get_gmix() ares = admom.admom(cin.image,cen[0],cen[1],guess=T/2,nsub=16) verbose=False skysig=cin['skysig'] gf=gmix_fit.GMixFitSimple(cin.image, 1./skysig**2, gmix_psf, 'exp', ares) res=gf.get_result() print 'chi2/deg:',res['chi2per'] model = gf.get_model() images.compare_images(cin.image,model)
def find_weight_admom(self, imin, **kw): """ iterate to get the weighted center and return the weight """ import admom im=imin.copy() dims=im.shape guess=1.0/self.sigma2 ccen=util.get_canonical_kcenter(dims) rows,cols=util.make_rows_cols(dims, cen=ccen) r2=rows**2 + cols**2 w=numpy.where(r2 > self.kmax2) im[w] = 0.0 ares=admom.admom(im, ccen[0], ccen[1], guess=guess, maxiter=200) res={ 'flags':ares['whyflag'], 'numiter':ares['numiter'], 'Tguess':2*guess, } if res['flags']==0: cen=[ares['wrow'], ares['wcol']] weight, wrows, wcols=self.get_weight(dims, cen) res.update( { 'cen':cen, 'ccen':ccen, 'T':ares['Irr']+ares['Icc'], 'weight':weight, 'rows':wrows, 'cols':wcols, }) return res
def test_err(n=10000, skysig=0.1): """ this shows that the uncer is per component """ import ngmix import admom from numpy.random import randn T = 4.0 sigma = numpy.sqrt(T / 2.0) dim = int(round(2.0 * 5.0 * sigma)) dims = [dim] * 2 cen = [(dim - 1.0) / 2.0] * 2 pars = [cen[0], cen[1], 0.0, 0.0, T, 100.0] gm = ngmix.gmix.GMixModel(pars, "gauss") im0 = gm.make_image(dims, nsub=16.0) e1s = numpy.zeros(n) e2s = numpy.zeros(n) errs = numpy.zeros(n) for i in xrange(n): if (i % 100) == 0: print "%d/%d" % (i + 1, n) im = im0 + skysig * randn(im0.size).reshape(im0.shape) res = admom.admom(im, cen[0], cen[1], guess=T / 2.0, sigsky=skysig) e1s[i] = res["e1"] e2s[i] = res["e2"] errs[i] = res["uncer"] print "mean err: ", errs.mean() print "e1 shape std:", e1s.std() print "e2 shape std:", e2s.std()
def find_weight_admom(self, imin, **kw): """ iterate to get the weighted center and return the weight """ import admom im = imin.copy() dims = im.shape guess = 1.0 / self.sigma2 ccen = util.get_canonical_kcenter(dims) rows, cols = util.make_rows_cols(dims, cen=ccen) r2 = rows**2 + cols**2 w = numpy.where(r2 > self.kmax2) im[w] = 0.0 ares = admom.admom(im, ccen[0], ccen[1], guess=guess, maxiter=200) res = { 'flags': ares['whyflag'], 'numiter': ares['numiter'], 'Tguess': 2 * guess, } if res['flags'] == 0: cen = [ares['wrow'], ares['wcol']] weight, wrows, wcols = self.get_weight(dims, cen) res.update({ 'cen': cen, 'ccen': ccen, 'T': ares['Irr'] + ares['Icc'], 'weight': weight, 'rows': wrows, 'cols': wcols, }) return res
def add_image_stats(self): mom_uw = stat.fmom(self.image) cov_uw = mom_uw['cov'] cen_uw = mom_uw['cen'] res = admom.admom(self.image, cen_uw[0], cen_uw[1], guess=(cov_uw[0]+cov_uw[2])/2) if res['whyflag'] != 0: raise ValueError("admom failure: '%s'" % res['whystr']) cov_admom = array([res['Irr'],res['Irc'],res['Icc']]) cen_admom = array([res['wrow'], res['wcol']]) self['cov_uw'] = cov_uw self['cen_uw'] = cen_uw self['cov_admom'] = cov_admom self['cen_admom'] = cen_admom self['a4'] = res['a4'] self['e1_admom'] = res['e1'] self['e2_admom'] = res['e2']
def add_psf_stats(self): mom = stat.fmom(self.psf) cov_uw = mom['cov'] cen_uw = mom['cen'] res = admom.admom(self.psf,cen_uw[0],cen_uw[1], guess=(cov_uw[0]+cov_uw[2])/2) cov_admom = array([res['Irr'],res['Irc'],res['Icc']]) cen_admom = array([res['wrow'], res['wcol']]) self.psfpars['cov_uw'] = cov_uw self.psfpars['cen_uw'] = cen_uw self.psfpars['cov_admom'] = cov_admom self.psfpars['cen_admom'] = cen_admom self['cov_psf_uw'] = cov_uw self['cen_psf_uw'] = cen_uw self['cov_psf_admom'] = cov_admom self['cen_psf_admom'] = cen_admom self['a4_psf'] = res['a4']
def do_admom(self): ''' row, col: row,column in image. Note numpy arrays are indexed [row,col] sky: sky value at the location of row,col sigsky: sky variance at row,col ''' out = admom.admom(self.image, self.row, self.col, sky=0.0, sigsky=self.sigsky, guess=self.guess) self['imstats'] = out if self.verbose: print("image stats:") pprint(out)
def add_image0_stats(self): """ mom = stat.fmom(self.image0) cov_meas = mom['cov'] cen_meas = mom['cen'] res = admom.admom(self.image0, cen_meas[0],cen_meas[1], guess=(cov_meas[0]+cov_meas[1])/2 ) cov_meas_admom = array([res['Irr'],res['Irc'],res['Icc']]) """ pars = self.objpars mom = stat.fmom(self.image0) cov_uw = mom['cov'] cen_uw = mom['cen'] res = admom.admom(self.image0, cen_uw[0],cen_uw[1], guess=(cov_uw[0]+cov_uw[2])/2) cov_admom = array([res['Irr'],res['Irc'],res['Icc']]) cen_admom = array([res['wrow'], res['wcol']]) pars['cov_uw'] = cov_uw pars['cen_uw'] = cen_uw pars['cov_admom'] = cov_admom pars['cen_admom'] = cen_admom self['cov_image0_uw'] = cov_uw self['cen_image0_uw'] = cen_uw e1_uw = (cov_uw[2]-cov_uw[0])/(cov_uw[2]+cov_uw[0]) e2_uw = 2*cov_uw[1]/(cov_uw[2]+cov_uw[0]) self['e1_image0_uw'] = e1_uw self['e2_image0_uw'] = e2_uw self['e_image0_uw'] = sqrt(e1_uw**2 + e2_uw**2)
def test_fit_1gauss_galsim(ellip=0.2, s2n=10000): import images import galsim import admom numpy.random.seed(35) #sigma = 1.4 sigma = 1 T=2*sigma**2 e = 0.2 theta=23.7 e1,e2 = etheta2e1e2(e,theta) fimage_cov = ellip2mom(T, e=e, theta=theta) print 'e: ',e print 'e1:',e1 print 'e2:',e2 pixel_scale = 1. nsig=5 dim = int(nsig*T) if (dim % 2) == 0: dim += 1 dims=array([dim,dim]) cen=(dims-1)/2 pix = galsim.Pixel(xw=pixel_scale, yw=pixel_scale) gobj = galsim.Gaussian(sigma=sigma) gobj.applyDistortion(galsim.Ellipse(e1=e1,e2=e2)) gcobj = galsim.Convolve([gobj,pix]) im0 = galsim.ImageD(int(dims[1]),int(dims[0])) gcobj.draw(image=im0, dx=pixel_scale) images.multiview(im0.array) galsim_nsub=16 ares = admom.admom(im0.array,cen[0],cen[1],guess=T/2,nsub=galsim_nsub) print 'galsim sigma:',sqrt( (ares['Irr']+ares['Icc'])/2 ) print 'galsim admom e1:',ares['e1'] print 'galsim admom e2:',ares['e2'] print 'galsim center:',ares['row'],ares['col'] fnsub=16 fim0 = model_image('gauss',dims,cen,fimage_cov,nsub=fnsub) fares = admom.admom(fim0,cen[0],cen[1],guess=T/2,nsub=fnsub) print 'fimage sigma:',sqrt( (fares['Irr']+fares['Icc'])/2 ) print 'fimage admom e1:',fares['e1'] print 'fimage admom e2:',fares['e2'] print 'fimage center:',fares['row'],fares['col'] return theta=23.7*numpy.pi/180. print >>stderr,'ellip:',ellip pars=array([cen[0],cen[1],eta,theta,1.,T]) print >>stderr,'pars' gmix = gmix_fit.pars2gmix_coellip_pick(pars,ptype='eta') nsub=1 im0=gmix2image_em(gmix,dims,nsub=nsub) im,skysig = fimage.add_noise(im0, s2n,check=True) images.multiview(im,title='nsub: %d' % nsub) p0=pars.copy() p0[0] += 1*(randu()-0.5) # cen0 p0[1] += 1*(randu()-0.5) # cen1 p0[2] += 0.2*(randu()-0.5) # eta p0[3] += 0.5*(randu()-0.5) # theta radians p0[4] += 0.1*(randu()-0.5) # p p0[5] += 1*(randu()-0.5) # T print_pars(pars,front='pars: ') print_pars(p0, front='guess: ') gf=gmix_fit.GMixFitCoellip(im, p0, ptype='eta',verbose=True) print 'numiter:',gf.numiter print_pars(gf.popt, front='popt: ') print_pars(gf.perr, front='perr: ') images.imprint(gf.pcov)
def test_turb(ngauss=2, Tfrac=False): import pprint import fimage import admom from fimage.transform import rebin import images from .gmix_fit import print_pars counts=1. fwhm=3.3 dims=array([20,20]) #fwhm=10. #dims=array([60,60]) s2n_psf=1.e9 print 'making image' expand_fac=5 psfexp=fimage.pixmodel.ogrid_turb_psf(dims*expand_fac,fwhm*expand_fac, counts=counts) psf0=rebin(psfexp, expand_fac) psf,skysig=fimage.noise.add_noise_admom(psf0, s2n_psf) psfres = admom.admom(psf, dims[0]/2., dims[1]/2., sigsky=skysig, guess=4., nsub=1) """ psfpars={'model':'turb','psf_fwhm':fwhm} objpars={'model':'exp','cov':[2.0,0.0,2.0]} s2n_obj=200. ci_nonoise = fimage.convolved.ConvolverTurbulence(objpars,psfpars) ci=fimage.convolved.NoisyConvolvedImage(ci_nonoise, s2n_obj, s2n_psf, s2n_method='admom') print ci['cen_uw'] print ci['cov_uw'] print 'running admom' counts=ci.psf.sum() psf=ci.psf, skysig=ci['skysig_psf'] psfres = admom.admom(ci.psf, ci['cen_uw'][0], ci['cen_uw'][1], sigsky=ci['skysig_psf'], guess=4., nsub=1) """ pprint.pprint(psfres) if psfres['whyflag'] != 0: raise ValueError("found admom error: %s" % admom.wrappers.flagmap[psfres['whyflag']]) print 'making prior/guess' npars=2*ngauss+4 prior=zeros(npars) width=zeros(npars) + 1000 prior[0]=psfres['row'] prior[1]=psfres['col'] prior[2]=psfres['e1'] prior[3]=psfres['e2'] Tpsf=psfres['Irr']+psfres['Icc'] if Tfrac: if ngauss==3: model='coellip-Tfrac' Tmax = Tpsf*8.3 Tfrac1 = 1.7/8.3 Tfrac2 = 0.8/8.3 prior[4] = Tmax prior[5] = Tfrac1 prior[6] = Tfrac2 prior[7] = 0.08*counts prior[8] = 0.38*counts prior[9] = 0.53*counts else: raise ValueError("Do Tfrac ngauss==2") else: model='coellip' if ngauss==3: Texamp=array([0.46,5.95,2.52]) pexamp=array([0.1,0.7,0.22]) Tfrac=Texamp/Texamp.sum() pfrac=pexamp/pexamp.sum() prior[4:4+3] = Tpsf*Tfrac prior[7:7+3] = counts*pfrac else: prior[4] = Tpsf/3.0 prior[5] = Tpsf/3.0 prior[6] = counts/3. prior[7] = counts/3. # randomize prior[0] += 0.01*srandu() prior[1] += 0.01*srandu() e1start=prior[2] e2start=prior[3] prior[2:2+2] += 0.02*srandu(2) prior[4:npars] = prior[4:npars]*(1+0.05*srandu(2*ngauss)) print_pars(prior) print 'doing fit' gm = gmix_image.GMixFitCoellip(psf, skysig, prior,width, model=model, Tpositive=True) print_pars( gm.get_pars() ) gmix=gm.get_gmix() print 'gmix' pprint.pprint(gmix) #print 'Tpsf:',Tpsf moms=fimage.fmom(psf0) print 'uw T:',moms['cov'][0]+moms['cov'][2] #print 'unweighted T:',ci['cov_uw'][0]+ci['cov_uw'][1] print 'T:',gmix.get_T() model=gm.get_model() images.compare_images(psf,model)
def test_fit_dev_e1e2(ngauss=4, s2n=1.e5): import biggles import admom import fimage numpy.random.seed(35) ptype='e1e2' e = 0.2 theta = 23.7 e1,e2 = etheta2e1e2(e,theta) print >>stderr,"e:",e,"e1:",e1,"e2:",e2 nsig=15 #nsig=7 npars=2*ngauss+4 nsigma_vals=20 f='test-opt-dev-bysigma' f += '-s2n%d' % s2n f += '.rec' pngf=f.replace('.rec','.png') if not os.path.exists(f): data=numpy.zeros(nsigma_vals,dtype=[('sigma','f8'),('pars','f8',npars)]) #sigvals = numpy.linspace(1.5,5.0,nsigma_vals) sigvals = numpy.linspace(3.,5.0,nsigma_vals) #sigvals=array([3.0]) for isigma,sigma in enumerate(sigvals): print '-'*70 print 'sigma:',sigma T = 2*sigma**2 cov = ellip2mom(T, e=e, theta=theta) dim = int(2*nsig*sigma) if (dim % 2) == 0: dim += 1 dims=array([dim,dim]) cen=(dims-1)/2. im0 = model_image('dev',dims,cen,cov,nsub=16) im,skysig = fimage.add_noise(im0, s2n, check=True) dim = int(2*nsig*sigma) if (dim % 2) == 0: dim += 1 dims=array([dim,dim]) cen=(dims-1)/2. ares = admom.admom(im0,cen[0],cen[1],guess=T/2,nsub=16) Tadmom=ares['Irr'] + ares['Icc'] if ngauss == 4: Tmax = Tadmom*100 # 0.02620127 0.09348825 0.23987656 0.63958437 p0 = array([cen[0], cen[1], e1, e2, 0.026, 0.093, 0.24, 0.64, Tmax, Tmax*0.18, Tmax*0.04, Tmax*0.0027]) else: p0 = array([cen[0], cen[1], e1, e2, 1./ngauss, 1./ngauss, 1./ngauss, Tadmom*4.9, Tadmom*0.82, Tadmom*0.18]) print_pars(p0, front='guess: ') verbose=False gf=gmix_fit.GMixFitCoellip(im, p0, ptype=ptype, verbose=verbose) chi2per = gf.get_chi2per(gf.popt,skysig) print 'numiter:',gf.numiter print_pars(gf.popt, front='popt: ') if gf.perr is not None: print_pars(gf.perr, front='perr: ') print 'chi2/deg:',chi2per if gf.flags != 0: gmix_image.printflags('fit',gf.flags) raise RuntimeError("failed") data['sigma'][isigma] = sigma data['pars'][isigma,:] = gf.popt tvals = gf.popt[4+ngauss:] tmax=tvals.max() print 't ratios:',tvals/tmax print 'p values:',gf.popt[4:4+ngauss] print 'T vals/Tadmom:',tvals/Tadmom # plot the last one gmix = gmix_fit.pars2gmix_coellip_pick(gf.popt,ptype=ptype) model = gmix2image_em(gmix,im.shape) images.compare_images(im,model) else: data=eu.io.read(f) biggles.configure('fontsize_min', 1.0) biggles.configure('linewidth',1.0) # frame only nrows=3 ncols=4 tab=biggles.Table(nrows,ncols) for par in xrange(npars): plt=biggles.FramedPlot() plt.add(biggles.Curve(data['sigma'],data['pars'][:,par])) plt.add(biggles.Points(data['sigma'],data['pars'][:,par], type='filled circle')) plt.xlabel = r'$\sigma$' plt.ylabel = 'p%d' % par tab[par//ncols,par%ncols] = plt tab.show() tab.write_img(1024,1024,pngf)
def test_fit_dev_eta_bysigma(): """ Round object as a function of sigma """ import admom import biggles from fimage import model_image, ellip2mom numpy.random.seed(35) ngauss=4 nsig=15 npars=2*ngauss+4 nsigma_vals=20 e=0.3 eta = ellip2eta(e) theta=23.7 print >>stderr,'ellip:',e print >>stderr,'eta:',eta print >>stderr,'theta:',theta*pi/180. f='test-opt-dev-bysigma.rec' pngf=f.replace('.rec','.png') if not os.path.exists(f): data=numpy.zeros(nsigma_vals,dtype=[('sigma','f8'),('pars','f8',npars)]) #sigvals = numpy.linspace(1.5,5.0,nsigma_vals) #sigvals = numpy.linspace(3.,5.0,nsigma_vals) sigvals=array([7.0]) for isigma,sigma in enumerate(sigvals): print '-'*70 print 'sigma:',sigma T = 2*sigma**2 dim = int(2*nsig*sigma) if (dim % 2) == 0: dim += 1 dims=array([dim,dim]) cen=(dims-1)/2. cov=ellip2mom(T, e=e, theta=theta) im = model_image('dev',dims,cen,cov,nsub=16) #images.multiview(im) ares = admom.admom(im,cen[0],cen[1],guess=T/2,nsub=16) if ares['whyflag'] != 0: raise ValueError("admom failed") Tadmom = ares['Irr']+ares['Icc'] print >>stderr,'admom sigma:',sqrt(Tadmom/2) print >>stderr,'admom T:',Tadmom print >>stderr,'admom e:',sqrt(ares['e1']**2 + ares['e2']**2) print >>stderr,'T input:',T #Tuse = Tadmom Tuse = T p0 = array([cen[0], cen[1], eta, theta*pi/180., 0.22, 0.35, 0.25, 0.15, Tuse*0.15, Tuse*0.5, Tuse*2.0, Tuse*5.0]) #0.18450384 2.09205287 10.31125635 67.13233512 print_pars(p0, front='guess: ') gf=gmix_fit.GMixFitCoellip(im, p0, ptype='eta',verbose=True) flags = gf.flags print 'numiter:',gf.numiter print_pars(gf.popt, front='popt: ') #for i in xrange(len(gf.popt)): # print '%.6g' % gf.popt[i] if gf.flags != 0: raise RuntimeError("failed") print >>stderr,'T relative to T uw:',gf.popt[4+ngauss:]/T print >>stderr,'T relative to T admom:',gf.popt[4+ngauss:]/Tadmom data['sigma'][isigma] = sigma data['pars'][isigma,:] = gf.popt # plot the last one gmix = gmix_fit.pars2gmix_coellip_eta(gf.popt) model = gmix2image_em(gmix,im.shape) images.compare_images(im,model) else: data=eu.io.read(f) biggles.configure('fontsize_min', 1.0) biggles.configure('linewidth',1.0) # frame only nrows=3 ncols=4 tab=biggles.Table(nrows,ncols) for par in xrange(npars): plt=biggles.FramedPlot() plt.add(biggles.Curve(data['sigma'],data['pars'][:,par])) plt.add(biggles.Points(data['sigma'],data['pars'][:,par], type='filled circle')) plt.xlabel = r'$\sigma$' plt.ylabel = 'p%d' % par tab[par//ncols,par%ncols] = plt tab.show() tab.write_img(1024,1024,pngf)
def add_noise_admom(im, s2n, check=False): """ Add noise to a convolved image based on requested S/N. This will be the adaptive moments S/N so is gaussian weighted. This is *not* appropriate for all profiles, and is in fact very poor for some. parameters ---------- im: numpy array The image s2n: The requested S/N check: bool If True, print out the measured S/N outputs ------- image, skysig A tuple with the image and error per pixel. """ import admom from .statistics import fmom from .conversions import mom2sigma moms = fmom(im) cen = moms['cen'] cov = moms['cov'] T = cov[0] + cov[2] sigma = mom2sigma(T) shape = im.shape row,col=ogrid[0:shape[0], 0:shape[1]] rm = array(row - cen[0], dtype='f8') cm = array(col - cen[1], dtype='f8') radpix = sqrt(rm**2 + cm**2) # sigfac is 4 in admom sigfac = 4.0 step=0.1 w = where(radpix <= sigfac*sigma) npix = w[0].size + w[1].size while npix == 0: sigfac += step w = where(radpix <= sigfac*sigma) npix = w[0].size + w[1].size pix = im[w] wt = sqrt(pix) wsignal = (wt*pix).sum() wsum = wt.sum() skysig = wsignal/sqrt(wsum)/s2n noise_image = \ skysig*randn(im.size).reshape(shape) image = im + noise_image out = admom.admom(image, cen[0], cen[1], guess=T/2., sigsky=skysig) # fix up skysig based on measurement skysig = out['s2n']/s2n*skysig noise_image = skysig*randn(im.size).reshape(shape) image = im + noise_image if check: out = admom.admom(image, cen[0], cen[1], guess=T/2., sigsky=skysig) print >>stderr," target S/N: ",s2n print >>stderr," meas S/N after noise: ",out['s2n'] return image, skysig
def get_s2n_admom(image, cen, skysig): import admom Tguess=2. out = admom.admom(image, cen[0], cen[1], guess=Tguess, sigsky=skysig) return out['s2n']
def _measure_gals_admom(self): import admom nbin=self.im_stacks.size Tpsf=self.psf_ares['Irr'] + self.psf_ares['Icc'] e1p=self.psf_ares['e1'] e2p=self.psf_ares['e2'] a4p=self.psf_ares['a4'] st=zeros(nbin, dtype=[('s2n','f8'), ('e1','f8'), ('e1err','f8'), ('e2','f8'), ('e2err','f8'), ('T','f8'), ('R','f8')]) self._ares_dicts=[] for i in xrange(nbin): print '-'*70 s2n_min=self.im_stacks['s2n_min'][i] s2n_max=self.im_stacks['s2n_max'][i] print 's2n: [%.2f,%.2f]' % (s2n_min,s2n_max) im=self.im_stacks['images'][i,:,:] skysig=sqrt(self.im_stacks['skyvar'][i]) images.multiview(im) cen=array(im.shape)/2. ares = admom.admom(im, cen[0], cen[1], sigsky=skysig, guess=4.0, nsub=self.nsub) T=ares['Irr']+ares['Icc'] corr=admom.correct(T, ares['e1'], ares['e2'],ares['a4'], Tpsf, e1p, e2p, a4p) e1,e2,R,flags=corr sh1=0.5*e1/self.Rshear sh2=0.5*e2/self.Rshear uncer=ares['uncer']/R err=0.16/sqrt(self.im_stacks['nstack'][i]) mess='sh1: %s +/- %s sh2: %s +/- %s R: %s flags: %s' mess=mess % (sh1,err,sh2,err,R,flags) print mess st['s2n'][i] = (s2n_min+s2n_max)/2. st['e1'][i] = e1 st['e1err'][i] = err st['e2'][i] = e2 st['e2err'][i] = err st['R'][i] = R st['T'][i] = T self._ares_dicts.append(ares) self._admom_shear = st