예제 #1
0
 def GetFits(self):
     bands = dict([('J0837','F606W'),('J0901','F606W'),('J0913','F555W'),('J1125','F606W'),('J1144','F606W'),('J1218','F606W'),('J1248','F555W'),('J1323','F555W'),('J1347','F606W'),('J1446','F606W'),('J1605','F555W'),('J1606','F606W'),('J1619','F606W'),('J2228','F606W')])
     #  not working yet - this will need us to have all the images somewhere, and all the xc,yc offsets!
     # get nnls values! Ideally, these should be already saved
     print "why didn't you save these before?!?"
     yc,xc = iT.coords(self.img1.shape)
     OVRS=1
     yo,xo=iT.overSample(self.img1.shape,OVRS)
     colours = [bands[self.name], 'F814W']
     models = []
     fits = []
     for i in range(len(self.imgs)):
         if i == 0:
             dx,dy = 0,0
         else:
             dx = self.Ddic['xoffset']
             dy = self.Ddic['yoffset']
         xp,yp = xc+dx+self.Dx,yc+dy+self.Dx
         xop,yop = xo+dy+self.Dy,yo+dy+self.Dy
         image = self.imgs[i]
         sigma = self.sigs[i]
         psf = self.PSFs[i]
         imin,sigin,xin,yin = image.flatten(), sigma.flatten(),xp.flatten(),yp.flatten()
         n = 0
         model = np.empty(((len(self.gals) + len(self.srcs)+1),imin.size))
         for gal in self.gals:
             gal.setPars()
             tmp = xc*0.
             tmp = gal.pixeval(xp,yp,1./OVRS,csub=11) # evaulate on the oversampled grid. OVRS = number of new pixels per old pixel.
             tmp = iT.resamp(tmp,OVRS,True) # convert it back to original size
             tmp = convolve.convolve(tmp,psf,False)[0]
             model[n] = tmp.ravel()
             n +=1
         for lens in self.lenses:
             lens.setPars()
             x0,y0 = pylens.lens_images(self.lenses,self.srcs,[xp,yp],1./OVRS,getPix=True)
         for src in self.srcs:
             src.setPars()
             tmp = xc*0.
             tmp = src.pixeval(x0,y0,1./OVRS,csub=11)
             tmp = iT.resamp(tmp,OVRS,True)
             tmp = convolve.convolve(tmp,psf,False)[0]
             model[n] = tmp.ravel()
             n +=1
         model[n] = np.ones(model[n].shape)
         n +=1
         rhs = (imin/sigin) # data
         op = (model/sigin).T # model matrix
         fit, chi = optimize.nnls(op,rhs)
         components = (model.T*fit).T.reshape((n,image.shape[0],image.shape[1]))
         model = components.sum(0)
         models.append(model)
         #SotPleparately(image,model,sigma,colours[i])
         #NotPlicely(image,model,sigma)
         comps = False
         if comps == True:
             CotSomponents(components,colours[i])
         fits.append(fit)
         self.fits = fits
def logP(value=0.,p=pars):
    lp = 0.
    models = []
    for i in range(len(imgs)):
        image, sigma,scale = imgs[i],sigs[i],scales[i]
        if i == 0:
            dx,dy = 0,0
            xp,yp = xc+dx,yc+dy
            psf = PSFs[i]
        elif i ==1:
            dx = pars[0].value 
            dy = pars[1].value 
            xp,yp = xc+dx,yc+dy
            psf = PSFs[i]
        elif i ==2:
            dx = pars[2].value 
            dy = pars[3].value
            xp,yp = xck+dx,yck+dy
            psf = xpsf*0.
            for obj in psfObjs:
                obj.setPars()
                psf += obj.pixeval(xpsf,ypsf) / (np.pi*2.*obj.pars['sigma'].value**2.)
            psf = psf/psf.sum()
            psf = convolve.convolve(image,psf)[1]
        mask,mask2=np.ones(image.shape),np.ones(image.shape)
        mask,mask2=mask==1,mask2==1
        imin,sigin,xin,yin = image[mask], sigma[mask],xp[mask2],yp[mask2]
        n = 0
        model = np.empty(((len(gals) + len(srcs)+1),imin.size))
        for gal in gals:
            gal.setPars()
            #print gal.pars['x'].value, gal.pars['y'].value,gal.pars['q'].value, gal.pars['pa'].value,gal.pars['re'].value, gal.pars['n'].value
            tmp = xp*0.
            tmp[mask2] = gal.pixeval(xin,yin,scale/OVRS,csub=1) 
            tmp = iT.resamp(tmp,OVRS,True) 
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp[mask].ravel()
            n +=1
        for lens in lenses:
            lens.setPars()
        x0,y0 = pylens.lens_images(lenses,srcs,[xin,yin],1./OVRS,getPix=True)
        for src in srcs:
            src.setPars()
            #print src.pars['x'].value, src.pars['y'].value,src.pars['q'].value, src.pars['pa'].value,src.pars['re'].value, src.pars['n'].value
            tmp = xp*0.
            tmp[mask2] = src.pixeval(x0,y0,scale/OVRS,csub=1)
            tmp = iT.resamp(tmp,OVRS,True)
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp[mask].ravel()
            n +=1
        model[n] = np.ones(model[n-1].shape)
        rhs = (imin/sigin) 
        op = (model/sigin).T 
        fit, chi = optimize.nnls(op,rhs)
        model = (model.T*fit).sum(1)
        resid = (model-imin)/sigin
        lp += -0.5*(resid**2.).sum()
        models.append(model)
    return lp 
예제 #3
0
def logP(value=0.,p=pars):
    lp = 0.
    models = []
    dx = pars[0].value
    dy = pars[1].value 
    xp,yp = xc+dx,yc+dy
    sig1 = pars[2].value.item()
    q1 = pars[3].value.item()
    pa1 = pars[4].value.item()
    amp1 = pars[5].value.item()
    sig2 = pars[6].value.item()
    q2 = 1.#pars[7].value.item()
    pa2 = 0#pars[7].value.item()
    amp2 = pars[7].value.item()
    sig3 = pars[8].value.item()
    q3,pa3 = 1.,0.
    amp3 = 1.-amp1-amp2
    psfObj1 = SBObjects.Gauss('psf 1',{'x':0,'y':0,'sigma':sig1,'q':q1,'pa':pa1,'amp':10})
    psfObj2 = SBObjects.Gauss('psf 2',{'x':0,'y':0,'sigma':sig2,'q':q2,'pa':pa2,'amp':10})
    psfObj3 = SBObjects.Gauss('psf 3',{'x':0,'y':0,'sigma':sig3,'q':q3,'pa':pa3,'amp':10})
    psf1 = psfObj1.pixeval(xpsf,ypsf) * amp1 / (np.pi*2.*sig1**2.)
    psf2 = psfObj2.pixeval(xpsf,ypsf) * amp2 / (np.pi*2.*sig2**2.)
    psf3 = psfObj3.pixeval(xpsf,ypsf) * amp3 / (np.pi*2.*sig3**2.)
    psf = psf1 + psf2 + psf3
    psf /= psf.sum()
    psf = convolve.convolve(image,psf)[1]
    imin,sigin,xin,yin = image[mask], sigma[mask],xp[mask2],yp[mask2]
    n = 0
    model = np.empty(((len(gals) + len(srcs)+1),imin.size))
    for gal in gals:
        gal.setPars()
        tmp = xc*0.
        tmp[mask2] = gal.pixeval(xin,yin,1./OVRS,csub=1) # evaulate on the oversampled grid. OVRS = number of new pixels per old pixel.
        tmp = iT.resamp(tmp,OVRS,True) # convert it back to original size
        tmp = convolve.convolve(tmp,psf,False)[0]
        model[n] = tmp[mask].ravel()
        n +=1
    for lens in lenses:
        lens.setPars()
    x0,y0 = pylens.lens_images(lenses,srcs,[xin,yin],1./OVRS,getPix=True)
    for src in srcs:
        src.setPars()
        tmp = xc*0.
        tmp[mask2] = src.pixeval(x0,y0,1./OVRS,csub=1)
        tmp = iT.resamp(tmp,OVRS,True)
        tmp = convolve.convolve(tmp,psf,False)[0]
        model[n] = tmp[mask].ravel()
        n +=1
    model[n] = np.ones(model[n-1].shape)
    rhs = (imin/sigin) # data
    op = (model/sigin).T # model matrix
    fit, chi = optimize.nnls(op,rhs)
    model = (model.T*fit).sum(1)
    resid = (model-imin)/sigin
    lp = -0.5*(resid**2.).sum()
    return lp 
def logP(value=0.,p=pars):
    lp = 0.
    models = []
    for i in range(len(imgs)):
        if i == 0:
            dx,dy = 0,0
            xp,yp = xc+dx,yc+dy
            OVRS=3
        elif i ==1:
            dx = pars[0].value 
            dy = pars[1].value 
            xp,yp = xc+dx,yc+dy
            OVRS=3
        elif i ==2:
            dx = pars[0].value+pars[2].value 
            dy = pars[1].value +pars[3].value
            xp,yp = xck+dx,yck+dy
            OVRS=1
        image = imgs[i]
        sigma = sigs[i]
        psf = PSFs[i]
        mask,mask2=np.ones(image.shape),np.ones(image.shape)
        mask,mask2=mask==1,mask2==1
        imin,sigin,xin,yin = image[mask], sigma[mask],xp[mask2],yp[mask2]
        n = 0
        model = np.empty(((len(gals) + len(srcs)+1),imin.size))
        for gal in gals:
            gal.setPars()
            tmp = xp*0.
            tmp[mask2] = gal.pixeval(xin,yin,1./OVRS,csub=11) # evaulate on the oversampled grid. OVRS = number of new pixels per old pixel.
            tmp = iT.resamp(tmp,OVRS,True) # convert it back to original size
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp[mask].ravel()
            n +=1
        for lens in lenses:
            lens.setPars()
        x0,y0 = pylens.lens_images(lenses,srcs,[xin,yin],1./OVRS,getPix=True)
        for src in srcs:
            src.setPars()
            tmp = xp*0.
            tmp[mask2] = src.pixeval(x0,y0,1./OVRS,csub=11)
            tmp = iT.resamp(tmp,OVRS,True)
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp[mask].ravel()
            n +=1
        model[n] = np.ones(model[n].shape)
        n +=1
        rhs = (imin/sigin) # data
        op = (model/sigin).T # model matrix
        fit, chi = optimize.nnls(op,rhs)
        model = (model.T*fit).sum(1)
        resid = (model-imin)/sigin
        lp += -0.5*(resid**2.).sum()
        models.append(model)
    return lp #,models
def logP(value=0.,p=pars):
    lp = 0.
    models = []
    for i in range(len(imgs)):
        if i == 0:
            dx,dy = 0,0
        else:
            dx = pars[0].value 
            dy = pars[1].value 
        xp,yp = xc+dx,yc+dy
        image = imgs[i]
        sigma = sigs[i]
        psf = PSFs[i]
        imin,sigin,xin,yin = image[mask], sigma[mask],xp[mask2],yp[mask2]
        n = 0
        model = np.empty(((len(gals) + len(srcs)+1),imin.size))
        galaxy = np.zeros(imin.size)
        for gal in gals:
            gal.setPars()
            tmp = xc*0.
            tmp[mask2] = gal.pixeval(xin,yin,1./OVRS,csub=11) # evaulate on the oversampled grid. OVRS = number of new pixels per old pixel.
            tmp = iT.resamp(tmp,OVRS,True) # convert it back to original size
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp[mask].ravel()
            if gal.pars['q'].value<0.35:
                galaxy += gal.pixeval(xin,yin,1,csub=11)
            n +=1
        for lens in lenses:
            lens.setPars()
        x0,y0 = pylens.lens_images(lenses,srcs,[xin,yin],1./OVRS,getPix=True)
        for src in srcs:
            src.setPars()
            tmp = xc*0.
            tmp[mask2] = src.pixeval(x0,y0,1./OVRS,csub=11)
            tmp = iT.resamp(tmp,OVRS,True)
            b,std,xmid,ymid = lenses[0].pars['b'].value, lenses[0].pars['b'].value*0.5,lenses[0].pars['x'].value,lenses[0].pars['y'].value
            r = np.sqrt((xin-xmid)**2. + (yin-ymid)**2.)
            mask3 = np.where((r>b-std) & (r<b+std) & (galaxy>=0.05*np.amax(galaxy)))
            tmp.ravel()[mask3] -= pars[-1].value#*galaxy[mask3]
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp[mask].ravel()
            n +=1
        model[n] = -1*np.ones(model[n-1].shape)
        n+=1
        ### if galaxy light > X, 
        rhs = (imin/sigin) # data
        op = (model/sigin).T # model matrix
        fit, chi = optimize.nnls(op,rhs)
        model = (model.T*fit).sum(1)
        resid = (model-imin)/sigin
        lp += -0.5*(resid**2.).sum()
        models.append(model)
    return lp #,models
예제 #6
0
def logP(value=0.,p=pars):
    # read in sources - I don't think this is the best way, but...
    xll,yll = pylens.getDeflections(lenses,[xind,yind])
    xpeak = np.sum(xll*imgind)/np.sum(imgind)
    ypeak = np.sum(yll*imgind)/np.sum(imgind)
    #print 'xpeak,ypeak',xpeak, ypeak
    if len(srcs)==2:
        srcs[0] = SBModels.Sersic('Source 2',{'x':dics[0]['x']+xpeak,'y':dics[0]['y']+ypeak,'pa':dics[0]['pa'],'q':dics[0]['q'],'re':dics[0]['re'],'n':dics[0]['n']})
        srcs[1] = SBModels.Sersic('Source 1',{'x':dics[0]['x']+xpeak,'y':dics[0]['y']+ypeak,'pa':dics[1]['pa'],'q':dics[1]['q'],'re':dics[1]['re'],'n':dics[1]['n']})
    else:
        srcs[0] = SBModels.Sersic('Source 1',{'x':dics[0]['x']+xpeak,'y':dics[0]['y']+ypeak,'pa':dics[0]['pa'],'q':dics[0]['q'],'re':dics[0]['re'],'n':dics[0]['n']})
    lp = 0.
    models = []
    for i in range(len(imgs)):
        if i == 0:
            dx,dy = 0,0
        else:
            dx = pars[0].value 
            dy = pars[1].value 
        xp,yp = xc+dx,yc+dy
        image = imgs[i]
        sigma = sigs[i]
        psf = PSFs[i]
        imin,sigin,xin,yin = image[mask], sigma[mask],xp[mask2],yp[mask2]
        n = 0
        model = np.empty(((len(gals) + len(srcs)),imin.size))
        for gal in gals:
            gal.setPars()
            tmp = xc*0.
            tmp[mask2] = gal.pixeval(xin,yin,1./OVRS,csub=1) # evaulate on the oversampled grid. OVRS = number of new pixels per old pixel.
            tmp = iT.resamp(tmp,OVRS,True) # convert it back to original size
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp[mask].ravel()
            n +=1
        for lens in lenses:
            lens.setPars()
        x0,y0 = pylens.lens_images(lenses,srcs,[xin,yin],1./OVRS,getPix=True)
        for src in srcs:
            src.setPars()
            tmp = xc*0.
            tmp[mask2] = src.pixeval(x0,y0,1./OVRS,csub=1)
            tmp = iT.resamp(tmp,OVRS,True)
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp[mask].ravel()
            n +=1
        rhs = (imin/sigin) # data
        op = (model/sigin).T # model matrix
        fit, chi = optimize.nnls(op,rhs)
        model = (model.T*fit).sum(1)
        resid = (model-imin)/sigin
        lp += -0.5*(resid**2.).sum()
        models.append(model)
    return lp #,models
예제 #7
0
def logP(value=0.,p=pars):
    lp = 0.
    models = []
    for i in range(len(imgs)):
        if i == 0:
            dx,dy = 0,0
            xp,yp = xc,yc
        else:
            dx = pars[0].value 
            dy = pars[1].value 
            xp,yp = (xck+dx)*0.2,(yck+dy)*0.2
        image = imgs[i]
        sigma = sigs[i]
        psf = PSFs[i]
        mask = np.ones(image.shape)
        mask = mask==1
        imin,sigin,xin,yin = image.flatten(), sigma.flatten(),xp.flatten(),yp.flatten()
        n = 0
        model = np.empty(((len(gals) + len(srcs)+1),imin.size))
        for gal in gals:
            gal.setPars()
            tmp = xc*0.
            if gal.pars['q'].value<0.3:
                tmp = gal.boxypixeval(xp,yp,1./OVRS,csub=11,c=pars[-1].value)
            else:
                tmp = gal.boxypixeval(xp,yp,1./OVRS,csub=11)
            tmp = iT.resamp(tmp,OVRS,True) # convert it back to original size
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp.ravel()
            n +=1
        for lens in lenses:
            lens.setPars()
        x0,y0 = pylens.lens_images(lenses,srcs,[xp,yp],1./OVRS,getPix=True)
        for src in srcs:
            src.setPars()
            tmp = xp*0.
            tmp = src.pixeval(x0,y0,1./OVRS,csub=11)
            tmp = iT.resamp(tmp,OVRS,True)
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp.ravel()
            n +=1
        model[n] = np.ones(model[n-1].shape)
        n+=1
        rhs = (imin/sigin) # data
        op = (model/sigin).T # model matrix
        fit, chi = optimize.nnls(op,rhs)
        model = (model.T*fit).sum(1)
        resid = (model-imin)/sigin
        lp += -0.5*(resid**2.).sum()
        models.append(model)
    return lp #,models
def logP(value=0.0, p=pars):
    lp = 0.0
    models = []
    dx = pars[0].value
    dy = pars[1].value
    xp, yp = xc + dx, yc + dy
    psf = xpsf * 0.0
    for obj in psfObjs:
        obj.setPars()
        psf += obj.pixeval(xpsf, ypsf) / (np.pi * 2.0 * obj.pars["sigma"].value ** 2.0)
    if obj.pars["amp"].value < 0:
        return -1e10
    psf = psf / np.sum(psf)
    # print obj.pars['q'].value, obj.pars['amp'].value
    psf = convolve.convolve(image, psf)[1]
    imin, sigin, xin, yin = image[mask], sigma[mask], xp[mask2], yp[mask2]
    n = 0
    model = np.empty(((len(gals) + len(srcs) + 1), imin.size))
    for gal in gals:
        gal.setPars()
        tmp = xc * 0.0
        tmp[mask2] = gal.pixeval(
            xin, yin, 0.2, csub=11
        )  # evaulate on the oversampled grid. OVRS = number of new pixels per old pixel.
        tmp = iT.resamp(tmp, OVRS, True)  # convert it back to original size
        tmp = convolve.convolve(tmp, psf, False)[0]
        model[n] = tmp[mask].ravel()
        n += 1
    for lens in lenses:
        lens.setPars()
    x0, y0 = pylens.lens_images(lenses, srcs, [xin, yin], 1.0 / OVRS, getPix=True)
    kk = 0
    for src in srcs:
        src.setPars()
        tmp = xc * 0.0
        tmp[mask2] = src.pixeval(x0, y0, 0.2, csub=11)
        tmp = iT.resamp(tmp, OVRS, True)
        tmp = convolve.convolve(tmp, psf, False)[0]
        model[n] = tmp[mask].ravel()
        n += 1
    model[n] = np.ones(model[n - 1].shape)
    rhs = imin / sigin  # data
    op = (model / sigin).T  # model matrix
    fit, chi = optimize.nnls(op, rhs)
    model = (model.T * fit).sum(1)
    resid = (model - imin) / sigin
    lp = -0.5 * (resid ** 2.0).sum()
    return lp
def logP(value=0.,p=pars):
    #print 'calculating likelihood'
    lp = 0.
    models = []
    for i in range(len(imgs)):
        if i == 0:
            dx,dy = 0,0
        else:
            dx = pars[0].value 
            dy = pars[1].value 
        xp,yp = xc+dx,yc+dy
        image = imgs[i]
        poisson = poissons[i]
        noise = noises[i]
        X = pars[-1].value
        sigma = (poisson + noise**X)**0.5
        psf = PSFs[i]
        imin,sigin,xin,yin = image[mask], sigma[mask],xp[mask2],yp[mask2]
        n = 0
        model = np.empty(((len(gals) + len(srcs)),imin.size))
        for gal in gals:
            gal.setPars()
            tmp = xc*0.
            tmp[mask2] = gal.pixeval(xin,yin,1./OVRS,csub=1) # evaulate on the oversampled grid. OVRS = number of new pixels per old pixel.
            tmp = iT.resamp(tmp,OVRS,True) # convert it back to original size
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp[mask].ravel()
            n +=1
        for lens in lenses:
            lens.setPars()
        x0,y0 = pylens.lens_images(lenses,srcs,[xin,yin],1./OVRS,getPix=True)
        for src in srcs:
            src.setPars()
            tmp = xc*0.
            tmp[mask2] = src.pixeval(x0,y0,1./OVRS,csub=1)
            tmp = iT.resamp(tmp,OVRS,True)
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp[mask].ravel()
            n +=1
        rhs = (imin/sigin) # data
        op = (model/sigin).T # model matrix
        fit, chi = optimize.nnls(op,rhs)
        model = (model.T*fit).sum(1)
        resid = (model-imin)/sigin
        lp += -0.5*(resid**2.).sum()
        models.append(model)
        #print 'calculated likelihood', lp
    return lp #,models
예제 #10
0
def logP(value=0.,p=pars):
    lp = 0.
    models = []
    for i in range(len(imgs)):
        if i == 0:
            dx,dy = 0,0
        else:
            dx = pars[0].value 
            dy = pars[1].value 
        xp,yp = xc+dx,yc+dy
        image = imgs[i]
        sigma = sigs[i]
        psf = PSFs[i]
        imin,sigin,xin,yin = image[mask], sigma[mask],xp[mask2],yp[mask2]
        n = 0
        model = np.empty(((len(srcs)),imin.size))
        for lens in lenses:
            lens.setPars()
        x0,y0 = pylens.lens_images(lenses,srcs,[xin,yin],1./OVRS,getPix=True)
        for src in srcs:
            src.setPars()
            tmp = xc*0.
            tmp[mask2] = src.pixeval(x0,y0,1./OVRS,csub=1)
            tmp = iT.resamp(tmp,OVRS,True)
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp[mask].ravel()
            n +=1
        rhs = (imin/sigin) # data
        op = (model/sigin).T # model matrix
        fit, chi = optimize.nnls(op,rhs)
        model = (model.T*fit).sum(1)
        resid = (model-imin)/sigin
        lp += -0.5*(resid**2.).sum()
        models.append(model)
    return lp #,models
예제 #11
0
def getYsoln(star, nstars, low, high):
    # Find solution as function of y position if there are enough star traces
    print ""
    print "Finding y solution"
    star = star.repeat(2, 0).repeat(2, 1)
    star = rotate2(star)
    starTMP = star[low * 2:high * 2].copy()
    if nstars > 3:
        ytrue2, ymap2 = ycorrect.ycorrect(starTMP, False, order=2)
        coords = numpy.indices(starTMP.shape).astype(numpy.float32)
        x = coords[1].flatten()
        y = coords[0].flatten()
        del coords
        yforw2 = sf.genfunc(x, y, ytrue2).reshape(starTMP.shape)
        yback2 = sf.genfunc(x, y, ymap2).reshape(starTMP.shape)
    # Not enough star traces; assume the distortion is constant over y
    else:
        yforw2, yback2 = ycor(starTMP)
    # Repeat for non-oversampled case
    star = iT.resamp(star, 2)[low:high]
    if nstars > 3:
        ytrue, ymap = ycorrect.ycorrect(star, False, order=2)
        coords = numpy.indices(star.shape).astype(numpy.float32)
        x = coords[1].flatten()
        y = coords[0].flatten()
        del coords
        yforw = sf.genfunc(x, y, ytrue).reshape(star.shape)
        yback = sf.genfunc(x, y, ymap).reshape(star.shape)
    else:
        yforw, yback = ycor(star)
    return yforw, yback, yforw2, yback2  #,ytrue2,ymap2
def logP(value=0.,p=pars):
    lp = 0.
    models = []
    for i in range(len(imgs)):
        if i == 0:
            dx,dy = 0,0
        else:
            dx = pars[0].value 
            dy = pars[1].value 
        xp,yp = xc+dx,yc+dy
        image = imgs[i]
        sigma = sigs[i]
        psf = PSFs[i]
        mask = masks[i]
        mask2 = mask2s[i]
        x0,y0=coords[i]
        imin,sigin,xin,yin = image[mask], sigma[mask],xp[mask2],yp[mask2]
        n = 0
        model = np.empty(((len(gals) + len(srcs)),imin.size))
        for gal in gals:
            gal.setPars()
            tmp = xc*0.
            tmp[mask2] = gal.pixeval(xin,yin,1./OVRS,csub=1) # evaulate on the oversampled grid. OVRS = number of new pixels per old pixel.
            tmp = iT.resamp(tmp,OVRS,True) # convert it back to original size
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp[mask].ravel()
            n +=1
        for src in srcs:
            src.setPars()
            tmp = xc*0.
            tmp[mask2] = src.pixeval(x0,y0,1./OVRS,csub=1)
            tmp = iT.resamp(tmp,OVRS,True)
            tmp = convolve.convolve(tmp,psf,False)[0]
            model[n] = tmp[mask].ravel()
            n +=1
        rhs = (imin/sigin) # data
        op = (model/sigin).T # model matrix
        fit, chi = optimize.nnls(op,rhs)
        model = (model.T*fit).sum(1)
        resid = (model-imin)/sigin
        lp += -0.5*(resid**2.).sum()
        models.append(model)
    return lp #,models
예제 #13
0
def getFlatNorm(flat, ysoln, low, high):
    from scipy.stats import stats
    f = getStraight(flat, ysoln, low, False)
    ftmp = numpy.where(f == 0, numpy.nan, f)
    norm = stats.nanmedian(ftmp[20:-20], 0)
    norm = numpy.where((norm <= 0) | numpy.isnan(norm), 1., norm)
    f /= norm
    img = numpy.ones((2400, 2400))
    img[low * 2:high * 2] = st.resampley(f, ysoln[3], mode='nearest')
    return iT.resamp(derotate2(img), 2)
예제 #14
0
def lensModel(inpars,
              image,
              sig,
              gals,
              lenses,
              sources,
              xc,
              yc,
              OVRS=1,
              csub=11,
              psf=None,
              noResid=False,
              verbose=False):
    import pylens, numpy
    import indexTricks as iT

    model = xc * 0.
    for gal in gals:
        gal.setPars(inpars)
        model += gal.pixeval(xc, yc, 1. / OVRS, csub=csub)

    for src in sources:
        src.setPars(inpars)

    for lens in lenses:
        lens.setPars(inpars)

    model = model + pylens.lens_images(lenses, sources, [xc, yc], 1. / OVRS)
    if numpy.isnan(model.sum()):
        if verbose == True:
            print 'nan model'
        return -1e300

    if OVRS > 1:
        model = iT.resamp(model, OVRS, True)

    if psf is not None:
        from imageSim import convolve
        global psfFFT
        if psfFFT is None:
            psf /= psf.sum()
            model, psfFFT = convolve.convolve(model, psf)
        else:
            model, psfFFT = convolve.convolve(model, psfFFT, False)

    if noResid is True:
        return model
    resid = ((model - image) / sig).ravel()
    if verbose == True:
        print "%f  %5.2f %d %dx%d" % (
            (resid**2).sum(), (resid**2).sum() / resid.size, resid.size,
            image.shape[1], image.shape[0])
    return -0.5 * (resid**2).sum()
예제 #15
0
def getStraight(img, ysoln, low, resamp=True, mode='constant'):
    yforw = ysoln[2]
    tmp = img.repeat(2, 0).repeat(2, 1)
    x = iT.coords(yforw.shape)[1]
    c = numpy.array([yforw + low * 2, x])
    X = ndimage.map_coordinates(rotcoords2[1], c)
    Y = ndimage.map_coordinates(rotcoords2[0], c)
    c = numpy.array([Y, X])
    tmp = ndimage.map_coordinates(tmp, c, mode=mode)
    if resamp == True:
        return iT.resamp(tmp, 2)
    return tmp
예제 #16
0
def cr_reject(sub, sky, nsig=5., contrast=2., sigfrac=0.3):
    gain = 5.
    rn = 25.
    sub = sub.copy()
    med5 = ndimage.median_filter(sub, 5)
    med5 += sky

    n = 2
    blksub = sub.repeat(n, 0).repeat(n, 1)

    blksub = ndimage.laplace(blksub) * -0.5
    blksub[blksub < 0] = 0.
    sub2 = iT.resamp(blksub, n, False)

    med5[med5 <= 0.] = 0.0001

    noise = (med5 * gain + rn**2)**0.5 / gain
    sigmap = sub2 / noise
    med5 = ndimage.median_filter(sigmap, 5)
    sigmap -= med5

    map = sigmap.copy()
    map[map < nsig] = 0
    map[map > 0] = 1

    med3 = ndimage.median_filter(sub, 3)
    med7 = ndimage.median_filter(med3, 7)

    med3 -= med7
    med3 /= noise

    med3[med3 < 0.01] = 0.01

    stars = (map * sigmap) / med3

    stars[stars < contrast] = 0
    stars[stars > 0.] = 1

    map *= stars

    gmap = ndimage.maximum_filter(map, 3) * sigmap
    gmap[gmap < nsig] = 0
    gmap[gmap > 0] = 1

    fmap = ndimage.maximum_filter(gmap, 3) * sigmap
    fmap[fmap < (nsig * sigfrac)] = 0
    fmap[fmap > 0] = 1
    map = fmap.copy()
    del gmap, fmap, stars, sigmap, med3, med7

    return map
def logP(value=0.,p=pars):
    lp = 0.
    models = []
    dx = pars[0].value
    dy = pars[1].value 
    xp,yp = xc+dx,yc+dy
    imin,sigin,xin,yin = image[mask], sigma[mask],xp[mask2],yp[mask2]
    n = 0
    model = np.empty(((len(gals) + len(srcs)+1),imin.size))
    for gal in gals:
        gal.setPars()
        tmp = xc*0.
        tmp[mask2] = gal.pixeval(xin,yin,1./OVRS,csub=11) # evaulate on the oversampled grid. OVRS = number of new pixels per old pixel.
        tmp = iT.resamp(tmp,OVRS,True) # convert it back to original size
        tmp = convolve.convolve(tmp,psf,False)[0]
        model[n] = tmp[mask].ravel()
        n +=1
    for lens in lenses:
        lens.setPars()
    x0,y0 = pylens.lens_images(lenses,srcs,[xin,yin],1./OVRS,getPix=True)
    kk=0
    for src in srcs:
        src.setPars()
        tmp = xc*0.
        tmp[mask2] = src.pixeval(x0,y0,1./OVRS,csub=11)
        tmp = iT.resamp(tmp,OVRS,True)
        tmp = convolve.convolve(tmp,psf,False)[0]
        model[n] = tmp[mask].ravel()
        n +=1
    model[n] = np.ones(model[n-1].shape)
    rhs = (imin/sigin) # data
    op = (model/sigin).T # model matrix
    fit, chi = optimize.nnls(op,rhs)
    model = (model.T*fit).sum(1)
    resid = (model-imin)/sigin
    lp = -0.5*(resid**2.).sum()
    return lp 
예제 #18
0
def resampleData(data, owgrid, low, high, ysoln, xsoln, rwsoln):
    dy = (high - low) * 2
    ygrid = iT.coords((dy, owgrid.size))[0]
    xgrid = sf.genfunc(owgrid, 0., rwsoln).repeat(dy)
    xgrid = xgrid.reshape((owgrid.size, dy)).T
    xgrid = sf.genfunc(xgrid.flatten(), ygrid.flatten(), xsoln['forw'])
    xgrid = xgrid.reshape(ygrid.shape)
    c = numpy.array([ygrid, xgrid])
    ygrid = ndimage.map_coordinates(ysoln[2], c)
    c = numpy.array([ygrid + low * 2, xgrid])
    X = ndimage.map_coordinates(rotcoords2[1], c)
    Y = ndimage.map_coordinates(rotcoords2[0], c)
    c = numpy.array([Y, X])
    d = data.repeat(2, 0).repeat(2, 1)
    img = ndimage.map_coordinates(d, c, order=5)
    return iT.resamp(img, 2)
예제 #19
0
def lensModel(inpars,image,sig,gals,lenses,sources,xc,yc,OVRS=1,csub=11,psf=None,noResid=False,verbose=False):
    import pylens,numpy
    import indexTricks as iT

    model = xc*0.
    for gal in gals:
        gal.setPars(inpars)
        model += gal.pixeval(xc,yc,1./OVRS,csub=csub)

    for src in sources:
        src.setPars(inpars)

    for lens in lenses:
        lens.setPars(inpars)

    model = model + pylens.lens_images(lenses,sources,[xc,yc],1./OVRS)
    if numpy.isnan(model.sum()):
        if verbose==True:
            print 'nan model'
        return -1e300

    if OVRS>1:
        model = iT.resamp(model,OVRS,True)

    if psf is not None:
        from imageSim import convolve
        global psfFFT
        if psfFFT is None:
            psf /= psf.sum()
            model,psfFFT = convolve.convolve(model,psf)
        else:
            model,psfFFT = convolve.convolve(model,psfFFT,False)

    if noResid is True:
        return model
    resid = ((model-image)/sig).ravel()
    if verbose==True:
        print "%f  %5.2f %d %dx%d"%((resid**2).sum(),(resid**2).sum()/resid.size,resid.size,image.shape[1],image.shape[0])
    return -0.5*(resid**2).sum()
for obj in psfObjs:
    obj.setPars()
    psf += obj.pixeval(xpsf,ypsf) / (np.pi*2.*obj.pars['sigma'].value**2.)
psf = psf/np.sum(psf)
print 'ici',obj.pars['q'].value
psf = convolve.convolve(image,psf)[1]
xp,yp = xc+dx,yc+dy
xop,yop = xo+dy,yo+dy
imin,sigin,xin,yin = image.flatten(), sigma.flatten(),xp.flatten(),yp.flatten()
n = 0
model = np.empty(((len(gals) + len(srcs)+1),imin.size))
for gal in gals:
    gal.setPars()
    tmp = xc*0.
    tmp = gal.pixeval(xp,yp,1./OVRS,csub=11) # evaulate on the oversampled grid. OVRS = number of new pixels per old pixel.
    tmp = iT.resamp(tmp,OVRS,True) # convert it back to original size
    tmp = convolve.convolve(tmp,psf,False)[0]
    model[n] = tmp.ravel()
    n +=1
for lens in lenses:
    lens.setPars()
x0,y0 = pylens.lens_images(lenses,srcs,[xp,yp],1./OVRS,getPix=True)
for src in srcs:
    src.setPars()
    tmp = xc*0.
    tmp = src.pixeval(x0,y0,1./OVRS,csub=11)
    tmp = iT.resamp(tmp,OVRS,True)
    tmp = convolve.convolve(tmp,psf,False)[0]
    model[n] = tmp.ravel()
    n +=1
model[n] = np.ones(model[n-1].shape)
예제 #21
0
파일: modelSB.py 프로젝트: tcollett/pylens
def linearmodelSB(inpars,
                  simage,
                  sigma,
                  mask,
                  models,
                  xc,
                  yc,
                  OVRS=1,
                  csub=11,
                  noResid=False,
                  levMar=False):
    def objf(x, lhs, rhs):
        return ((numpy.dot(lhs, x) - rhs)**2).sum()

    def objdf(x, lhs, rhs):
        return numpy.dot(lhs.T, numpy.dot(lhs, x) - rhs)

    nmod = len(models)
    model = numpy.zeros((nmod, mask.sum()))
    norm = numpy.zeros(nmod)
    for n in range(nmod):
        M = models[n]
        M.setPars(inpars)
        if M.convolve is not None:
            img = M.pixeval(xc, yc, scale=1. / abs(OVRS))
            img = convolve.convolve(img, M.convolve, False)[0]
            if OVRS > 1:
                img = iT.resamp(img, OVRS, True)
        else:
            img = M.pixeval(xc, yc)
            if OVRS > 1:
                img = iT.resamp(img, OVRS, True)
        if numpy.isnan(img).any() and noResid == False:
            return -1e300
        model[n] = img[mask].ravel()
        norm[n] = model[n].max()
        model[n] /= norm[n]

    op = (model / sigma).T
    fit, chi = numpy.linalg.lstsq(op, simage)[:2]
    fit = numpy.array(fit)
    if (fit < 0).any():
        sol = fit
        sol[sol < 0] = 1e-11
        bounds = [(1e-11, 1e11)] * nmod
        result = fmin_slsqp(objf,
                            sol,
                            bounds=bounds,
                            full_output=1,
                            fprime=objdf,
                            acc=1e-19,
                            iter=2000,
                            args=[op.copy(), simage.copy()],
                            iprint=0)
        fit, chi = result[:2]
        fit = numpy.asarray(fit)
        if (fit < 1e-11).any():
            fit[fit < 1e-11] = 1e-11

    for i in range(nmod):
        models[i].amp = fit[i] / norm[i]

    if levMar == True:
        return (op * fit).sum(1) - simage
        lhs = (op * fit)
        print lhs.shape, simage.shape
        return lhs - simage

    if noResid == True:
        output = []
        for M in models:
            if M.convolve is not None:
                img = M.pixeval(xc, yc, scale=1. / abs(OVRS))
                img = convolve.convolve(img, M.convolve, False)[0]
                if OVRS > 1:
                    img = iT.resamp(img, OVRS, True)
            else:
                img = M.pixeval(xc, yc)
                if OVRS > 1:
                    img = iT.resamp(img, OVRS, True)
            output.append(img)
        return output

    logp = -0.5 * chi - numpy.log(sigma).sum()
    return logp
srcs = []
for name in S.keys():
    s = S[name]
    p = {}
    if name == 'Source 1':
        print name
        for key in 'q','re','n','pa':
            p[key] =s[key]['value']
        for key in 'x','y':
            p[key] = s[key]['value']
    srcs.append(SBModels.Sersic(name,p))
psfObj1 = SBObjects.Gauss('psf 1',{'x':0,'y':0,'sigma':sig1,'q':q1,'pa':pa1,'amp':10})
psfObj2 = SBObjects.Gauss('psf 2',{'x':0,'y':0,'sigma':sig2,'q':q2,'pa':pa2,'amp':10})
psf1 = psfObj1.pixeval(xpsf,ypsf) * amp1 / (np.pi*2.*sig1**2.)
psf2 = psfObj2.pixeval(xpsf,ypsf) * amp2 / (np.pi*2.*sig2**2.)
psf = iT.resamp(psf1,PVRS,True)/PVRS**2. + iT.resamp(psf2,PVRS,True)/PVRS**2.
psf /= psf.sum()
psf = convolve.convolve(image,psf)[1]
xp,yp = xc+dx,yc+dy
imin,sigin,xin,yin = image[mask], sigma[mask],xp[mask2],yp[mask2]
n = 0
model = np.empty(((len(gals) + len(srcs)+1),imin.size))
for gal in gals:
    gal.setPars()
    tmp = xc*0.
    tmp[mask2] = gal.pixeval(xin,yin,1./OVRS,csub=1) # evaulate on the oversampled grid. OVRS = number of new pixels per old pixel.
    tmp = iT.resamp(tmp,OVRS,True) # convert it back to original size
    tmp = convolve.convolve(tmp,psf,False)[0]
    model[n] = tmp[mask].ravel()
    n +=1
for lens in lenses:
예제 #23
0
    def GetPDFs(self,kpc=False):
        self.muPDF = []
        self.murestPDF = []
        self.RePDF = []
        self.magrestPDF = []
        self.LumPDF = []
        self.magPDF = []
        self.fitPDF = []
        self.bbandPDF = []
        OVRS=self.OVRS
        yo,xo = iT.coords(self.img1.shape)
        yc,xc=iT.overSample(self.img1.shape,OVRS)
        colours = [bands[self.name], 'F814W']
        for b1 in range(0,len(self.dictionaries),100):
            srcs,gals,lenses = [],[],[]
            for number in range(1,1+self.srcno):
                name = 'Source '+str(number)
                p = {}
                for key in 'q','re','n','pa':
                    p[key] = self.dictionaries[b1][name+' '+key]
                for key in 'x','y': # subtract lens potition - to be added back on later in each likelihood iteration!
                    p[key] = self.dictionaries[b1][name+' '+key]+self.dictionaries[b1]['Lens 1 '+key]
                srcs.append(SBBModels.Sersic(name,p))
            for number in range(1,1+self.galno):
                name = 'Galaxy '+str(number)
                p = {}
                for key in 'x','y','q','re','n','pa':
                    p[key] = self.dictionaries[b1][name+' '+key]
                gals.append(SBBModels.Sersic(name,p))
            p = {}
            for key in 'x','y','q','pa','b','eta':
                p[key] = self.dictionaries[b1]['Lens 1 '+key]
            lenses.append(MassModels.PowerLaw('Lens 1',p))
            p = {}
            p['x'] = lenses[0].pars['x']
            p['y'] = lenses[0].pars['y']
            p['b'] = self.dictionaries[b1]['extShear']
            p['pa'] = self.dictionaries[b1]['extShear PA']
            lenses.append(MassModels.ExtShear('shear',p))
            # fits
            fits = []
            for i in range(len(self.imgs)):
                if i == 0:
                    dx,dy = 0,0
                else:
                    dx = self.dictionaries[b1]['xoffset']
                    dy = self.dictionaries[b1]['yoffset']
                xp,yp = xc+dx+self.Dx,yc+dy+self.Dy
                xop,yop = xo+dy+self.Dx,yo+dy+self.Dy
                image = self.imgs[i]
                sigma = self.sigs[i]
                psf = self.PSFs[i]
                imin,sigin,xin,yin = image.flatten(), sigma.flatten(),xp.flatten(),yp.flatten()
                n = 0
                model = np.empty(((len(gals) + len(srcs)+1),imin.size))
                for gal in gals:
                    gal.setPars()
                    tmp = xc*0.
                    tmp = gal.pixeval(xp,yp,1./OVRS,csub=11) # evaulate on the oversampled grid. OVRS = number of new pixels per old pixel.
                    tmp = iT.resamp(tmp,OVRS,True) # convert it back to original size
                    tmp = convolve.convolve(tmp,psf,False)[0]
                    model[n] = tmp.ravel()
                    n +=1
                for lens in lenses:
                    lens.setPars()
                    x0,y0 = pylens.lens_images(lenses,srcs,[xp,yp],1./OVRS,getPix=True)
                for src in srcs:
                    src.setPars()
                    tmp = xc*0.
                    if 'boxiness' in self.dic.keys():
                        if src.name == 'Source 2':
                            #print 'this source has a boxy/disky component with c = ', '%.2f'%self.Ddic['boxiness'], '. I hope this is J1606!'
                            tmp = src.boxypixeval(x0,y0,1./OVRS,csub=11,c=self.Ddic['boxiness'])
                        else:
                            tmp = src.pixeval(x0,y0,1./OVRS,csub=11)
                    else:
                        tmp = src.pixeval(x0,y0,1./OVRS,csub=11)
                    tmp = iT.resamp(tmp,OVRS,True)
                    tmp = convolve.convolve(tmp,psf,False)[0]
                    model[n] = tmp.ravel()
                    if self.name == 'J0837':
                        #print "making J0837's dust lane..."
                        if src.name == 'Source 2':
                            model[n] *= -1
                    n +=1
                model[n] = np.ones(model[n].shape)
                n +=1
                rhs = (imin/sigin) # data
                op = (model/sigin).T # model matrix
                fit, chi = optimize.nnls(op,rhs)
                fits.append(fit)
            # source plane (observed) magnitudes
            if len(self.srcs)==1 or self.name == 'J0837':
                mag_v = srcs[0].getMag(fits[0][-2],self.ZPs[0])
                mag_i = srcs[0].getMag(fits[1][-2],self.ZPs[1])
            elif len(self.srcs)==2 and self.name != 'J0837':
                mv1,mv2 = srcs[0].getMag(fits[0][-3],self.ZPs[0]), srcs[1].getMag(fits[0][-2],self.ZPs[0])
                mi1,mi2 = srcs[0].getMag(fits[1][-3],self.ZPs[1]),srcs[1].getMag(fits[1][-2],self.ZPs[1]) 
                Fv = 10**(0.4*(self.ZPs[0]-mv1)) + 10**(0.4*(self.ZPs[0]-mv2))
                Fi = 10**(0.4*(self.ZPs[0]-mi1)) + 10**(0.4*(self.ZPs[0]-mi2))
                mag_v, mag_i = -2.5*np.log10(Fv) + self.ZPs[0], -2.5*np.log10(Fi) + self.ZPs[1]
            else:
                print 'how many sources do you want from me?'
            # intrinsic magnitudes
            if bands[self.name] == 'F555W':
                vband = MassB2
                bband = MassB2toB
            elif bands[self.name] == 'F606W':
                vband = MassB1
                bband = MassB1toB
            iband, kband = MassR, MassK
            Lv,mag_v_rest = vband(mag_v, self.z)
            Li,mag_i_rest = iband(mag_i, self.z)
            Lb,mag_b_rest = bband(mag_v,self.z)
            # sizes
            if self.srcno == 1 or self.name == 'J0837':
                Re_v, Re_i = srcs[0].pars['re']*0.05, srcs[0].pars['re']*0.05
            elif self.srcno == 2 and self.name != 'J0837':
                Xgrid = np.logspace(-4,5,1501)
                Ygrid = np.logspace(-4,5,1501)
                bandRes = []
                for i in range(len(self.imgs)):
                    source = fits[i][-3]*srcs[0].eval(Xgrid) + fits[i][-2]*srcs[1].eval(Xgrid)
                    R = Xgrid.copy()
                    light = source*2.*np.pi*R
                    mod = splrep(R,light,t=np.logspace(-3.8,4.8,1301))
                    intlight = np.zeros(len(R))
                    for i in range(len(R)):
                        intlight[i] = splint(0,R[i],mod)
                    model = splrep(intlight[:-300],R[:-300])
                    if len(model[1][np.where(np.isnan(model[1])==True)]>0):
                        #print 'here'
                        model = splrep(intlight[:-600],R[:-600])
                    reff = splev(0.5*intlight[-1],model)
                    bandRes.append(reff*0.05)
                Re_v,Re_i = bandRes
            # surface brightnesses
            mu_v_rest = mag_v_rest +  2.5*np.log10(2.*np.pi*Re_v**2.)
            mu_i_rest = mag_i_rest + 2.5*np.log10(2.*np.pi*Re_i**2.)
            mu_b_rest = mag_b_rest + 2.5*np.log10(2.*np.pi*Re_v**2.)
            mu_v = mag_v +  2.5*np.log10(2.*np.pi*Re_v**2.)
            mu_i = mag_i + 2.5*np.log10(2.*np.pi*Re_i**2.)
            self.muPDF.append([mu_v,mu_i])
            self.murestPDF.append([mu_v_rest,mu_i_rest,mu_b_rest])
	    if kpc:
		self.RePDF.append([Re_v*self.scale,Re_i*self.scale])
	    else:
		self.RePDF.append([Re_v,Re_i])
            self.magrestPDF.append([mag_v_rest,mag_i_rest,mag_b_rest])
            self.LumPDF.append([Lv,Li,Lb])
            self.magPDF.append([mag_v,mag_i])
            self.fitPDF.append(fits)
예제 #24
0
def lensFit(inpars,image,sig,gals,lenses,sources,xc,yc,OVRS=1,csub=5,psf=None,mask=None,noResid=False,verbose=False,getModel=False,showAmps=False,allowNeg=False):
    import pylens,numpy
    import indexTricks as iT
    from imageSim import convolve
    from scipy import optimize


    if noResid==True or getModel==True:
        mask = None
    if mask is None:
        xin = xc.copy()
        yin = yc.copy()
        imin = image.flatten()
        sigin = sig.flatten()
    else:
        xin = xc[mask].copy()
        yin = yc[mask].copy()
        imin = image[mask].flatten()
        sigin = sig[mask].flatten()

    n = 0
    model = numpy.empty((len(gals)+len(sources),imin.size))
    for gal in gals:
        gal.setPars()
        gal.amp = 1
        if mask is None:
            tmp = gal.pixeval(xin,yin,1./OVRS,csub=csub)
        else:
            tmp = xc*0.
            tmp[mask] = gal.pixeval(xin,yin,1./OVRS,csub=csub)
        if numpy.isnan(tmp).any():
            if verbose==True:
                print 'nan model'
            return -1e300

#        if psf is not None:
#            tmp = convolve.convolve(tmp,psfFFT,False)[0]
        if OVRS>1:
            tmp = iT.resamp(tmp,OVRS,True)
        if psf is not None and gal.convolve is not None:
            tmp = convolve.convolve(tmp,psf,False)[0]
        if mask is None:
            model[n] = tmp.ravel()
        else:
            model[n] = tmp[mask].ravel()
        n += 1

    for lens in lenses:
        lens.setPars()

    x0,y0 = pylens.lens_images(lenses,sources,[xin,yin],1./OVRS,getPix=True)
    for src in sources:
        src.setPars()
        src.amp = 1
        if mask is None:
            tmp = src.pixeval(x0,y0,1./OVRS,csub=csub)
        else:
            tmp = xc*0.
            tmp[mask] = src.pixeval(x0,y0,1./OVRS,csub=csub)
        if numpy.isnan(tmp).any():
            if verbose==True:
                print 'nan model'
            return -1e300

#        if psf is not None:
#            tmp = convolve.convolve(tmp,psfFFT,False)[0]
        if OVRS>1:
            tmp = iT.resamp(tmp,OVRS,True)
        if psf is not None:
            tmp = convolve.convolve(tmp,psf,False)[0]
        if mask is None:
            model[n] = tmp.ravel()
        else:
            model[n] = tmp[mask].ravel()
        n += 1

    rhs = (imin/sigin)
    op = (model/sigin).T

    fit,chi = optimize.nnls(op,rhs)

    if getModel is True:
        j = 0
        for m in gals+sources:
            m.amp = fit[j]
            j += 1
        return (model.T*fit).T.reshape((n,image.shape[0],image.shape[1]))
    elif noResid is True:
        model = (model.T*fit).sum(1).reshape(image.shape)
        j = 0
        for m in gals+sources:
            m.amp = fit[j]
            j += 1
        return model
    model = (model.T*fit).sum(1)

    if mask is None:
        model = model.reshape(image.shape)
        resid = ((model-image)/sig).ravel()
    else:
        resid = (model-imin)/sigin

    if verbose==True:
        print "%f  %5.2f %d %dx%d"%((resid**2).sum(),(resid**2).sum()/resid.size,resid.size,image.shape[1],image.shape[0])
    return -0.5*(resid**2).sum()
예제 #25
0
def lensFit(inpars,
            image,
            sig,
            gals,
            lenses,
            sources,
            xc,
            yc,
            OVRS=1,
            csub=5,
            psf=None,
            mask=None,
            noResid=False,
            verbose=False,
            getModel=False,
            showAmps=False,
            allowNeg=False):
    import pylens, numpy
    import indexTricks as iT
    from imageSim import convolve
    from scipy import optimize
    """
    if psf is not None:
        from imageSim import convolve
        global psfFFT
        if psfFFT is None:
            psf /= psf.sum()
            #if OVRS>1:
            #    from scipy import ndimage
            #    psf = ndimage.zoom(psf,OVRS)
            tmp,psfFFT = convolve.convolve(image,psf)
    """

    if noResid == True or getModel == True:
        mask = None
    if mask is None:
        xin = xc.copy()
        yin = yc.copy()
        imin = image.flatten()
        sigin = sig.flatten()
    else:
        xin = xc[mask].copy()
        yin = yc[mask].copy()
        imin = image[mask].flatten()
        sigin = sig[mask].flatten()

    n = 0
    model = numpy.empty((len(gals) + len(sources), imin.size))
    for gal in gals:
        gal.setPars()
        gal.amp = 1
        if mask is None:
            tmp = gal.pixeval(xin, yin, 1. / OVRS, csub=csub)
        else:
            tmp = xc * 0.
            tmp[mask] = gal.pixeval(xin, yin, 1. / OVRS, csub=csub)
        if numpy.isnan(tmp).any():
            if verbose == True:
                print 'nan model'
            return -1e300

#        if psf is not None:
#            tmp = convolve.convolve(tmp,psfFFT,False)[0]
        if OVRS > 1:
            tmp = iT.resamp(tmp, OVRS, True)
        if psf is not None and gal.convolve is not None:
            tmp = convolve.convolve(tmp, psf, False)[0]
        if mask is None:
            model[n] = tmp.ravel()
        else:
            model[n] = tmp[mask].ravel()
        n += 1

    for lens in lenses:
        lens.setPars()

    x0, y0 = pylens.lens_images(lenses,
                                sources, [xin, yin],
                                1. / OVRS,
                                getPix=True)
    for src in sources:
        src.setPars()
        src.amp = 1
        if mask is None:
            tmp = src.pixeval(x0, y0, 1. / OVRS, csub=csub)
        else:
            tmp = xc * 0.
            tmp[mask] = src.pixeval(x0, y0, 1. / OVRS, csub=csub)
        if numpy.isnan(tmp).any():
            if verbose == True:
                print 'nan model'
            return -1e300

#        if psf is not None:
#            tmp = convolve.convolve(tmp,psfFFT,False)[0]
        if OVRS > 1:
            tmp = iT.resamp(tmp, OVRS, True)
        if psf is not None:
            tmp = convolve.convolve(tmp, psf, False)[0]
        if mask is None:
            model[n] = tmp.ravel()
        else:
            model[n] = tmp[mask].ravel()
        n += 1

    rhs = (imin / sigin)
    op = (model / sigin).T

    fit, chi = optimize.nnls(op, rhs)
    #print fit
    #exit()

    if getModel is True:
        j = 0
        for m in gals + sources:
            m.amp = fit[j]
            j += 1
        return (model.T * fit).T.reshape((n, image.shape[0], image.shape[1]))
    elif noResid is True:
        model = (model.T * fit).sum(1).reshape(image.shape)
        j = 0
        for m in gals + sources:
            m.amp = fit[j]
            j += 1
        return model
    model = (model.T * fit).sum(1)

    if mask is None:
        model = model.reshape(image.shape)
        resid = ((model - image) / sig).ravel()
    else:
        resid = (model - imin) / sigin

    if verbose == True:
        print "%f  %5.2f %d %dx%d" % (
            (resid**2).sum(), (resid**2).sum() / resid.size, resid.size,
            image.shape[1], image.shape[0])
    return -0.5 * (resid**2).sum()
예제 #26
0
     psf = xpsf*0.
     for obj in psfObjs:
         obj.setPars()
         psf += obj.pixeval(xpsf,ypsf) / (np.pi*2.*obj.pars['sigma'].value**2.)
     psf = psf/psf.sum()
     psf = convolve.convolve(image,psf)[1]
 mask,mask2=np.ones(image.shape),np.ones(image.shape)
 mask,mask2=mask==1,mask2==1
 imin,sigin,xin,yin = image[mask], sigma[mask],xp[mask2],yp[mask2]
 n = 0
 model = np.empty(((len(gals) + len(srcs)+1),imin.size))
 for gal in gals:
     gal.setPars()
     tmp = xp*0.
     tmp[mask2] = gal.pixeval(xin,yin,scale/OVRS,csub=1) 
     tmp = iT.resamp(tmp,OVRS,True) 
     tmp = convolve.convolve(tmp,psf,False)[0]
     model[n] = tmp[mask].ravel()
     n +=1
 for lens in lenses:
     lens.setPars()
 x0,y0 = pylens.lens_images(lenses,srcs,[xin,yin],1./OVRS,getPix=True)
 for src in srcs:
     src.setPars()
     tmp = xp*0.
     tmp[mask2] = src.pixeval(x0,y0,scale/OVRS,csub=1)
     tmp = iT.resamp(tmp,OVRS,True)
     tmp = convolve.convolve(tmp,psf,False)[0]
     model[n] = tmp[mask].ravel()
     n +=1
 model[n] = np.ones(model[n-1].shape)
def logP(value=0.0, p=pars):
    lp = 0.0
    models = []
    dx = pars[0].value
    dy = pars[1].value
    xp, yp = xc + dx, yc + dy
    sig1 = pars[2].value.item()
    q1 = pars[3].value.item()
    pa1 = pars[4].value.item()
    amp1 = pars[5].value.item()
    sig2 = pars[6].value.item()
    q2 = pars[7].value.item()
    pa2 = pars[8].value.item()
    amp2 = pars[9].value.item()
    sig3 = pars[10].value.item()
    q3 = pars[11].value.item()
    pa3 = pars[12].value.item()
    amp3 = 1.0 - amp1 - amp2
    if amp3 < 0:
        return -1e10
    # print dx,dy,sig1,sig2,sig3,q1,q2,q3,pa1,pa2,pa3,amp1,amp2,amp3
    psfObj1 = SBObjects.Gauss("psf 1", {"x": 0, "y": 0, "sigma": sig1, "q": q1, "pa": pa1, "amp": 10})
    psfObj2 = SBObjects.Gauss("psf 2", {"x": 0, "y": 0, "sigma": sig2, "q": q2, "pa": pa2, "amp": 10})
    psfObj3 = SBObjects.Gauss("psf 3", {"x": 0, "y": 0, "sigma": sig3, "q": q3, "pa": pa3, "amp": 10})
    psf1 = psfObj1.pixeval(xpsf, ypsf) * amp1 / (np.pi * 2.0 * sig1 ** 2.0)
    psf2 = psfObj2.pixeval(xpsf, ypsf) * amp2 / (np.pi * 2.0 * sig2 ** 2.0)
    psf3 = psfObj3.pixeval(xpsf, ypsf) * amp3 / (np.pi * 2.0 * sig3 ** 2.0)
    psf = psf1 + psf2 + psf3
    psf /= psf.sum()
    psf = convolve.convolve(image, psf)[1]
    imin, sigin, xin, yin = image[mask], sigma[mask], xp[mask2], yp[mask2]
    n = 0
    model = np.empty(((len(gals) + len(srcs) + 1), imin.size))
    for gal in gals:
        gal.setPars()
        tmp = xc * 0.0
        tmp[mask2] = gal.pixeval(
            xin, yin, 1.0 / OVRS, csub=1
        )  # evaulate on the oversampled grid. OVRS = number of new pixels per old pixel.
        tmp = iT.resamp(tmp, OVRS, True)  # convert it back to original size
        tmp = convolve.convolve(tmp, psf, False)[0]
        model[n] = tmp[mask].ravel()
        n += 1
    for lens in lenses:
        lens.setPars()
    x0, y0 = pylens.lens_images(lenses, srcs, [xin, yin], 1.0 / OVRS, getPix=True)
    kk = 0
    for src in srcs:
        src.setPars()
        tmp = xc * 0.0
        tmp[mask2] = src.pixeval(x0, y0, 1.0 / OVRS, csub=1)
        tmp = iT.resamp(tmp, OVRS, True)
        tmp = convolve.convolve(tmp, psf, False)[0]
        model[n] = tmp[mask].ravel()
        n += 1
    model[n] = np.ones(model[n - 1].shape)
    rhs = imin / sigin  # data
    op = (model / sigin).T  # model matrix
    fit, chi = optimize.nnls(op, rhs)
    model = (model.T * fit).sum(1)
    resid = (model - imin) / sigin
    lp = -0.5 * (resid ** 2.0).sum()
    return lp