コード例 #1
0
    def logL(value=0., tmp=pars):
        """ Calculate log-likelihood probability.
        Minimise the variance in the source position from all images. """
        for lens in lenses:
            lens.setPars()
            if lens.b < 0:
                return -1e99

        x_src, y_src = {}, {}
        lnlike_dict = {}
        for name in names:
            x_src[name], y_src[name] = pylens.getDeflections(
                lenses, [img_xobs[name], img_yobs[name]], d[name])

            # CALC IMG POS
            xs = np.median(x_src[name])
            ys = np.median(y_src[name])

            # Assume gaussian surface brightness at (xs, ys)
            X1 = pymc.Uniform('X1', -1.e99, 1.e99, value=xs)
            Y1 = pymc.Uniform('Y1', -1.e99, 1.e99, value=ys)
            Q1 = pymc.Uniform('Q1', 0., 1., value=1.)
            P1 = pymc.Uniform('P1', -180., 180., value=0.)
            S1 = pymc.Uniform('N1', 0., 10000., value=6.)
            srcs = SBObjects.Gauss('', {
                'x': X1,
                'y': Y1,
                'q': Q1,
                'pa': P1,
                'sigma': S1
            })

            # Get Image plane
            x_src_all, y_src_all = pylens.getDeflections(lenses, [x, y],
                                                         d=d[name])
            image_plane = srcs.pixeval(x_src_all, y_src_all)
            image_indexes_pred = np.where(image_plane > threshold)
            image_coords_pred = np.array(
                [x[image_indexes_pred], y[image_indexes_pred]])
            num_pred_points = image_coords_pred.shape[1]
            num_obs_points = 10 * len(img_xobs[name])
            # if num_pred_points < num_obs_points:
            #     num_pred_points = num_obs_points
            penalise_more_points_weight = (num_pred_points / num_obs_points)

            lnlike_dict[name] = -0.5 * (x_src[name].var() + y_src[name].var()
                                        ) * (1 + penalise_more_points_weight)
        print(sum(lnlike_dict.values()), num_pred_points,
              num_obs_points)  #, [lens.b for lens in lenses])
        return sum(lnlike_dict.values())
コード例 #2
0
ファイル: pyplz_offsetpos.py プロジェクト: langeroodi/pyplz
    def optimize_amp(self):

        chi2sum = 0.

        for band in self.bands:

            lens_models = []
            for lens_model in self.lens_models:
                lens_models.append(lens_model[band])
            xl, yl = pylens.getDeflections(lens_models, (self.X, self.Y))

            lpix = []
            spix = []

            for light in self.light_sb_models:
                light[band].amp = 1.
                lpix.append(light[band].pixeval(self.X, self.Y))

            for source in self.source_sb_models:
                source[band].amp = 1.
                spix.append(source[band].pixeval(xl, yl))

            modlist = []
            for l in lpix:
                modlist.append(
                    (convolve.convolve(l, self.convol_matrix[band], False)[0] /
                     self.err[band]).ravel()[self.mask_r])
            for s in spix:
                modlist.append(
                    (convolve.convolve(s, self.convol_matrix[band], False)[0] /
                     self.err[band]).ravel()[self.mask_r])

            modarr = np.array(modlist).T
            if np.isnan(modarr).any() or not np.isfinite(modarr).any():
                amps = np.ones(self.nlight + self.nsource)
                chi = 1e300
            else:
                amps, chi = nnls(modarr, (self.sci[band] /
                                          self.err[band]).ravel()[self.mask_r])
            chi2sum += chi**2

            i = 0
            for light, mags in zip(self.light_sb_models, self.light_mags):
                if amps[i] > 0.:
                    light[band].amp = amps[i]
                    mags[band] = light[band].Mag(self.zp[band])
                else:
                    mags[band] = 99.
                i += 1

            for source, mags in zip(self.source_sb_models, self.source_mags):
                if amps[i] > 0.:
                    source[band].amp = amps[i]
                    mags[band] = source[band].Mag(self.zp[band])
                else:
                    mags[band] = 99.
                i += 1

        self.logp = -0.5 * chi2sum
        return chi2sum
コード例 #3
0
    def get_chi2(self):

        light_ind_model = []
        source_ind_model = []

        xl, yl = pylens.getDeflections(self.lens_models, (self.X, self.Y))

        model_array = (0. * self.scistack).ravel()[self.maskstack_r]

        for light, sed in zip(self.light_sb_models, self.light_sed_models):
            lmodel = 0. * self.scistack
            light.setAmpFromMag(sed.mags[self.main_band],
                                self.zp[self.main_band])
            if light.__class__.__name__ == 'PointSource':
                for i in range(self.nbands):
                    scale = sed.scale(self.bands[i], self.main_band)
                    lmodel[i * self.ny:(i + 1) * self.ny, :] = light.pixeval(
                        self.X, self.Y, self.bands[i])
            else:
                lpix = light.pixeval(self.X, self.Y)
                for i in range(self.nbands):
                    scale = sed.scale(self.bands[i], self.main_band)
                    lmodel[i * self.ny:(i + 1) *
                           self.ny, :] = scale * convolve.convolve(
                               lpix, self.convol_matrix[self.bands[i]],
                               False)[0]
            model_array += lmodel.ravel()[self.maskstack_r]

        for source, sed in zip(self.source_sb_models, self.source_sed_models):
            smodel = 0. * self.scistack
            source.setAmpFromMag(sed.mags[self.main_band],
                                 self.zp[self.main_band])
            spix = source.pixeval(xl, yl)
            for i in range(self.nbands):
                scale = sed.scale(self.bands[i], self.main_band)
                smodel[i * self.ny:(i + 1) *
                       self.ny, :] = scale * convolve.convolve(
                           spix, self.convol_matrix[self.bands[i]], False)[0]
            model_array += smodel.ravel()[self.maskstack_r]

        if self.sky is not None:
            skymodel = 0. * self.scistack
            for i in range(self.nbands):
                skymodel[i * self.ny:(i + 1) *
                         self.ny, :] = self.sky['amp_%s' % self.bands[i]].value
            model_array += skymodel.ravel()[self.maskstack_r]

        if np.isnan(model_array).any() or not np.isfinite(model_array).any():
            chi2 = 1e300
        else:
            chi2 = (
                (model_array - self.scistack.ravel()[self.maskstack_r])**2 /
                (self.errstack.ravel()[self.maskstack_r])**2).sum()

        self.logp = -0.5 * chi2
コード例 #4
0
    def logL(value=0., tmp=pars):
        for key in srcs:
            srcs[key].setPars()
        for lens in lenses:
            lens.setPars()
        lnlike = {}

        for name in names:
            # Calculate deflections
            # x, y = np.array([[img_xobs[name]], [img_yobs[name]]])
            x_src, y_src = pylens.getDeflections(lenses, [x, y], d[name])

            # Get list of predicted image coordinates
            image_plane = srcs[name].pixeval(x_src, y_src)
            image_indexes_pred = np.where(image_plane > threshold)
            image_coords_pred = np.array(
                [x[image_indexes_pred],
                 y[image_indexes_pred]])  # Only if brightness > threshold

            if not image_coords_pred.size:  # If it's an empty list
                return -1e30
            img_xpred, img_ypred = image_coords_pred

            # Map each observed image to the single closest predicted image
            pred_arg = []
            for xo, yo in zip(img_xobs[name], img_yobs[name]):
                xdist = np.abs(
                    img_xpred -
                    xo)  # pixel distance between xobs and xpredicted
                ydist = np.abs(img_ypred - yo)
                dist = xdist**2 + ydist**2
                pred_arg.append(
                    np.argmin(dist)
                )  # The index of the pred_img that the given observed image is closest to
            pred_arg = np.array(pred_arg)

            # these pred images are the ones that are being compared with the list of the obs images
            img_xpred_compare = np.array([img_xpred[i] for i in pred_arg])
            img_ypred_compare = np.array([img_ypred[i] for i in pred_arg])

            lnlike[name] = -0.5 * (np.sum(
                (img_xpred_compare - img_xobs[name])**2 +
                (img_ypred_compare - img_yobs[name])**2))

            # print(name, img_xpred_compare, lnlike[name], float(srcs[name].x), float(srcs[name].y), float(srcs[name].sigma), float(lens.x), float(lens.y), float(lens.b), float(lens.q), float(lens.pa))
            # print(name, img_ypred_compare, lnlike[name], float(srcs[name].x), float(srcs[name].y), float(srcs[name].sigma), float(lens.x), float(lens.y), float(lens.b), float(lens.q), float(lens.pa))

        print(sum(lnlike.values()), [(float(srcs[name].x), float(srcs[name].y),
                                      float(srcs[name].sigma))
                                     for name in names], float(lens.x),
              float(lens.y), float(lens.b), float(lens.q), float(lens.pa))

        return sum(lnlike.values())
コード例 #5
0
def plot_img_pos(pars, pix_scale=1., threshold=0.8, fits_file=None, img_xobs=None, img_yobs=None, d=None):
    xsrcA, ysrcA, sigsrcA, xlens, ylens, blens, qlens, plens = pars
    fig_dir = 'Figures/lensed_quasar/'
    sa = (0, 100)  # search area is 2000 pixels to 5000 pixels

    # Define source positions as a Guassian surface brightness profile
    X1, Y1, Q1, P1, S1, srcs = {}, {}, {}, {}, {}, {}
    X1['A'] = pymc.Uniform('X1A', 0., 100., value=xsrcA)
    Y1['A'] = pymc.Uniform('Y1A', 0., 100., value=ysrcA)
    Q1['A'] = pymc.Uniform('Q1A', 0.2, 1., value=1.)
    P1['A'] = pymc.Uniform('P1A', -180., 180., value=0.)
    S1['A'] = pymc.Uniform('N1A', 0., 6., value=sigsrcA)
    srcs['A'] = SBObjects.Gauss('', {'x': X1['A'], 'y': Y1['A'], 'q': Q1['A'],'pa': P1['A'], 'sigma': S1['A']})

    # Define lens mass model
    LX = pymc.Uniform('lx', 0., 100., value=xlens)
    LY = pymc.Uniform('ly', 0., 100., value=ylens)
    LB = pymc.Uniform('lb', 0., 100., value=blens)
    LQ = pymc.Uniform('lq', 0.2, 1., value=qlens)
    LP = pymc.Uniform('lp', -180., 180., value=plens)
    XB = pymc.Uniform('xb', -0.2, 0.2, value=0.)
    XP = pymc.Uniform('xp', -180., 180., value=0.)
    lens = MassModels.SIE('', {'x': LX, 'y': LY, 'b': LB, 'q': LQ, 'pa': LP})
    shear = MassModels.ExtShear('',{'x':LX,'y':LY,'b':XB,'pa':XP})
    lenses = [lens]

    x, y = np.meshgrid(np.arange(sa[0], sa[1], pix_scale), np.arange(sa[0], sa[1], pix_scale))

    image_plane, image_coords_pred = {}, {}
    for name in ['A']:
        x_src, y_src = pylens.getDeflections(lenses, [x, y], d=d[name])
        image_plane[name] = srcs[name].pixeval(x_src, y_src)
        plt.figure()
        plt.imshow(image_plane[name], interpolation='nearest', origin='lower')
        plt.xlabel('%dx - %d pixels' % (pix_scale, sa[0]))
        plt.ylabel('%dy - %d pixels' % (pix_scale, sa[0]))
        plt.savefig(os.path.join(ROOT_DIR, fig_dir, 'image_plane%s.png' % name))
        image_coords_pred[name] = np.add(np.multiply(np.where(image_plane[name] > threshold), pix_scale)[::-1], sa[0])

        lnlike, img_xpred_compare, img_ypred_compare = calc_lnlike(image_coords_pred[name], img_xobs[name], img_yobs[name])

        print(img_xpred_compare, img_xobs[name], lnlike)
        print(img_ypred_compare, img_yobs[name], lnlike)

    colors = (col for col in ['#1f77b4', '#2ca02c', '#9467bd', '#17becf', '#e377c2'])
    fig = plt.figure('image_and_position')
    plot_image(fits_file, figname='image_and_position', vmax=10.)
    plt.xlim(sa[0], sa[1])
    plt.ylim(sa[0], sa[1])
    for name in ['A']:
        plt.scatter(image_coords_pred[name][0], image_coords_pred[name][1], marker='.', alpha=0.3, c=next(colors))
    plt.savefig(os.path.join(ROOT_DIR, fig_dir, 'image_with_predicted_image_plane.png'))
コード例 #6
0
def doFit(p=None,doReg=True,updateReg=True,checkImgs=True,levMar=False):
    global reg
    # Check if using levMar-style parameters
    if p is not None:
        for i in range(len(p)):
            pars[i].value = p[i]
            # If the parameter is out-of-bounds return a bad fit
            try:
                a = pars[i].logp
            except:
                return iflt/sflt

    for l in lenses:
        l.setPars()
    xl,yl = pylens.getDeflections(lenses,coords)

    src.update(xl,yl,doReg=doReg)
    lmat = PSFm*src.lmat
    if doReg==True:
        rmat = src.rmat
    else:
        rmat = None
    nupdate = 0
    if doReg==True and updateReg==True:
        nupdate = 10
    res,fit,model,_,regg = aT.getModelG(ifltm,vfltm,lmat,cmatm,rmat,reg,nupdate)
    reg = regg[0]
    if checkImgs is False:
        if levMar:
            res = res**0.5+ifltm*0.
        return -0.5*res
    # This checks is images are formed outside of the masked region
    xl,yl = pylens.getDeflections(lenses,[xflt,yflt])
    oimg,pix = src.eval(xl,yl,fit,domask=False)
    oimg = PSF*oimg
    res = (iflt-oimg)/sflt
    if levMar:
        return res
    return -0.5*(res**2).sum()
コード例 #7
0
    def logL(value=0., tmp=pars):
        """ Calculate log-likelihood probability.
        Minimise the variance in the source position from all images. """
        for lens in lenses:
            lens.setPars()

        x_src, y_src = {}, {}
        lnlike_dict = {}

        for name in names:
            x_src[name], y_src[name] = pylens.getDeflections(lenses, [img_xobs[name], img_yobs[name]], d[name])
            lnlike_dict[name] = -0.5 * (x_src[name].var() + y_src[name].var())
        print(sum(lnlike_dict.values()), float(lenses[0].x), float(lenses[0].y), float(lenses[0].b), float(lenses[0].q), float(lenses[0].pa))
        return sum(lnlike_dict.values())
    def logL(value=0., tmp=pars):
        """ Calculate log-likelihood probability.
        Minimise the variance in the source position from all images. """
        for key in srcs:
            srcs[key].setPars()
        for lens in lenses:
            lens.setPars()
            if lens.b < 0:
                return -1e99

        x_src, y_src = {}, {}
        lnlike_dict = {}
        for name in names:
            # Get Image plane
            x_src_all, y_src_all = pylens.getDeflections(lenses, [x, y], d=d[name])
            image_plane = srcs.pixeval(x_src_all, y_src_all)
            image_indexes_pred = np.where(image_plane > threshold)
            image_coords_pred = np.array([x[image_indexes_pred], y[image_indexes_pred]])
            if not image_coords_pred.size:  # If it's an empty list
                return -1e30
            img_xpred, img_ypred = image_coords_pred

            num_pred_points = image_coords_pred.shape[1]
            num_obs_points = 10*len(img_xobs[name])
            penalise_more_points_weight = (num_pred_points/num_obs_points)

            # Map each observed image to the single closest predicted image
            pred_arg = []
            for xo, yo in zip(img_xobs[name], img_yobs[name]):
                xdist = np.abs(img_xpred - xo)  # pixel distance between xobs and xpredicted
                ydist = np.abs(img_ypred - yo)
                dist = xdist**2 + ydist**2
                pred_arg.append(np.argmin(dist))  # The index of the pred_img that the given observed image is closest to
            pred_arg = np.array(pred_arg)

            # these pred images are the ones that are being compared with the list of the obs images
            img_xpred_compare = np.array([img_xpred[i] for i in pred_arg])
            img_ypred_compare = np.array([img_ypred[i] for i in pred_arg])

            lnlike_dict[name] = -0.5 * (np.sum((img_xpred_compare - img_xobs[name]) ** 2 + (img_ypred_compare - img_yobs[name]) ** 2)) * (1+penalise_more_points_weight)

        print(sum(lnlike_dict.values()), num_pred_points, num_obs_points) #, [lens.b for lens in lenses])
        return sum(lnlike_dict.values())
コード例 #9
0
    def save(self, outname, make_rgb=True):

        fitsname = outname + '.fits'
        rgbname = outname + '_rgb.png'

        hdr = pyfits.Header()
        hdr['logp'] = self.logp

        light_ind_model = []
        source_ind_model = []

        xl, yl = pylens.getDeflections(self.lens_models, (self.X, self.Y))

        n = 0
        for light, sed in zip(self.light_sb_models, self.light_sed_models):

            light_ind_dic = {}

            if light.__class__.__name__ == 'PointSource':
                for band in self.bands:
                    hdr['%s.mag_%s' % (light.name, band)] = sed.mags[band]
                    scale = sed.scale(band, self.main_band)
                    light_ind_dic[band] = scale * light.pixeval(
                        self.X, self.Y, band)
            else:
                lpix = light.pixeval(self.X, self.Y)
                for band in self.bands:
                    hdr['%s.mag_%s' % (light.name, band)] = sed.mags[band]
                    scale = sed.scale(band, self.main_band)
                    light_ind_dic[band] = scale * convolve.convolve(
                        lpix, self.convol_matrix[band], False)[0]

            light_ind_model.append(light_ind_dic)

            n += 1

        for source, sed in zip(self.source_sb_models, self.source_sed_models):

            source_ind_dic = {}

            spix = source.pixeval(xl, yl)

            for band in self.bands:
                hdr['%s.mag_%s' % (source.name, band)] = sed.mags[band]
                scale = sed.scale(band, self.main_band)
                source_ind_here = scale * convolve.convolve(
                    spix, self.convol_matrix[band], False)[0]

                source_ind_dic[band] = source_ind_here

            source_ind_model.append(source_ind_dic)

            n += 1

        phdu = pyfits.PrimaryHDU(header=hdr)

        hdulist = pyfits.HDUList([phdu])

        for light, light_ind_dic in zip(self.light_sb_models, light_ind_model):

            for band in self.bands:
                hdu_here = pyfits.ImageHDU(data=light_ind_dic[band])
                hdu_here.header['EXTNAME'] = '%s_%s' % (light.name, band)

                hdulist.append(hdu_here)

        for source, source_ind_dic in zip(self.source_sb_models,
                                          source_ind_model):
            for band in self.bands:
                hdu_here = pyfits.ImageHDU(data=source_ind_dic[band])
                hdu_here.header['EXTNAME'] = '%s_%s' % (source.name, band)

                hdulist.append(hdu_here)

        if self.sky is not None:
            for band in self.bands:
                hdu_here = pyfits.ImageHDU(
                    data=self.sky['amp_%s' % band].value + 0. * self.sci[band])
                hdu_here.header['EXTNAME'] = 'sky_%s' % band
                hdulist.append(hdu_here)

        hdulist.writeto(fitsname, overwrite=True)

        if make_rgb:

            # makes model rgb
            sci_list = []
            light_list = []
            source_list = []
            for band in self.bands:
                sci_list.append(self.sci[band])
                lmodel = 0. * self.sci[band]
                smodel = 0. * self.sci[band]
                for light in light_ind_model:
                    lmodel += light[band]
                if self.sky is not None:
                    lmodel += self.sky['amp_%s' % band].value

                light_list.append(lmodel)
                for source in source_ind_model:
                    smodel += source[band]
                source_list.append(smodel)

            pyplz_rgbtools.make_full_rgb(sci_list,
                                         light_list,
                                         source_list,
                                         outname=rgbname)
コード例 #10
0
ym = y[mask]
coords = [xm,ym]

PSF = pT.getPSFMatrix(psf,img.shape)
PSFm = pT.maskPSFMatrix(PSF,mask)

iflt = img.flatten()
sflt = sig.flatten()
vflt = sflt**2

xflt = x.flatten()
yflt = y.flatten()

src = aT.AdaptiveSource(ifltm/sfltm,ifltm.size/Npnts)

xl,yl = pylens.getDeflections(lenses,coords)
src.update(xl,yl)
osrc = showRes(xl,yl,src,PSFm,img,sig,mask,ifltm,vfltm,cmatm,1e-5,1,400)
pylab.show()
'''

G,L,S,offsets,shear = numpy.load(guiFile)
pars = []
cov = []
lenses = []
for name in L.keys():
    model = L[name]
    lpars = {}
    for key in 'x','y','q','pa','b','eta':
        lo,hi = model[key]['lower'],model[key]['upper']
        val = dic[name+' '+key][a1,a2,a3]
コード例 #11
0
def plot_img_pos(pars,
                 pix_scale=1.,
                 threshold=0.8,
                 fits_file=None,
                 img_xobs=None,
                 img_yobs=None,
                 d=None,
                 fig_dir=None):
    names = img_xobs.keys()
    sa = (2000, 4500)  # search area is 2000 pixels to 5000 pixels

    xsrc, ysrc, sigsrc = {}, {}, {}
    for i, name in enumerate(names):
        xsrc[name], ysrc[name], sigsrc[name] = pars[3 * i:3 * (i + 1)]
    xlens, ylens, blens, qlens, plens = pars[-5:]

    # Define source positions as a Guassian surface brightness profile
    X1, Y1, Q1, P1, S1, srcs = {}, {}, {}, {}, {}, {}
    for name in names:
        X1[name] = pymc.Uniform('X1%s' % name, 0., 5000., value=xsrc[name])
        Y1[name] = pymc.Uniform('Y1%s' % name, 0., 5000., value=ysrc[name])
        Q1[name] = pymc.Uniform('Q1%s' % name, 0.2, 1., value=1.)
        P1[name] = pymc.Uniform('P1%s' % name, -180., 180., value=0.)
        S1[name] = pymc.Uniform('N1%s' % name, 0., 10000., value=sigsrc[name])
        srcs[name] = SBObjects.Gauss(
            '', {
                'x': X1[name],
                'y': Y1[name],
                'q': Q1[name],
                'pa': P1[name],
                'sigma': S1[name]
            })

    # Define lens mass model
    LX = pymc.Uniform('lx', 0., 5000., value=xlens)
    LY = pymc.Uniform('ly', 0., 5000., value=ylens)
    LB = pymc.Uniform('lb', 0., 5000., value=blens)
    LQ = pymc.Uniform('lq', 0.2, 1., value=qlens)
    LP = pymc.Uniform('lp', -180., 180., value=plens)
    XB = pymc.Uniform('xb', -0.2, 0.2, value=0.)
    XP = pymc.Uniform('xp', -180., 180., value=0.)
    lens = MassModels.SIE('', {'x': LX, 'y': LY, 'b': LB, 'q': LQ, 'pa': LP})
    shear = MassModels.ExtShear('', {'x': LX, 'y': LY, 'b': XB, 'pa': XP})
    lenses = [lens]

    x, y = np.meshgrid(np.arange(sa[0], sa[1], pix_scale),
                       np.arange(sa[0], sa[1], pix_scale))

    image_plane, image_coords_pred = {}, {}
    for name in names:
        x_src, y_src = pylens.getDeflections(lenses, [x, y], d=d[name])
        image_plane[name] = srcs[name].pixeval(x_src, y_src)
        plt.figure()
        plt.imshow(image_plane[name], interpolation='nearest', origin='lower')
        plt.xlabel('%dx - %d pixels' % (pix_scale, sa[0]))
        plt.ylabel('%dy - %d pixels' % (pix_scale, sa[0]))
        plt.savefig(os.path.join(ROOT_DIR, fig_dir,
                                 'image_plane%s.png' % name))
        image_indexes_pred = np.where(image_plane[name] > threshold)
        image_coords_pred[name] = np.array(
            [x[image_indexes_pred], y[image_indexes_pred]])
        print(name, image_coords_pred[name])

    colors = (col for col in
              ['#1f77b4', '#2ca02c', '#9467bd', '#17becf', '#e377c2', 'lime'])
    markers = (marker for marker in ['x', 'o', '*', '+', 'v', 'D'])
    fig = plt.figure('image_and_position', figsize=(13, 13))
    plot_image(fits_file, figname='image_and_position')
    plt.xlim(sa[0], sa[1])
    plt.ylim(sa[0], sa[1])
    for name in names:
        plt.scatter(img_xobs[name],
                    img_yobs[name],
                    marker=next(markers),
                    c='white',
                    label="%s obs" % name,
                    alpha=0.8)
        plt.scatter(image_coords_pred[name][0],
                    image_coords_pred[name][1],
                    marker='.',
                    alpha=0.5,
                    c=next(colors),
                    label=name)
    plt.legend(loc='upper right')
    plt.savefig(
        os.path.join(ROOT_DIR, fig_dir,
                     'image_with_predicted_image_plane.png'))
def plot_source_and_pred_lens_positions(pars, img_xobs, img_yobs, d, fig_dir, threshold=0.01, plotimage=False, fits_file=None, mass_pos=None, flux_dependent_b=False, masses_flux=None, sa=(2000, 4500), pix_scale=10.):
    if plotimage:
        fig = plt.figure('image_and_position', figsize=(13, 13))
        plot_image(fits_file, figname='image_and_position')
    names = img_xobs.keys()

    xsrc, ysrc, sigsrc = {}, {}, {}
    for i, name in enumerate(names):
        xsrc[name], ysrc[name], sigsrc[name] = pars[3 * i: 3 * (i + 1)]

    xlens, ylens, blens, qlens, plens = pars[-7:-2]

    # Define source positions as a Guassian surface brightness profile
    X1, Y1, Q1, P1, S1, srcs = {}, {}, {}, {}, {}, {}
    for name in names:
        X1[name] = pymc.Uniform('X1%s' % name, 0., 5000., value=xsrc[name])
        Y1[name] = pymc.Uniform('Y1%s' % name, 0., 5000., value=ysrc[name])
        Q1[name] = pymc.Uniform('Q1%s' % name, 0.2, 1., value=1.)
        P1[name] = pymc.Uniform('P1%s' % name, -180., 180., value=0.)
        S1[name] = pymc.Uniform('N1%s' % name, 0., 10000., value=sigsrc[name])
        srcs[name] = SBObjects.Gauss('', {'x': X1[name], 'y': Y1[name], 'q': Q1[name],'pa': P1[name], 'sigma': S1[name]})

    # Define lens mass model
    LX = pymc.Uniform('lx', 0., 5000., value=xlens)
    LY = pymc.Uniform('ly', 0., 5000., value=ylens)
    LB = pymc.Uniform('lb', 0., 5000., value=blens)
    LQ = pymc.Uniform('lq', 0., 1., value=qlens)
    LP = pymc.Uniform('lp', -180., 180., value=plens)
    lens = MassModels.SIE('', {'x': LX, 'y': LY, 'b': LB, 'q': LQ, 'pa': LP})
    lenses = [lens]

    if flux_dependent_b:
        for (lx, ly), flux in zip(mass_pos, masses_flux):
            slope, intercept = pars[-2:]
            LX = pymc.Uniform('lx', 0., 5000., value=lx)
            LY = pymc.Uniform('ly', 0., 5000., value=ly)
            LB = slope * np.log(flux) + intercept
            lens = MassModels.SIS('', {'x': LX, 'y': LY, 'b': LB})
            lenses += [lens]
            print('lens einstein radius', lens.b)
    else:
        for b, (lx, ly) in zip(pars[-2:], mass_pos):
            LX = pymc.Uniform('lx', 0., 5000., value=lx)
            LY = pymc.Uniform('ly', 0., 5000., value=ly)
            LB = pymc.Uniform('lb', 0., 5000., value=b)
            lens = MassModels.SIS('', {'x': LX, 'y': LY, 'b': LB})
            lenses += [lens]
            print('lens einstein radius', lens.b)

    colors = (col for col in ['#1f77b4', '#2ca02c', '#9467bd', '#17becf', '#e377c2', '#ADFF2F'])
    markers = (marker for marker in ['x', 'o', '*', '+', 'v', 'D'])

    x_src, y_src = {}, {}
    image_plane, image_coords_pred = {}, {}
    X1, Y1, Q1, P1, S1, srcs = {}, {}, {}, {}, {}, {}
    x, y = np.meshgrid(np.arange(sa[0], sa[1], pix_scale), np.arange(sa[0], sa[1], pix_scale))
    plt.xlim(sa[0], sa[1])
    plt.ylim(sa[0], sa[1])
    for name in names:
        plt.figure('image_and_position')

        col = next(colors)
        plt.scatter(img_xobs[name], img_yobs[name], marker=next(markers), c='white', label="%s obs" % name, alpha=0.8)
        plt.scatter(x_src[name], y_src[name], marker='.', alpha=0.5, c=col, label="%s pred src" % name)

        # Get Image plane
        x_src_all, y_src_all = pylens.getDeflections(lenses, [x, y], d=d[name])
        image_plane[name] = srcs[name].pixeval(x_src_all, y_src_all)
        image_indexes_pred = np.where(image_plane[name] > threshold)
        image_coords_pred[name] = np.array([x[image_indexes_pred], y[image_indexes_pred]])

        image_plane_norm = (image_plane[name] - image_plane[name].min())/(image_plane[name].max() - image_plane[name].min())
        rgba = np.zeros((len(image_coords_pred[name][0]), 4))
        rgba[:, 0:3] = list(int(col[i:i+2], 16)/256. for i in (1, 3, 5))
        rgba[:, 3] = 0.8 * np.array(image_plane_norm[image_indexes_pred])
        plt.scatter(image_coords_pred[name][0], image_coords_pred[name][1], marker='x', color=rgba, label="%s pred img" % name)
        plt.figure(name)
        plt.title(name)
        plt.imshow(image_plane[name], interpolation='nearest', origin='lower')

    print(x_src, y_src)
    plt.figure('image_and_position')
    plt.legend(loc='upper right')
    plt.savefig(os.path.join(fig_dir, 'image_with_contours_and_images.png'))
コード例 #13
0
ファイル: pyplz_offsetpos.py プロジェクト: langeroodi/pyplz
    def save(self, outname, make_rgb=True):

        fitsname = outname + '.fits'
        rgbname = outname + '_rgb.png'

        hdr = pyfits.Header()
        hdr['logp'] = self.logp

        light_ind_model = []
        source_ind_model = []

        xl, yl = pylens.getDeflections(self.lens_models, (self.X, self.Y))

        n = 0
        for light, mags in zip(self.light_sb_models, self.light_mags):

            light_ind_dic = {}
            for band in self.bands:
                light[band].amp = 1.
                lpix = light[band].pixeval(self.X, self.Y)
                hdr['%s.mag_%s' % (light[band].name, band)] = mags[band]
                scale = 10.**(-2. / 5. *
                              (mags[band] - light[band].Mag(self.zp[band])))

                light_ind_dic[band] = scale * convolve.convolve(
                    lpix, self.convol_matrix[band], False)[0]

            light_ind_model.append(light_ind_dic)

            n += 1

        xl = {}
        yl = {}
        for band in self.bands:
            lens_models = []
            for lens_model in self.lens_models:
                lens_models.append(lens_model[band])
            xl_here, yl_here = pylens.getDeflections(lens_models,
                                                     (self.X, self.Y))
            xl[band] = xl_here
            yl[band] = yl_here

        for source, mags in zip(self.source_sb_models, self.source_mags):

            source_ind_dic = {}

            for band in self.bands:
                source[band].amp = 1.
                spix = source[band].pixeval(xl[band], yl[band])

                hdr['%s.mag_%s' % (source[band].name, band)] = mags[band]
                scale = 10.**(-2. / 5. *
                              (mags[band] - source[band].Mag(self.zp[band])))
                source_ind_here = scale * convolve.convolve(
                    spix, self.convol_matrix[band], False)[0]

                source_ind_dic[band] = source_ind_here

            source_ind_model.append(source_ind_dic)

            n += 1

        phdu = pyfits.PrimaryHDU(header=hdr)

        hdulist = pyfits.HDUList([phdu])

        for light, light_ind_dic in zip(self.light_sb_models, light_ind_model):

            for band in self.bands:
                hdu_here = pyfits.ImageHDU(data=light_ind_dic[band])
                hdu_here.header['EXTNAME'] = '%s_%s' % (light[band].name, band)

                hdulist.append(hdu_here)

        for source, source_ind_dic in zip(self.source_sb_models,
                                          source_ind_model):
            for band in self.bands:
                hdu_here = pyfits.ImageHDU(data=source_ind_dic[band])
                hdu_here.header['EXTNAME'] = '%s_%s' % (source[band].name,
                                                        band)

                hdulist.append(hdu_here)

        hdulist.writeto(fitsname, overwrite=True)

        if make_rgb:

            # makes model rgb
            sci_list = []
            light_list = []
            source_list = []
            for band in self.bands:
                sci_list.append(self.sci[band])
                lmodel = 0. * self.sci[band]
                smodel = 0. * self.sci[band]
                for light in light_ind_model:
                    lmodel += light[band]
                light_list.append(lmodel)
                for source in source_ind_model:
                    smodel += source[band]
                source_list.append(smodel)

            pyplz_rgbtools.make_full_rgb(sci_list,
                                         light_list,
                                         source_list,
                                         outname=rgbname)
コード例 #14
0
ファイル: MapLenses.py プロジェクト: lindzlebean/pylathon
from pylens import MassModels,pylens
from scipy.special import gamma,gammainc
import itertools
import numpy as np, pylab as pl

sersic = lambda n,Re,k,R:  np.exp(-k*((R/Re)**(1./n))) * (k**(2.*n)) / (2.*np.pi*n*gamma(2.*n)*  gammainc(2.*n,k*(240./Re)**(1./n))  * Re**2)

x,y=np.linspace(-20,20,700),np.linspace(-20,20,700)
ii = np.array(list(itertools.product(x,y)))
lens = MassModels.PowerLaw('Lens1', {'x':0,'y':0,'q':1,'pa':0,'b':10,'eta':0.7})
xd,yd = pylens.getDeflections(lens,ii.T)
rl = np.sqrt(xd**2. + yd**2.)
SB = sersic(4,30,(2.*4-0.324), rl)

#pl.figure()
#pl.scatter(ii[:,0],ii[:,1],c=SB,edgecolors='none',s=100)
#pl.figure()
#pl.scatter(xd,yd,c=SB,edgecolors='none',s=100)

# caustic?
# source relative to galaxy?

DXs,DYs = np.linspace(0.1,1,3), np.linspace(0.1,1,3)
jj = np.array(list(itertools.product(DXs,DYs)))
for i in range(jj.shape[0]):
    DX,DY=jj[i]
    rl = np.sqrt((xd-DX)**2. + (yd-DY)**2.)
    SB = sersic(4,30,(2.*4-0.324), rl)
    pl.figure()
    pl.scatter(ii[:,0],ii[:,1],c=SB,edgecolors='none',s=100)
    pl.scatter(0,0,color='White')
コード例 #15
0
def plot_source_and_pred_lens_positions(pars, img_xobs, img_yobs, d, fig_dir, threshold=0.01, plotimage=False, fits_file=None):
    if plotimage:
        fig = plt.figure(figsize=(13, 13))
        plot_image(fits_file, fig)
    names = img_xobs.keys()
    try:
        xlens, ylens, blens, qlens, plens = pars
        bshear, pshear = 0., 0.
    except ValueError:  # includes shear
        xlens, ylens, blens, qlens, plens, bshear, pshear = pars

    # Define lens mass model
    LX = pymc.Uniform('lx', 0., 5000., value=xlens)
    LY = pymc.Uniform('ly', 0., 5000., value=ylens)
    LB = pymc.Uniform('lb', 0., 5000., value=blens)
    LQ = pymc.Uniform('lq', 0.2, 1., value=qlens)
    LP = pymc.Uniform('lp', -180., 180., value=plens)
    XB = pymc.Uniform('xb', -200., 200., value=bshear)
    XP = pymc.Uniform('xp', -180., 180., value=pshear)
    lens = MassModels.SIE('', {'x': LX, 'y': LY, 'b': LB, 'q': LQ, 'pa': LP})
    lenses = [lens]
    if len(pars) == 7:
        shear = MassModels.ExtShear('',{'x':LX,'y':LY,'b':XB,'pa':XP})
        lenses += [shear]

    colors = (col for col in ['#1f77b4', '#2ca02c', '#9467bd', '#17becf', '#e377c2', 'lime'])
    markers = (marker for marker in ['x', 'o', '*', '+', 'v', 'D'])

    x_src, y_src = {}, {}
    image_plane, image_coords_pred = {}, {}
    X1, Y1, Q1, P1, S1, srcs = {}, {}, {}, {}, {}, {}
    print(float(lens.x), float(lens.y), float(lens.b), float(lens.q), float(lens.pa))
    sa = (2000, 4500)
    pix_scale = 10.
    x, y = np.meshgrid(np.arange(sa[0], sa[1], pix_scale), np.arange(sa[0], sa[1], pix_scale))
    plt.xlim(sa[0], sa[1])
    plt.ylim(sa[0], sa[1])
    for name in names:
        x_src[name], y_src[name] = pylens.getDeflections(lenses, [img_xobs[name], img_yobs[name]], d[name])
        xs = np.median(x_src[name])
        ys = np.median(y_src[name])
        lnlike = -0.5 * (x_src[name].var() + y_src[name].var())
        print(float(lens.x), float(lens.y), float(lens.b), float(lens.q), float(lens.pa))
        print(name, xs, ys, lnlike)

        col = next(colors)
        plt.scatter(img_xobs[name], img_yobs[name], marker=next(markers), c='white', label="%s obs" % name, alpha=0.8)
        plt.scatter(x_src[name], y_src[name], marker='.', alpha=0.5, c=col, label="%s pred src" % name)

        # CALC IMG POS
        # Assume gaussian surface brightness at (xs, ys)
        X1[name] = pymc.Uniform('X1%s' % name, 0., 5000., value=xs)
        Y1[name] = pymc.Uniform('Y1%s' % name, 0., 5000., value=ys)
        Q1[name] = pymc.Uniform('Q1%s' % name, 0.2, 1., value=1.)
        P1[name] = pymc.Uniform('P1%s' % name, -180., 180., value=0.)
        S1[name] = pymc.Uniform('N1%s' % name, 0., 10000., value=6.)
        srcs[name] = SBObjects.Gauss('', {'x': X1[name], 'y': Y1[name], 'q': Q1[name], 'pa': P1[name], 'sigma': S1[name]})
        # Get Image plane
        x_src_all, y_src_all = pylens.getDeflections(lenses, [x, y], d=d[name])
        image_plane[name] = srcs[name].pixeval(x_src_all, y_src_all)
        image_indexes_pred = np.where(image_plane[name] > threshold)
        image_coords_pred[name] = np.array([x[image_indexes_pred], y[image_indexes_pred]])
        plt.scatter(image_coords_pred[name][0], image_coords_pred[name][1], marker='x', alpha=0.5, c=col, label="%s pred img" % name)

    print(x_src, y_src)
    plt.legend(loc='upper right')
    plt.savefig(os.path.join(fig_dir, 'image_with_contours_and_images.png'))