コード例 #1
0
def makeTractor(bands, ra, dec, S, RCFS):
    TI = []
    for i, (run, camcol, field) in enumerate(RCFS):

        for bandname in bands:
            im, inf = st.get_tractor_image(run,
                                           camcol,
                                           field,
                                           bandname,
                                           useMags=True,
                                           roiradecsize=(ra, dec, S))
            #im.dxdy = (fxc - xc, fyc - yc)
            TI.append((im, inf))
            if i == 0 and bandname == 'r':
                wcs = im.getWcs()
                # im,info = TI[bands.index('r')]
                #wcs = im.getWcs()
                # this is a shifted WCS; S,S is the center.
                # rd = wcs.pixelToPosition(None, (S,S))
                # ra,dec = rd.ra,rd.dec
                # print 'RA,Dec', ra,dec
                cd = wcs.cdAtPixel(xc, yc)
                pixscale = np.sqrt(np.abs(np.linalg.det(cd)))
                print('pixscale', pixscale * 3600.)
                extent = pixscale * S

    #for timg,info in TI:
    #	print timg.hashkey()

    sources = st.get_tractor_sources(run, camcol, field, roi=roi, bands=bands)

    print('Sources:')
    for s in sources:
        print(s)
    print()

    print('Tractor images:', TI)

    cftimg, cfsky, cfstd = get_cfht_img(ra, dec, extent)

    # Create fake tractor.Image
    #  psf = NCircularGaussianPSF([0.1], [1.])
    #  sky = timg.sky
    #  print 'SDSS Sky:', timg.sky
    #  photocal = timg.photocal
    #  fakescale = 3
    #  #wcs = ScaledWCS(fakescale, timg.wcs)
    #  #(h,w) = timg.data.shape
    #  #fakedata = np.zeros((h*fakescale, w*fakescale))
    #  # 0.066
    #  # make-wcs.py -r 333.55503 -d 0.36438 -s 0.02 -W 1200 -H 1200 fake-wcs.fits
    #  # # flip parity
    #  # modhead fake-wcs.fits CD1_1 0
    #  # modhead fake-wcs.fits CD1_2 1.666666667e-5
    #  # modhead fake-wcs.fits CD2_1 1.666666667e-5
    #  # modhead fake-wcs.fits CD2_2 0
    #  wcs = FitsWcs(Tan('fake-wcs.fits', 0))
    #  #h,w = 600,600
    #  h,w = 1200,1200
    #  fakescale = 0.396 * w / (0.02 * 3600.)
    #  fakedata = np.zeros((h, w))
    #  # print '0,0', wcs.pixelToPosition(None, (0,0))
    #  # print 'W,0', wcs.pixelToPosition(None, (w,0))
    #  # print '0,H', wcs.pixelToPosition(None, (0,h))
    #  # print 'W,H', wcs.pixelToPosition(None, (w,h))
    #  fakewcs = wcs
    #  fakeimg = Image(data=fakedata, invvar=fakedata, psf=psf,
    #  				wcs=wcs, sky=sky, photocal=photocal, name='Fake')
    #  del psf
    #  del wcs
    #  del photocal

    tims = [cftimg] + [timg for timg, tinf in TI]
    # for tim in tims:
    # 	try:
    # 		print 'Test pickling im', tim.name
    # 		pickle_to_file(tim, 'test.pickle')
    # 	except:
    # 		print 'failed:'
    # 		traceback.print_exc()
    # 		pass
    # for src in sources:
    # 	try:
    # 		print 'Test pickling source', src
    # 		pickle_to_file(src, 'test.pickle')
    # 	except:
    # 		print 'failed:'
    # 		traceback.print_exc()
    # 		pass
    # sys.exit(0)

    tractor = Tractor(tims)
    tractor.addSources(sources)

    skyvals = ([(cfstd, cfsky)] + [(info['skysig'], info['sky'])
                                   for timg, info in TI])
    return tractor, skyvals
コード例 #2
0
    roi = [1850, 1950, 620, 720]
    x0, y0 = roi[0], roi[2]

    # rd1 is near the position of the SDSS-catalog object
    # rd2 is four pixels above.
    rd1 = RaDecPos(225.67954, 11.265948)
    rd2 = RaDecPos(225.67991, 11.265852)

    lvl = logging.INFO
    logging.basicConfig(level=lvl, format='%(message)s', stream=sys.stdout)
    bandname = band

    sdssprefix = '%06i-%s%i-%04i' % (run, bandname, camcol, field)

    timg, info = st.get_tractor_image(run, camcol, field, bandname, roi=roi)
    sources = st.get_tractor_sources(run, camcol, field, bandname, roi=roi)

    wcs = timg.getWcs()
    for source in sources:
        x, y = wcs.positionToPixel(source, source.getPosition())
        print('  (%.2f, %.2f):' % (x + x0, y + y0), source)

    tractor = st.SDSSTractor([timg])
    tractor.addSources(sources)

    lnlorig = tractor.getLogLikelihood()
    zr = np.array([-5., +20.]) * info['skysig']
    save(sdssprefix + '-orig', tractor, zr)

    # find closest source
    mini = -1
コード例 #3
0
ファイル: trample.py プロジェクト: bpartridge/tractor
def main():
	from optparse import OptionParser
	parser = OptionParser(usage=('%prog'))
	parser.add_option('--steps', dest='steps', type=int, help='Number of steps',
					  default=100)
	parser.add_option('--step0', dest='step0', type=int, help='Starting step',
					  default=0)
	parser.add_option('--nomodplot', dest='modplot', action='store_false', default=True)
	opt,args = parser.parse_args()
	


	lvl = logging.INFO
	#lvl = logging.DEBUG
	logging.basicConfig(level=lvl, format='%(message)s', stream=sys.stdout)
	np.seterr(all='warn')
	np.seterr(divide='raise')

	bands = ['r']
	#RCFS = [(2728, 4, 236),]
	#ra,dec = (333.5596, 0.3671)
	#S = 40
	RCFS = [(756, 3, 243),]
	ra,dec = (152.208922638573, -0.202430118237826)
	S = 18


	TI = []
	for i,(run,camcol,field) in enumerate(RCFS):
		for bandname in bands:
			im,inf = st.get_tractor_image(run, camcol, field, bandname,
										  useMags=True,
										  roiradecsize=(ra,dec,S))
			#im.dxdy = (fxc - xc, fyc - yc)
			TI.append((im,inf))
	tims = [im for im,inf in TI]
	skyvals = [(info['skysig'], info['sky']) for timg,info in TI]
	zrs = [np.array([-1.,+6.]) * std + sky for std,sky in skyvals]

	# Grab sources from the LAST RCF
	roi = inf['roi']
	sources = st.get_tractor_sources(run, camcol, field, roi=roi,
									 bands=bands)

	# DevGalaxy
	s0 = sources[0]
	s0.re = 0.01
	s0.brightness.r = 22.
	
	tractor = Tractor(tims)
	tractor.addSources(sources)

	lnp0 = tractor.getLogProb()

	print 'Catalog:'
	print tractor.catalog
	print tractor.catalog.getParams()

	nthreads = 16
	p0 = np.array(tractor.catalog.getParams())
	ndim = len(p0)
	nw = max(50, 2*ndim)
	print 'ndim', ndim
	print 'nw', nw

	sampler = emcee.EnsembleSampler(nw, ndim, tractor,
									threads=nthreads)
									
	im0 = tractor.getImages()[0]
	steps = np.hstack([src.getStepSizes(im0) for src in tractor.catalog])
	#print 'steps', steps
	print 'p0', p0
	pp0 = np.vstack([p0 + 1e-2 * steps * np.random.normal(size=len(steps))
					 for i in range(nw)])

	plt.figure(1, figsize=(6,6))
	#plt.figure(2, figsize=(18,18))
	plt.figure(2, figsize=(12,12))
	plt.figure(3, figsize=(4,4))

	plt.figure(1)
	plt.clf()
	plotpos0 = [0.01, 0.01, 0.98, 0.94]

	alllnp = []
	allp = []

	lnp = None #lnp0
	pp = pp0
	rstate = None
	for step in range(opt.step0, opt.steps):

		pfn = 'trample-%03i.pickle' % step
		if os.path.exists(pfn):
			print 'Unpickling', pfn
			allp,alllnp = unpickle_from_file(pfn)
			lnp = alllnp[-1]
			pp  = allp[-1]
		else:
			print 'Taking step', step
			print 'pp shape', pp.shape
			pp,lnp,rstate = sampler.run_mcmc(pp, 1, lnprob0=lnp, rstate0=rstate)
			print 'lnprobs:', lnp

			for p,x in zip(lnp,pp):
				tractor.setAllSourceParams(x)
				print 'lnp', p
				print tractor.catalog

			#print 'pp shape', pp.shape
			# nw,ndim
			alllnp.append(lnp.copy())
			allp.append(pp.copy())
			pickle_to_file((allp, alllnp), pfn)
		
		plt.clf()
		plt.plot(alllnp, 'k', alpha=0.5)
		plt.axhline(lnp0, color='r', lw=2, alpha=0.5)
		mx = np.max([p.max() for p in alllnp])
		plt.ylim(mx-300, mx+10)
		plt.xlim(0, len(alllnp)-1)
		plt.savefig('lnp.png')

		for i in range(len(tractor.getImages())):
			zr = zrs[i]
			ima = dict(interpolation='nearest', origin='lower',
					   vmin=zr[0], vmax=zr[1], cmap='gray')
			imchi = dict(interpolation='nearest', origin='lower',
						 vmin=-5., vmax=+5., cmap='gray')
			if step == 0:
				tim = tractor.getImage(i)
				data = tim.getImage()

				plt.clf()
				plt.gca().set_position(plotpos0)
				plt.imshow(data, **ima)
				plt.title('Data %s' % tim.name)
				plt.xticks([],[])
				plt.yticks([],[])
				plt.savefig('data%02i.png' % i)

			modsum = None
			#KK = 
			for k in xrange(nw):
				tractor.setAllSourceParams(pp[k,:])
				mod = tractor.getModelImage(i)
				if k == 0:
					modsum = mod
				else:
					modsum += mod

				if step%50 == 0 and opt.modplot:
					print 'mod,chi'
					plt.clf()
					plt.gca().set_position(plotpos0)
					plt.imshow(mod, **ima)
					plt.title('Model')
					plt.xticks([],[])
					plt.yticks([],[])
					plt.savefig('mod%02i-%02i-%03i.png' % (i,step,k))

					chi = tractor.getChiImage(i)
					plt.clf()
					plt.gca().set_position(plotpos0)
					plt.imshow(chi, **imchi)
					plt.title('Chi')
					plt.xticks([],[])
					plt.yticks([],[])
					plt.savefig('chi%02i-%02i-%03i.png' % (i,step,k))

			if step % 10 == 0:
				print 'modbest, chibest'
				ibest = np.argmax(lnp)
				print 'ibest', ibest
				tractor.setAllSourceParams(pp[ibest,:])
				mod = tractor.getModelImage(i)
				plt.clf()
				plt.gca().set_position(plotpos0)
				plt.imshow(mod, **ima)
				plt.title('Best Model')
				plt.xticks([],[])
				plt.yticks([],[])
				plt.savefig('modbest%02i-%02i.png' % (i,step))

				chi = tractor.getChiImage(i)
				plt.clf()
				plt.gca().set_position(plotpos0)
				plt.imshow(chi, **imchi)
				plt.title('Best Chi')
				plt.xticks([],[])
				plt.yticks([],[])
				plt.savefig('chibest%02i-%02i.png' % (i,step))

			if step % 1 == 0:
				print 'modsum'
				plt.clf()
				plt.gca().set_position(plotpos0)
				plt.imshow(modsum/float(nw), **ima)
				plt.title('Model')
				plt.xticks([],[])
				plt.yticks([],[])
				plt.savefig('modsum%02i-%02i.png' % (i,step))


			if step % 1 == 0 and False:
				# Plot models, exaggerating the variance
				# pp shape is (nw,ndim)
				print 'exag'
				p0 = pp.mean(axis=0)
				print 'p0 shape', p0
				for i in range(nw):
					delta = pp[i,:] - p0
					exagg = 10.
					pnew = pp[i,:] + (exagg-1.)*delta
					tractor.setAllSourceParams(pnew)
					modex = tractor.getModelImage(0)
					
					plt.clf()
					plt.gca().set_position(plotpos0)
					plt.imshow(modex, **ima)
					plt.title('Model (exaggerated x %g)' % exagg)
					plt.xticks([],[])
					plt.yticks([],[])
					plt.savefig('modex%02i-%02i.png' % (i,step))



		if step % 50 == 0:
			pnames = tractor.catalog[0].getParamNames()
			print 'Params', pnames
			NP = len(pnames)

			# select objid, ra,raerr,dec,decerr,devmag_r,devmagerr_r,devrad_r,devraderr_r,devphi_r,devab_r,devaberr_r from mydb.mytable_2 where run=756 and camcol=3 and field=243
			#objid,ra,raerr,dec,decerr,devmag_r,devmagerr_r,devrad_r,devraderr_r,devphi_r,devab_r,devaberr_r
			#1237648721218568377,152.208922638573,0.00391166133082899,-0.202430118237826,0.00423603626875907,17.59624,0.005895343,1.081388,0.0371073,26.40831,0.435521,0.01508615


			# DR8
			sdssvals = [ 152.208922638573,-0.202430118237826,17.59624,1.081388,0.435521, 26.40831 * -1. ]
			sdsserrs = [ 0.00391166133082899, 0.00423603626875907,0.005895343,0.0371073, 0.01508615, 0. ]
			# DR7; phi*-1; raErr, decErr are in arcsec, and raErr is err in ra*cos(dec)
			sdssvals7 = [ 152.20891415,-0.20242878,17.60266,1.044212,0.4157184,26.3763*-1.,]
			sdsserrs7 = [ 0.0443575305964374 / 3600., 0.041734802988402 / 3600.,0.006056787,0.03344231,0.0143005, 0.]


			tractor.setAllSourceParams(sdssvals7)
			sdssmod = tractor.getModelImage(0)
			sdsschi = tractor.getChiImage(0)
					
			plt.clf()
			plt.gca().set_position(plotpos0)
			plt.imshow(sdssmod, **ima)
			plt.title('SDSS Model')
			plt.xticks([],[])
			plt.yticks([],[])
			plt.savefig('sdssmod.png')
			plt.clf()
			plt.gca().set_position(plotpos0)
			plt.imshow(sdsschi, **imchi)
			plt.title('SDSS Model Chi')
			plt.xticks([],[])
			plt.yticks([],[])
			plt.savefig('sdsschi.png')


			ra0, dec0 = sdssvals7[:2]
			#152.209, -0.202
			pnames = [#'RA - %.3f (arcsec)' % np.abs(ra0),
					  #'Dec + %.3f (arcsec)' % np.abs(dec0),
				'RA - SDSS (milli-arcsec)',
				'Dec - SDSS (milli-arcsec)',
				'r (mag)',
				'effective radius (arcsec)', 'axis ratio',
				'position angle (deg)']

			nsteps = 20
			ppp = allp[-nsteps:]

			tmn = {}
			tstd = {}
			paris = {}
			
			for i in range(NP):
				pari = np.hstack([p[:,i] for p in ppp])

				mn,std,c =(sdssvals7[i],sdsserrs7[i],'m')
				# in [#(sdssvals[i],sdsserrs[i],'r'),

				if i == 0:
					pari -= ra0
					mn -= ra0
					pari *= 3600. * 1000.
					mn *= 3600. * 1000.
					std *= 3600. * 1000.
				elif i == 1:
					pari -= dec0
					mn -= dec0
					pari *= 3600. * 1000.
					mn *= 3600. * 1000.
					std *= 3600. * 1000.

				paris[i] = pari
				tmn[i] = np.mean(pari)
				tstd[i] = np.std(pari)

				plt.figure(3)
				plt.clf()
				xlo, xhi = min(pari.min(), mn-std), max(pari.max(), mn+std)
				n,b,p1 = plt.hist(pari, 25, ec='none', alpha=0.5)
				plt.hist(pari, 25, histtype='step', ec='b', lw=2)
				xx = np.linspace(xlo, xhi, 100)
				ax = plt.axis()
				dx = b[1]-b[0]
				#yy = np.exp(-0.5 * (xx - mn)**2 / std**2)
				#yy /= sum(yy)
				#yy *= sum(n)*dx / (xx[1]-xx[0])
				#print 'yy', yy
				#plt.plot(xx, yy, 'b-', lw=3, alpha=0.8)
				print 'mn', mn, 'std', std
				#plt.axvline(mn, color='b', lw=3, alpha=0.5)

				#for mn,std,c in [#(sdssvals[i],sdsserrs[i],'r'),
				#				 (sdssvals7[i],sdsserrs7[i],'m')]:
				if std != 0:
					yy = np.exp(-0.5 * (xx - mn)**2 / std**2)
					yy /= sum(yy)
					yy *= sum(n)*dx / (xx[1]-xx[0])
					plt.plot(xx, yy, '-', color=c, lw=3, alpha=0.8)
				print 'sdss', mn, std
				p2 = plt.axvline(mn, color=c, lw=3, alpha=0.8)

				#plt.axis(ax)

				#plt.xlim(min(xx.min(), mn-std), max(xx.max(), mn+std))
				plt.xlim(xlo,xhi)
				plt.xlabel(pnames[i])
				plt.legend((p1[0],p2), ('Tractor', 'SDSS DR7'))
				fn = 'modparam%02i-%02i.png' % (step,i)
				print 'save', fn
				plt.savefig(fn)


			plt.figure(2)
			plt.clf()
			plt.subplots_adjust(left=0.01, right=0.98, bottom=0.03, top=0.98,
								wspace=0.1, hspace=0.1)
			for i in range(NP):
				pari = paris[i]
				for j in range(i, NP):
					parj = paris[j]
					plt.subplot(NP, NP, (i*NP)+j+1)
					mn,std = tmn[i],tstd[i]
					irng = (mn-3*std, mn+3*std)
					mn,std = tmn[j],tstd[j]
					jrng = (mn-3*std, mn+3*std)
					if i == j:
						plt.hist(pari, 25, ec='none', alpha=0.5, range=irng)
						plt.hist(pari, 25, histtype='step', ec='b', lw=1, range=irng)
						plt.xlabel(pnames[i])
					else:
						plt.plot(pari, parj, 'b.', alpha=0.1)
						plt.ylim(*jrng)
						#plt.ylabel(pnames[j])
					#plt.xlabel(pnames[i])
					plt.xticks([])
					plt.yticks([])
					plt.xlim(*irng)
			plt.savefig('modhist%02i.png' % step)
			plt.savefig('modhist%02i.pdf' % step)
			plt.figure(1)
コード例 #4
0
ファイル: debugpool.py プロジェクト: rainwoodman/tractor
        #   img.shape = data.shape
        #   del img.data
        #   del img.invvar
        #   R = super(Tractor2,self).getModelPatchNoCache(img, src)
        #   img.data, img.invvar = data,invvar
    
    

    #run,camcol,field = 7164,4,273
    #band='g'
    run,camcol,field = 2662, 4, 111
    band='i'
    roi=[0,300,0,300]
    im,info = st.get_tractor_image(run, camcol, field, band,
                                   useMags=True, roi=roi)
    sources = st.get_tractor_sources(run, camcol, field, band, roi=roi)
    tractor = Tractor2([im], sources)
    print tractor
    print tractor.getLogProb()
    tractor.freezeParam('images')

    p0 = tractor.getParams()
    tractor.setParams(p0)

    print
    print 'With Debug:'
    tractor.setParams(p0)
    tractor.mp = dmup
    t0 = Time()
    tractor.opt2()
    print 'With Debug:', Time()-t0
コード例 #5
0
import numpy as np

from tractor import *
from tractor import sdss as st
from tractor.cache import *
from astrometry.util.ttime import *
import gc
#gc.set_debug(gc.DEBUG_LEAK)
#gc.enable()

run,camcol,field = 3384, 4, 198
bandname = 'r'

timg,info = st.get_tractor_image(run, camcol, field, bandname, useMags=True)
sources = st.get_tractor_sources(run, camcol, field,bandname, bands=[bandname])

# mags = []
# for i,src in enumerate(sources):
# 	m = getattr(src.getBrightness(), bandname)
# 	mags.append(m)
# J = np.argsort(mags)

#sources = [sources[J[i]] for i in range(10)]

sources = sources[:20]

tractor = Tractor([timg], sources)
tractor.cache = Cache(maxsize=100)

for step in range(10):
コード例 #6
0
ファイル: ugc5459.py プロジェクト: barentsen/tractor
def main():
    run = 2863
    field = 180
    camcol = 4
    x0 = 200 #Field of view for the image
    x1 = 900
    y0 = 400
    y1 = 850
    starx = 200. #Star location
    stary = 300.
    starr = 50. #Star radius

    roi = [x0,x1,y0,y1]
    
    bands=['r','g','i','u','z']
    bandname = 'r'
    flipBands = ['r']

    rerun = 0

    TI = []
    TI.extend([st.get_tractor_image(run, camcol, field, bandname,roi=roi,useMags=True) for bandname in bands])
    sources = st.get_tractor_sources(run, camcol, field,bandname, bands=bands,roi=roi)

    timg,info = TI[0]
    photocal = timg.getPhotoCal()

    wcs = timg.getWcs()
    lvl = logging.DEBUG
    logging.basicConfig(level=lvl,format='%(message)s',stream=sys.stdout)

    tims = [timg for timg,tinf in TI]
    tractor = st.SDSSTractor(tims)
    tractor.addSources(sources)

    zr = np.array([-5.,+5.]) * info['skysig']

    print bands

    ra,dec = 152.041958,53.083472

    r = 200
    itune = 10
    ntune = 5
    prefix = 'ugc5459'

    saveBands('initial-'+prefix, tractor,zr,flipBands,debug=True)

    xtr,ytr = wcs.positionToPixel(RaDecPos(ra,dec))
    
    print xtr,ytr
    bright = None
    lowbright = 1000

    xt = 250. #Moving to the left for better results
    yt = 210.
    for src in sources:
        xs,ys = wcs.positionToPixel(src.getPosition(), src)
        if (xs-xt)**2+(ys-yt)**2 <= r**2:
            if isinstance(src,st.CompositeGalaxy):
                brightE = src.brightnessExp
                brightD = src.brightnessDev
                sumbright = sum([brightE.getMag(bandname)+brightD.getMag(bandname) for bandname in bands])
                if sumbright < lowbright:
                    print("GREATER")
                    lowBrightE = brightE
                    lowBrightD = brightD
                    lowShapeE = src.shapeExp
                    lowShapeD = src.shapeDev
            print "Removed:", src
            print xs,ys
            tractor.removeSource(src)

    saveBands('removed-'+prefix, tractor,zr,flipBands,debug=True)

#    bright = Mags(r=15.,u=15.,g=15.,z=15.,i=15.,order=['r','u','g','z','i'])
#    shape = st.GalaxyShape(re,ab,phi)
#    shape2 = st.GalaxyShape(30.,0.3,45.)
#    print bright
#    print shape
#   print shape2

    CG = st.CompositeGalaxy(RaDecPos(ra,dec),lowBrightE,lowShapeE,lowBrightD,lowShapeD)
    print CG
    tractor.addSource(CG)


    saveBands('added-'+prefix,tractor,zr,flipBands,debug=True)


    for img in tractor.getImages():
        star =  [(x,y) for x in range(img.getWidth()) for y in range(img.getHeight()) if (x-starx)**2+(y-stary)**2 <= starr**2]
        for (x,y) in star:
            img.getInvError()[y][x] = 0


    saveBands('nostar-'+prefix,tractor,zr,flipBands,debug=True)
    for i in range(itune):
        tractor.optimizeCatalogLoop(nsteps=1,srcs=[CG],sky=False)
        tractor.clearCache()
        saveBands('itune-%d-' % (i+1)+prefix,tractor,zr,flipBands,debug=True)

    for i in range(ntune):
        tractor.optimizeCatalogLoop(nsteps=1,sky=True)
        saveBands('ntune-%d-' % (i+1)+prefix,tractor,zr,flipBands,debug=True)
        tractor.clearCache()

    makeflipbook(prefix,flipBands,itune,ntune)
コード例 #7
0
ファイル: ugc5459.py プロジェクト: charlotteaward/tractor-1
def main():
    run = 2863
    field = 180
    camcol = 4
    x0 = 200 #Field of view for the image
    x1 = 900
    y0 = 400
    y1 = 850
    starx = 200. #Star location
    stary = 300.
    starr = 50. #Star radius

    roi = [x0,x1,y0,y1]
    
    bands=['r','g','i','u','z']
    bandname = 'r'
    flipBands = ['r']

    rerun = 0

    TI = []
    TI.extend([st.get_tractor_image(run, camcol, field, bandname,roi=roi,useMags=True) for bandname in bands])
    sources = st.get_tractor_sources(run, camcol, field,bandname, bands=bands,roi=roi)

    timg,info = TI[0]
    photocal = timg.getPhotoCal()

    wcs = timg.getWcs()
    lvl = logging.DEBUG
    logging.basicConfig(level=lvl,format='%(message)s',stream=sys.stdout)

    tims = [timg for timg,tinf in TI]
    tractor = st.SDSSTractor(tims)
    tractor.addSources(sources)

    zr = np.array([-5.,+5.]) * info['skysig']

    print(bands)

    ra,dec = 152.041958,53.083472

    r = 200
    itune = 10
    ntune = 5
    prefix = 'ugc5459'

    saveBands('initial-'+prefix, tractor,zr,flipBands,debug=True)

    xtr,ytr = wcs.positionToPixel(RaDecPos(ra,dec))
    
    print(xtr,ytr)
    bright = None
    lowbright = 1000

    xt = 250. #Moving to the left for better results
    yt = 210.
    for src in sources:
        xs,ys = wcs.positionToPixel(src.getPosition(), src)
        if (xs-xt)**2+(ys-yt)**2 <= r**2:
            if isinstance(src,st.CompositeGalaxy):
                brightE = src.brightnessExp
                brightD = src.brightnessDev
                sumbright = sum([brightE.getMag(bandname)+brightD.getMag(bandname) for bandname in bands])
                if sumbright < lowbright:
                    print("GREATER")
                    lowBrightE = brightE
                    lowBrightD = brightD
                    lowShapeE = src.shapeExp
                    lowShapeD = src.shapeDev
            print("Removed:", src)
            print(xs,ys)
            tractor.removeSource(src)

    saveBands('removed-'+prefix, tractor,zr,flipBands,debug=True)

#    bright = Mags(r=15.,u=15.,g=15.,z=15.,i=15.,order=['r','u','g','z','i'])
#    shape = st.GalaxyShape(re,ab,phi)
#    shape2 = st.GalaxyShape(30.,0.3,45.)
#    print bright
#    print shape
#   print shape2

    CG = st.CompositeGalaxy(RaDecPos(ra,dec),lowBrightE,lowShapeE,lowBrightD,lowShapeD)
    print(CG)
    tractor.addSource(CG)


    saveBands('added-'+prefix,tractor,zr,flipBands,debug=True)


    for img in tractor.getImages():
        star =  [(x,y) for x in range(img.getWidth()) for y in range(img.getHeight()) if (x-starx)**2+(y-stary)**2 <= starr**2]
        for (x,y) in star:
            img.getInvError()[y][x] = 0


    saveBands('nostar-'+prefix,tractor,zr,flipBands,debug=True)
    for i in range(itune):
        tractor.optimizeCatalogLoop(nsteps=1,srcs=[CG],sky=False)
        tractor.clearCache()
        saveBands('itune-%d-' % (i+1)+prefix,tractor,zr,flipBands,debug=True)

    for i in range(ntune):
        tractor.optimizeCatalogLoop(nsteps=1,sky=True)
        saveBands('ntune-%d-' % (i+1)+prefix,tractor,zr,flipBands,debug=True)
        tractor.clearCache()

    makeflipbook(prefix,flipBands,itune,ntune)
コード例 #8
0
ファイル: dsDemo.py プロジェクト: barentsen/tractor
def makeTractor(bands, ra, dec, S, RCFS):
	TI = []
	for i,(run,camcol,field) in enumerate(RCFS):

		for bandname in bands:
			im,inf = st.get_tractor_image(run, camcol, field, bandname,
										  useMags=True,
										  roiradecsize=(ra,dec,S))
			#im.dxdy = (fxc - xc, fyc - yc)
			TI.append((im,inf))
			if i == 0 and bandname == 'r':
				wcs = im.getWcs()
				# im,info = TI[bands.index('r')]
				#wcs = im.getWcs()
				# this is a shifted WCS; S,S is the center.
				# rd = wcs.pixelToPosition(None, (S,S))
				# ra,dec = rd.ra,rd.dec
				# print 'RA,Dec', ra,dec
				cd = wcs.cdAtPixel(xc,yc)
				pixscale = np.sqrt(np.abs(np.linalg.det(cd)))
				print 'pixscale', pixscale * 3600.
				extent = pixscale * S

	#for timg,info in TI:
	#	print timg.hashkey()

	sources = st.get_tractor_sources(run, camcol, field, roi=roi,
									 bands=bands)

	print 'Sources:'
	for s in sources:
		print s
	print

	print 'Tractor images:', TI

	cftimg,cfsky,cfstd = get_cfht_img(ra,dec, extent)

	# Create fake tractor.Image
	#  psf = NCircularGaussianPSF([0.1], [1.])
	#  sky = timg.sky
	#  print 'SDSS Sky:', timg.sky
	#  photocal = timg.photocal
	#  fakescale = 3
	#  #wcs = ScaledWCS(fakescale, timg.wcs)
	#  #(h,w) = timg.data.shape
	#  #fakedata = np.zeros((h*fakescale, w*fakescale))
	#  # 0.066
	#  # make-wcs.py -r 333.55503 -d 0.36438 -s 0.02 -W 1200 -H 1200 fake-wcs.fits
	#  # # flip parity
	#  # modhead fake-wcs.fits CD1_1 0
	#  # modhead fake-wcs.fits CD1_2 1.666666667e-5
	#  # modhead fake-wcs.fits CD2_1 1.666666667e-5
	#  # modhead fake-wcs.fits CD2_2 0
	#  wcs = FitsWcs(Tan('fake-wcs.fits', 0))
	#  #h,w = 600,600
	#  h,w = 1200,1200
	#  fakescale = 0.396 * w / (0.02 * 3600.)
	#  fakedata = np.zeros((h, w))
	#  # print '0,0', wcs.pixelToPosition(None, (0,0))
	#  # print 'W,0', wcs.pixelToPosition(None, (w,0))
	#  # print '0,H', wcs.pixelToPosition(None, (0,h))
	#  # print 'W,H', wcs.pixelToPosition(None, (w,h))
	#  fakewcs = wcs
	#  fakeimg = Image(data=fakedata, invvar=fakedata, psf=psf,
	#  				wcs=wcs, sky=sky, photocal=photocal, name='Fake')
	#  del psf
	#  del wcs
	#  del photocal

	tims = [cftimg] + [timg for timg,tinf in TI]
	# for tim in tims:
	# 	try:
	# 		print 'Test pickling im', tim.name
	# 		pickle_to_file(tim, 'test.pickle')
	# 	except:
	# 		print 'failed:'
	# 		traceback.print_exc()
	# 		pass
	# for src in sources:
	# 	try:
	# 		print 'Test pickling source', src
	# 		pickle_to_file(src, 'test.pickle')
	# 	except:
	# 		print 'failed:'
	# 		traceback.print_exc()
	# 		pass
	# sys.exit(0)
	
	tractor = Tractor(tims)
	tractor.addSources(sources)

	skyvals = ( [(cfstd, cfsky)] +
				[(info['skysig'], info['sky'])
				 for timg,info in TI] )
	return tractor,skyvals
コード例 #9
0
ファイル: cachetest.py プロジェクト: lyczek/tractor
import numpy as np

from tractor import *
from tractor import sdss as st
from tractor.cache import *
from astrometry.util.ttime import *
import gc

# gc.set_debug(gc.DEBUG_LEAK)
# gc.enable()

run, camcol, field = 3384, 4, 198
bandname = "r"

timg, info = st.get_tractor_image(run, camcol, field, bandname, useMags=True)
sources = st.get_tractor_sources(run, camcol, field, bandname, bands=[bandname])

# mags = []
# for i,src in enumerate(sources):
# 	m = getattr(src.getBrightness(), bandname)
# 	mags.append(m)
# J = np.argsort(mags)

# sources = [sources[J[i]] for i in range(10)]

sources = sources[:20]

tractor = Tractor([timg], sources)
tractor.cache = Cache(maxsize=100)

for step in range(10):