コード例 #1
0
ファイル: visualize.py プロジェクト: beckermr/metadetect-sims
def view_mbobs(mbobs, **kw):
    import images

    if len(mbobs) == 3:
        rgb = make_rgb(mbobs)
        plt = images.view(rgb, **kw)
    else:
        #rgb=fake_rgb(mbobs)
        # just show the first one
        #plt = images.view(mbobs[0][0].image, **kw)
        #plt=images.view(rgb, **kw)
        #imc = mbobs[0][0].image.clip(min=1.0e-6)

        imin = -95.0
        imax = 985.0
        imc = mbobs[0][0].image.copy()
        #imin, imax = imc.min(), imc.max()
        #print('min:',imin,'max:',imax)
        imc -= imin
        imc *= 1.0 / imax
        plt = images.view(imc, nonlinear=0.3)

        #imstd=imc.std()
        #imc.clip(min=-, out=imc)
        #logim=np.log10(imc)

        #imc -= imc.min() + 1.0e-6
        #logim=np.log10(imc)
        #imc *= 1.0/imc.max()
        #logim *= 1.0/logim.max()
        #plt = images.view(logim, **kw)

    return plt
コード例 #2
0
ファイル: imsim.py プロジェクト: esheldon/espy
    def show(self):
        import biggles

        levels=7
        tab = biggles.Table(2,2)
        tab[0,0] = images.view(self.image0, show=False, levels=levels, min=0)
        tab[0,1] = images.view(self.psf, show=False, levels=levels, min=0)
        tab[1,0] = images.view(self.image, show=False, levels=levels, min=0)

        # cross-section across rows
        cen = self['cen']
        imrows = self.image[:, cen[1]]
        imcols = self.image[cen[0], :]

        crossplt = biggles.FramedPlot()
        hrows = biggles.Histogram(imrows, color='blue')
        hrows.label = 'Center rows'
        hcols = biggles.Histogram(imcols, color='red')
        hcols.label = 'Center columns'

        key = biggles.PlotKey(0.1, 0.9, [hrows, hcols])

        crossplt.add(hrows, hcols, key)
        crossplt.aspect_ratio=1
        yr = crossplt._limits1().yrange()
        yrange = (yr[0], yr[1]*1.2)
        crossplt.yrange = yrange

        tab[1,1] = crossplt

        tab.show()
コード例 #3
0
ファイル: coadd.py プロジェクト: esheldon/meds
    def _show_epoch(self, iobj, icut, im, seg, wt, bmask, extra=None):
        import biggles
        import images

        tab=biggles.Table(2,2,aspect_ratio=1.0)

        tab[0,0] = images.view(im, title='im', show=False)
        tab[0,1] = images.view(seg, title='seg', show=False)
        tab[1,0] = images.view(wt, title='weight', show=False)
        tab[1,1] = images.view(bmask, title='bmask', show=False)
        
        d='plots'
        if not os.path.exists(d):
            try:
                os.makedirs(d)
            except:
                pass

        fname=[
            'object',
            '%06d' % iobj,
            '%02d' % icut,
        ]
        if extra is not None:
            fname += [extra]
        fname = '-'.join(fname)
        fname += '.png'
        fname=os.path.join(d, fname)

        #tab.show()
        print("    writing:",fname)
        tab.write_img(1500,1500,fname)
コード例 #4
0
ファイル: wrappers.py プロジェクト: esheldon/admom
def view2(im1,im2):
    import biggles
    import images
    tab = biggles.Table(1,2)

    p1 = images.view(im1,show=False)
    p2 = images.view(im2,show=False)

    tab[0,0] = p1
    tab[0,1] = p2
    tab.show()
コード例 #5
0
def _plot_compare_model(gmix, tobs):
    import biggles
    import images
    model_im = gmix.make_image(tobs.image.shape, jacobian=tobs.jacobian)
    imdiff = model_im - tobs.image
    tab = biggles.Table(2, 2, aspect_ratio=1.0)
    tab[0, 0] = images.view(tobs.image, show=False, title='im')
    tab[0, 1] = images.view(model_im, show=False, title='model')
    tab[1, 0] = images.view(imdiff, show=False, title='diff')
    tab.show()
    if input('hit a key (q to quit): ') == 'q':
        stop
コード例 #6
0
ファイル: observations.py プロジェクト: esheldon/nsim
def find_centroid(image, rng, offset=None, maxiter=200, ntry=4):
    """
    use AM to fit a single gaussian
    """


    dims = numpy.array(image.shape)
    row0, col0 = (dims-1)/2.0

    if offset is not None:
        row0 += offset['row_offset']
        col0 += offset['col_offset']


    if False:
        import images
        images.multiview(image, width=800,height=800)
        if 'q'==raw_input('hit a key: '):
            stop



    j=ngmix.UnitJacobian(row=row0, col=col0)

    obs = ngmix.Observation(image, jacobian=j)

    guess_T = 4.0
    for i in xrange(ntry):
        fitter = ngmix.admom.run_admom(obs, guess_T, rng=rng)

        res=fitter.get_result()
        if res['flags']==0:
            break

    if res['flags'] != 0:
        if False:
            import images
            images.view(image, width=800,height=800)
            if 'q'==raw_input('hit a key: '):
                stop

        raise TryAgainError("could not fit 1 gauss to get centroid")

    pars=res['pars']
    row=pars[0]
    col=pars[1]

    row = row0 + row
    col = col0 + col

    return row,col
コード例 #7
0
ファイル: vis.py プロジェクト: esheldon/fitvd
def view_mbobs_list(fofid, mbobs_list, **kw):
    import biggles
    import images
    import plotting

    show = kw.get('show', False)
    save = kw.get('save', False)

    for i, mbobs in enumerate(mbobs_list):
        id = mbobs[0][0].meta['id']

        for band, obslist in enumerate(mbobs):

            grid = plotting.Grid(len(obslist))
            plt = biggles.Table(
                grid.nrow,
                grid.ncol,
            )
            aratio = grid.nrow/(grid.ncol*2)
            plt.aspect_ratio = aratio
            plt.title = 'FoF: %d id: %d band: %d' % (fofid, id, band)

            for iobs, obs in enumerate(obslist):

                im = obs.image
                wt = obs.weight

                im = im/im.max()

                row, col = grid(iobs)

                implt = images.view(im, nonlinear=0.4, show=False)
                wtplt = images.view(wt, show=False)

                tab = biggles.Table(1, 2)
                tab[0, 0] = implt
                tab[0, 1] = wtplt

                tab.title = 'id: %d band: %d obs: %d' % (id, band, iobs)
                plt[row, col] = tab

            if save:
                pltname = 'images-fof%06d-id%06d-band%d.png' % \
                    (fofid, id, band)
                logger.info('writing: %s' % pltname)
                plt.write_img(3000, 3000*aratio, pltname)

            if show:
                plt.show(width=2000, height=2000*aratio)

    return plt
コード例 #8
0
    def _get_mof_obs(self):
        im, psf_im, coords, dims, dx1, dy1, noises = self.sim()

        bg_rms = self.sim['Image']['Bgrms'] / np.sqrt(len(im))
        bg_rms_psf = self.sim['Psf']['Bgrms_psf']

        psf_ccen = (np.array(psf_im.shape) - 1.0) / 2.0
        psf_jacob = ngmix.UnitJacobian(
            row=psf_ccen[0],
            col=psf_ccen[1],
        )
        psf_weight = psf_im * 0 + 1.0 / bg_rms_psf**2
        psf_obs = ngmix.Observation(
            psf_im,
            weight=psf_weight,
            jacobian=psf_jacob,
        )

        psf_gmix = self._fit_psf_admom(psf_obs)
        psf_obs.set_gmix(psf_gmix)

        mb = MultiBandObsList()
        for i in range(len(im)):
            if self.show:
                import images
                tim = im[i] / im[i].max()
                tim = np.log10(tim - tim.min() + 1.0)

                images.view(tim)
                if 'q' == input('hit a key: (q to quit) '):
                    stop

            weight = im[i] * 0 + 1.0 / bg_rms**2
            jacobian = ngmix.UnitJacobian(
                row=0,
                col=0,
            )

            obs = ngmix.Observation(
                im[i],
                weight=weight,
                jacobian=jacobian,
                psf=psf_obs,
            )
            obs.noise = noises[i]
            olist = ObsList()
            olist.append(obs)
            mb.append(olist)

        return mb, coords
コード例 #9
0
ファイル: vis.py プロジェクト: esheldon/fofx
def plot_seg(segin, width=1000, rng=None, show=False, **kw):
    """
    plot the seg map with randomized colors for better display
    """
    import images

    if rng is None:
        rng = np.random.RandomState()

    seg = np.transpose(segin)

    max_seg = seg.max()

    low = 50 / 255
    high = 255 / 255
    n = (max_seg + 1) * 3
    colors = rng.uniform(low=low, high=high, size=n).reshape(
        (max_seg + 1, 3), )

    cseg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype='f4')

    _make_color_seg(seg, cseg, colors)

    plt = images.view(cseg, show=False, **kw)

    if show:
        srat = seg.shape[1] / seg.shape[0]
        plt.show(width=width, height=width * srat)

    return plt
コード例 #10
0
def view_peaks(*,
               image,
               noise,
               objects,
               show=False,
               color='red',
               type='filled circle',
               width=800,
               plt=None):
    """
    view the image with peak positions overplotted
    """
    import biggles
    import images

    tim = image.copy()

    if plt is None:
        aim = images.asinh_scale(image, noise=noise)
        plt = images.view(aim, show=False)

    # the viewer transposes the image
    points = biggles.Points(
        objects['col'],
        objects['row'],
        color=color,
        type=type,
    )
    plt.add(points)

    if show:
        arat = image.shape[0] / image.shape[1]
        plt.show(width=width, height=width * arat)

    return plt
コード例 #11
0
    def get_mof_model(self):
        mb, coords = self._get_mof_obs()
        prior = self._get_mof_prior(coords, len(mb))

        nobj = len(coords)
        mm = minimof.MOF(mb, "bdf", nobj, prior=prior)
        print(mm)
        for i in range(2):
            guess = self._get_mof_guess(coords, mb)
            ngmix.print_pars(guess, front="    guess:")
            mm.go(guess)
            res = mm.get_result()
            if res['flags'] == 0:
                break

        if res['flags'] == 0:
            ngmix.print_pars(res['pars'], front="      fit:")
            center_obs = mm.make_corrected_obs(0,
                                               band=None,
                                               obsnum=None,
                                               recenter=True)
            for i in range(len(center_obs)):
                center_obs[i][0].noise = mb[i][0].noise

            if self.show:
                import images
                cim = center_obs.image
                s = cim.shape
                tim = np.zeros((s[0], 2 * s[1]))

                tim[:, 0:s[1]] = obs.image
                tim[:, s[1]:] = cim
                tim *= 1.0 / tim.max()
                tim = np.log10(tim - tim.min() + 1.0)

                images.view(
                    #tim-tim.min(),
                    tim,
                    title='MOF',
                )
                if 'q' == input('hit a key: (q to quit) '):
                    stop

        else:
            center_obs = None

        return center_obs
コード例 #12
0
def view_rgb(imlist, wtlist, scale=2, show=False, **kw):
    """
    view rgb data
    """
    import images

    rgb = make_rgb(imlist, wtlist, scale=scale)
    plt = images.view(rgb, show=show, **kw)
    return plt
コード例 #13
0
ファイル: plotting.py プロジェクト: esheldon/espy
def plot_hist2d(x, y, **kw):
    """
    create a 2-d histogram of the data and view it


    parameters
    ----------
    x: array
        x data
    y: array
        y data

    log: bool
        If true, plot the log of the histogram, default
        True
    xlabel: string
        label for x axis
    ylabel: string
        label for y axis

    **kw:
        keywords for the histogram2d routine

    dependencies
    ------------
    esutil
    images
    """
    import images

    dolog=kw.pop('log',True)

    kw['more']=True
    hdict = eu.stat.histogram2d(x, y, **kw)

    hist = hdict['hist']
    if dolog:
        hist = numpy.log10( hist.clip(min=0.1) )

    kw['transpose'] = False
    kw['ranges'] = hdict['ranges']

    # we want exact ranges here, to avoid confusing areas
    # of black where there is no histogram
    kw['xrange'] = [hdict['ranges'][0][0], hdict['ranges'][1][0]]
    kw['yrange'] = [hdict['ranges'][0][1], hdict['ranges'][1][1]]

    plt = images.view(hist, **kw)

    return plt
コード例 #14
0
def plot_seg(segin, title=None, width=1000, rng=None, show=False):
    """
    plot the seg map with randomized colors
    """
    import images

    seg = np.transpose(segin)

    cseg = np.zeros((seg.shape[0], seg.shape[1], 3))

    if rng is None:
        rng = np.random.RandomState()

    useg = np.unique(seg)[1:]

    low = 50 / 255
    high = 255 / 255

    for i, segval in enumerate(useg):

        w = np.where(seg == segval)

        r, g, b = rng.uniform(low=low, high=high, size=3)

        cseg[w[0], w[1], 0] = r
        cseg[w[0], w[1], 1] = g
        cseg[w[0], w[1], 2] = b

    plt = images.view(cseg, show=False)

    if title is not None:
        plt.title = title

    if show:
        srat = seg.shape[1] / seg.shape[0]
        fname = tempfile.mktemp(suffix='.png')
        plt.write_img(width, width * srat, fname)
        show_image(fname)

    return plt
コード例 #15
0
ファイル: regauss.py プロジェクト: esheldon/espy
    def show(self, min=0, **keys):
        import fimage
        import biggles
        plt=images.view(self.im, show=False, min=min, **keys)
        s=self.rg['imstats']

        if s['whyflag'] == 0:
            levels=7

            wrow = s['wrow']
            wcol = s['wcol']

            model = fimage.model_image('gauss',
                                       self.im.shape,
                                       [wrow,wcol],
                                       [s['Irr'],s['Irc'],s['Icc']],
                                       counts=self.im.sum())

            cmod = biggles.Contours(model.transpose(), color='grey')
            cmod.levels = levels
            plt.add(cmod)
        plt.show()
コード例 #16
0
ファイル: util.py プロジェクト: esheldon/gmix_image
def _plot_gmix_thresh(im, cen, thresh, prompt=False):
    import images
    import biggles

    tab=biggles.Table(1,2)
    plt=biggles.FramedPlot()

    im_cenrows = im[:,cen[1]]
    im_cencols = im[cen[0],:]

    wrow,=numpy.where(im_cenrows >= thresh)
    wcol,=numpy.where(im_cencols >= thresh)

    hrow=biggles.Histogram(im_cenrows, x0=0, binsize=1,color='blue')
    hcol=biggles.Histogram(im_cencols, x0=0, binsize=1,color='red')
    plt.add(hrow,hcol)

    if wrow.size > 0:
        hrow_t=biggles.Histogram(im_cenrows[wrow], x0=wrow[0], binsize=1,
                                 color='blue',width=2)
        plt.add(hrow_t)
    if wcol.size > 0:
        hcol_t=biggles.Histogram(im_cencols[wcol], x0=wcol[0], binsize=1,
                                 color='red',width=2)
        plt.add(hcol_t)

    plt.title='thresh: %.2f' % thresh
    plt.aspect_ratio=1

    implt=images.view(im,show=False,type='dens-cont')
    tab[0,0]= implt
    tab[0,1] = plt
    tab.show()

    if prompt:
        key=raw_input('hit a key (q to quit): ')
        if key=='q':
            stop
コード例 #17
0
ファイル: toy.py プロジェクト: esheldon/metadetect-paper
def main():

    args = get_args()

    o1, o2 = get_objects(args)
    psf = get_psf()

    if args.no_full_scene:
        name = 'toy-no-full-scene'

        allo = galsim.Add(
            o1.shift(dx=-SHIFT, dy=0.0),
            o2.shift(dx=+SHIFT, dy=0.0),
        )
        allo_pre = galsim.Convolve(
            allo,
            psf,
        )


        o1_pre = galsim.Convolve(o1, psf).shear(
            g1=SHEAR[0],
            g2=SHEAR[1],
        )
        o2_pre = galsim.Convolve(o2, psf).shear(
            g1=SHEAR[0],
            g2=SHEAR[1],
        )
        o1_pre = o1_pre.shift(dx=-SHIFT, dy=0.0)
        o2_pre = o2_pre.shift(dx=+SHIFT, dy=0.0)
        allo_pre_sheared = galsim.Add(o1_pre, o2_pre)

        o1_post = o1.shear(
            g1=SHEAR[0],
            g2=SHEAR[1],
        )
        o2_post = o2.shear(
            g1=SHEAR[0],
            g2=SHEAR[1],
        )
        o1_post = galsim.Convolve(o1_post, psf)
        o2_post = galsim.Convolve(o2_post, psf)

        o1_post = o1_post.shift(dx=-SHIFT, dy=0.0)
        o2_post = o2_post.shift(dx=+SHIFT, dy=0.0)

        allo_post_sheared = galsim.Add(o1_post, o2_post)

    else:
        name = 'toy'

        allo = galsim.Add(o1, o2)
        allo_pre = galsim.Convolve(
            allo,
            psf,
        )


        allo_pre = galsim.Convolve(
            allo,
            psf,
        )
        allo_pre_sheared = allo_pre.shear(
            g1=SHEAR[0],
            g2=SHEAR[1],
        )

        allo_post = galsim.Add(o1, o2).shear(
            g1=SHEAR[0],
            g2=SHEAR[1],
        )
        allo_post_sheared = galsim.Convolve(
            allo_post,
            psf,
        )

    im_pre = get_image(allo_pre)
    im_pre_sheared = get_image(allo_pre_sheared)
    im_post_sheared = get_image(allo_post_sheared)

    plt_pre = images.view(
        im_pre,
        type='dens-cont',
        ccolor=CCOLOR,
        levels=LEVELS,
        zrange=np.percentile(im_pre, ZPERC),
        invert=True,
        show=False,
    )

    plt_pre_sheared = images.view(
        im_pre_sheared,
        type='dens-cont',
        ccolor=CCOLOR,
        levels=LEVELS,
        zrange=np.percentile(im_pre_sheared, ZPERC),
        invert=True,
        show=False,
    )

    plt_post_sheared = images.view(
        im_post_sheared,
        type='dens-cont',
        ccolor=CCOLOR,
        levels=LEVELS,
        zrange=np.percentile(im_post_sheared, ZPERC),
        invert=True,
        show=False,
    )

    plt_pre.add(
        biggles.PlotLabel(0.9, 0.9, '(a)', halign='right', color='black')
    )
    plt_pre_sheared.add(
        biggles.PlotLabel(0.9, 0.9, '(b)', halign='right', color='black')
    )
    plt_post_sheared.add(
        biggles.PlotLabel(0.9, 0.9, '(c)', halign='right', color='black')
    )

    tab = biggles.Table(1, 3, aspect_ratio=1/3)

    tab[0, 0] = plt_pre
    tab[0, 1] = plt_pre_sheared
    tab[0, 2] = plt_post_sheared

    tab.show()
    tab.write('%s.pdf' % name)
    tab.write('%s.png' % name, dpi=150)
コード例 #18
0
ファイル: plot-map.py プロジェクト: esheldon/espy
def main():
    import biggles
    biggles.configure('screen','width',1920)
    biggles.configure('screen','height',1200)

    tiledata=read_tiles()

    image, ra, dec = get_map_image()
    #images.view(image-image.min(),transpose=True)
    plt=images.view(image-image.min(),
                    xdr=[ra.min(), ra.max()],
                    ydr=[dec.min(), dec.max()],
                    transpose=False,
                    show=False)

    pts=biggles.Points(tiledata['ra'], tiledata['dec'],
                       type='filled circle', color='steel blue',
                       size=0.25)
    plt.add(pts)

    shoff=0.01
    #shoff=0.008
    for i in xrange(tiledata.size):
        ra=tiledata['ra'][i]
        dec=tiledata['dec'][i]
        tilename=tiledata['tilename'][i]
        if (    (spte_ra_range[0] < ra < spte_ra_range[1])
            and (spte_dec_range[0] < dec < spte_dec_range[1]) ):

            if tilename.strip() in testbed_tiles:
                color='green'
            else:
                color='red'
            dark_lab=biggles.DataLabel(ra,
                                       dec+0.05,
                                       tilename,
                                       color='black',
                                       size=0.3)

            plt.add(dark_lab)
            light_lab=biggles.DataLabel(ra-shoff,
                                        dec+0.05+shoff,
                                        tilename,
                                        color=color,
                                        size=0.3)
            plt.add(light_lab)

    plt.xrange=spte_ra_range
    plt.yrange=spte_dec_range
    plt.x1.ticks_style['color']='white'
    plt.x1.subticks_style['color']='white'
    plt.x1.spine_style['color']='white'

    plt.x2.ticks_style['color']='white'
    plt.x2.subticks_style['color']='white'
    plt.x2.spine_style['color']='white'

    plt.y1.ticks_style['color']='white'
    plt.y1.subticks_style['color']='white'
    plt.y1.spine_style['color']='white'

    plt.y2.ticks_style['color']='white'
    plt.y2.subticks_style['color']='white'
    plt.y2.spine_style['color']='white'

    epsname="map.eps"
    print("writing:",epsname)
    plt.write_eps(epsname)
コード例 #19
0
def _test_nobj(nobj, seed, show=False):
    """
    simulate one object
    """

    detband = 0
    conf = _get_conf(nobj)

    sim = Sim(conf, seed)
    sim.make_obs()
    if show:
        import images
        images.view(sim.obs[0][0].image)
        if raw_input('hit a key: (q to quit): ') == 'q':
            raise KeyboardInterrupt('stopping')

    fitrng = np.random.RandomState(sim.rng.randint(0, 2**15))

    # this runs sextractor
    medser = sim.get_medsifier()

    m2 = medser.get_meds(detband)
    objects = m2.get_cat()
    nobj = len(objects)
    if nobj == 0:
        print('found no objects')
        return

    m = medser.get_multiband_meds()
    list_of_obs = []
    for iobj in range(objects.size):
        mbo = m.get_mbobs(iobj, weight_type='weight')

        for olist in mbo:
            for o in olist:
                o.set_psf(sim.psf_obs)

        list_of_obs.append(mbo)

    # first do a fit
    prior = get_mof_stamps_prior(
        list_of_obs,
        conf['fit_model'],
        fitrng,
    )
    fitter = MOFStamps(
        list_of_obs,
        conf['fit_model'],
        prior=prior,
        lm_pars=LM_PARS,
    )
    guess = get_stamp_guesses(
        list_of_obs,
        detband,
        conf['fit_model'],
        fitrng,
    )

    for itry in range(2):
        fitter.go(guess)
        res = fitter.get_result()
        if res['flags'] == 0:
            break

    if res['flags'] != 0:
        raise RuntimeError('didnt find a fit')

    print('-' * 70)
    print('best fit pars for all objects')
    print('object   pars')
    for i in range(nobj):
        ores = fitter.get_object_result(i)
        s2n = ores['s2n']
        ngmix.print_pars(ores['pars'],
                         front='%d s2n: %.1f pars: ' % (i + 1, s2n))

    ffitter = MOFFlux(list_of_obs, conf['fit_model'], res['pars'])
    ffitter.go()

    fres = ffitter.get_result()
    if np.any(fres['flags'] != 0):
        print('didnt find a linear fit')
        return np.zeros(0), np.zeros(0)

    print('-' * 70)
    print('flux comparison')
    print('object   flux   flux_err  fflux  fflux_err')

    fluxes = np.zeros(nobj)
    flux_errs = np.zeros(nobj)

    for i in range(nobj):
        ores = fitter.get_object_result(i)
        fres = ffitter.get_object_result(i)
        print(
            'object:',
            i + 1,
            'flux:',
            ores['flux'][0],
            'flux_err:',
            ores['flux_err'][0],
            'fflux:',
            fres['flux'][0],
            'fflux_err:',
            fres['flux_err'][0],
        )

        fluxes[i] = fres['flux'][0]
        flux_errs[i] = fres['flux_err'][0]

    return fluxes, flux_errs
コード例 #20
0
ファイル: mag_dep_psf.py プロジェクト: esheldon/gmix_meds
    def _get_star_data(self, iobj, icutout):
        """
        We use a fixed size apertures for all stars but only process stars for
        which there are no neighbors in that aperture and for which there are
        not zero weights in that aperture.

        The smallest cutout we do is 32x32 so we will use a sub region
        of that to allow for pixel shifts, 25x25.  Then the region is
        rowcen-r1, colcen+r1 where r1 is (25-1)/2 = 12
        """

        defres=None,None,[]

        box_size=29
        rsub=(box_size-1)//2

        image0=self.meds.get_cutout(iobj,icutout)
        wt0=self.meds.get_cutout(iobj,icutout,type='weight')
        seg0=self.meds.get_cutout(iobj,icutout,type='seg')

        rowcen=self.meds['cutout_row'][iobj,icutout]
        colcen=self.meds['cutout_col'][iobj,icutout]

        sid=seg0[rowcen,colcen]

        # fix up compression issue

        """
        w=numpy.where(seg == sid)
        if w[0].size ==0:
            return defres
        rowmin=w[0].min()
        rowmax=w[0].max()
        colmin=w[1].min()
        colmax=w[1].max()
        """

        rowmin = int(rowcen) - rsub
        rowmax = int(rowcen) + rsub
        colmin = int(colcen) - rsub
        colmax = int(colcen) + rsub

        if ((rowmin < 0)
                or (rowmax > image0.shape[0])
                or (colmin < 0)
                or (colmax > image0.shape[1]) ):
            print >>stderr,'    hit bounds'
            return defres


        rowcen -= rowmin
        colcen -= colmin

        image = image0[rowmin:rowmax+1, colmin:colmax+1]
        wt    =    wt0[rowmin:rowmax+1, colmin:colmax+1]
        seg   =   seg0[rowmin:rowmax+1, colmin:colmax+1]

        if False:
            import images
            import biggles
            tab=biggles.Table(1,2)
            w0=numpy.where(wt0 < 0.2*wt0.max())
            if w0[0].size != 0:
                image0[w0] = 0
            w=numpy.where(wt < 0.2*wt.max())
            if w[0].size != 0:
                image[w] = 0

            nl=0.05
            tab[0,0]=images.view(image0,nonlinear=nl,title='raw',show=False)
            tab[0,1]=images.view(image,nonlinear=nl,title='cut',show=False)
            tab.show()
            resp=raw_input('hit enter (q to quit): ')
            if resp.lower() == 'q':
                stop

        # we don't work with images that have zero weight
        # in the image anywere because the EM code doesn't
        # have that feature
        # have to deal with noisy "zero" weights
        # also no pixels from other objects in our box
        wt_logic  =  ( wt < 0.2*wt.max()  )
        seg_logic = ( (seg != sid) & (seg != 0) )
        w_wt  = numpy.where(wt_logic)
        w_seg = numpy.where(seg_logic)

        if w_wt[0].size > 0:
            print >>stderr,'    ',iobj,'has',w_wt[0].size,'zero weight pixels'
            return None,None,[]
        if w_seg[0].size > 0:
            print >>stderr,'    ',iobj,'has',w_seg[0].size,'neighbor pixels'
            return None,None,[]


        ivar=numpy.median(wt)
        return image, ivar, [rowcen,colcen]
コード例 #21
0
ファイル: lmfit.py プロジェクト: esheldon/gmix_meds
 def _show_coadd(self):
     import images
     images.view(self.coadd)
コード例 #22
0
ファイル: regauss.py プロジェクト: esheldon/espy
def admom_atlas(type, run, camcol, field, id, filter, 
                objs=None,
                show=False, showmin=0, **keys):
    """
    Objs must be for this camcol!
    """
    import admom
    import sdsspy

    c = sdsspy.FILTERNUM[filter]

    if objs is None:
        sc=SweepCache()
        obj = sc.readobj(type, run, camcol, field, id)
    else:
        w=where1( (objs['field'] == field) & (objs['id'] == id) )
        if w.size == 0:
            raise ValueError("Object not found objs: "
                             "%06i-%i-%04i" % (run,camcol,id))
        obj = objs[w[0]]

    atls = sdsspy.read('fpAtlas',run,camcol,field,id, trim=True)
    im = numpy.array( atls['images'][c], dtype='f8') - atls['SOFT_BIAS']

    psfield = sdsspy.read('psField', run, camcol, field, lower=True)

    rowc=obj['rowc'][c]
    colc=obj['colc'][c]

    row=rowc - atls['row0'][c] - 0.5
    col=colc - atls['col0'][c] - 0.5

    sigsky = psfield['skysig'][0,c]
    Tguess_psf=admom.fwhm2mom( obj['psf_fwhm'][c], pixscale=0.4)
    if obj['m_rr_cc'][c] > Tguess_psf:
        Tguess=obj['m_rr_cc'][c]
    else:
        Tguess=Tguess_psf

    out = admom.admom(im,
                      row, 
                      col, 
                      sky=0.0,
                      sigsky=sigsky,
                      Tguess=Tguess)

    if show:
        import fimage
        import biggles
        plt=images.view(im, min=showmin, show=False, **keys)

        if out['whyflag'] == 0:
            levels=7

            wrow = out['wrow']
            wcol = out['wcol']

            model = fimage.model_image('gauss',
                                       im.shape,
                                       [wrow,wcol],
                                       [out['Irr'],out['Irc'],out['Icc']],
                                       counts=im.sum())


            cmod = biggles.Contours(model.transpose(), color='grey')
            cmod.levels = levels
            plt.add(cmod)
        plt.show()

    return out
コード例 #23
0
ファイル: mcm_sim.py プロジェクト: esheldon/espy
    def _doplots(self):
        import mcmc
        import biggles
        import esutil as eu

        biggles.configure("default","fontsize_min",1.2)
        tab=biggles.Table(6,2)

        cen1vals=self._trials[:,0]
        cen2vals=self._trials[:,1]
        Tvals=self._trials[:,4]
        g1vals=self._trials[:,2]
        g2vals=self._trials[:,3]
        g1lab=r'$g_1$'
        g2lab=r'$g_2$'

        ampvals=self._trials[:,5]

        ind=numpy.arange(g1vals.size)

        burn_cen=biggles.FramedPlot()
        cen1p=biggles.Curve(ind, cen1vals, color='blue')
        cen2p=biggles.Curve(ind, cen2vals, color='red')
        cen1p.label=r'$x_1$'
        cen2p.label=r'$x_2$'
        burn_cen.add(cen1p)
        burn_cen.add(cen2p)
        key=biggles.PlotKey(0.9,0.9,[cen1p,cen2p],halign='right')
        burn_cen.add(key)
        burn_cen.ylabel='cen'

        burn_g1=biggles.FramedPlot()
        burn_g1.add(biggles.Curve(ind, g1vals))
        burn_g1.ylabel=r'$g_1$'

        burn_g2=biggles.FramedPlot()
        burn_g2.add(biggles.Curve(ind, g2vals))
        burn_g2.ylabel=r'$g_2$'

        burn_T=biggles.FramedPlot()
        burn_T.add(biggles.Curve(ind, Tvals))
        burn_T.ylabel='T'

        burn_amp=biggles.FramedPlot()
        burn_amp.add(biggles.Curve(ind, ampvals))
        burn_amp.ylabel='Amplitide'



        likep = biggles.FramedPlot()
        likep.add( biggles.Curve(ind, self.lnprobs) )
        likep.ylabel='ln( prob )'


        g = self._result['g']
        gcov = self._result['gcov']
        errs = sqrt(diag(gcov))

        res=self.get_result()
        print 's2n weighted:',res['s2n_w']
        print 'acceptance rate:',res['arate'],'mca_a',self.mca_a
        print 'T:  %.16g +/- %.16g' % (Tvals.mean(), Tvals.std())

        print_pars(self._result['pars'])
        print_pars(sqrt(diag(self._result['pcov'])))
        print 'g1: %.16g +/- %.16g' % (g[0],errs[0])
        print 'g2: %.16g +/- %.16g' % (g[1],errs[1])
        print 'chi^2/dof: %.3f/%i = %f' % (res['chi2per']*res['dof'],res['dof'],res['chi2per'])
        print 'probrand:',res['fit_prob']

        cenw = cen1vals.std()
        cen_bsize=cenw*0.2
        hplt_cen0 = eu.plotting.bhist(cen1vals,binsize=cen_bsize,
                                      color='blue',
                                      show=False)
        hplt_cen = eu.plotting.bhist(cen2vals,binsize=cen_bsize,
                                     color='red',
                                     show=False, plt=hplt_cen0)
        hplt_cen.add(key)

        bsize1=g1vals.std()*0.2 #errs[0]*0.2
        bsize2=g2vals.std()*0.2 # errs[1]*0.2
        hplt_g1 = eu.plotting.bhist(g1vals,binsize=bsize1,
                                  show=False)
        hplt_g2 = eu.plotting.bhist(g2vals,binsize=bsize2,
                                  show=False)

        Tsdev = Tvals.std()
        Tbsize=Tsdev*0.2
        #hplt_T = eu.plotting.bhist(Tvals,binsize=Tbsize,
        #                          show=False)

        logTvals=log10(Tvals)
        Tsdev = logTvals.std()
        Tbsize=Tsdev*0.2
        hplt_T = eu.plotting.bhist(logTvals,binsize=Tbsize,
                                   show=False)



        amp_sdev = ampvals.std()
        amp_bsize=amp_sdev*0.2
        hplt_amp = eu.plotting.bhist(ampvals,binsize=amp_bsize,
                                     show=False)



        hplt_cen.xlabel='center'
        hplt_g1.xlabel=g1lab
        hplt_g2.xlabel=g2lab
        hplt_T.xlabel=r'$log_{10}T$'
        hplt_amp.xlabel='Amplitude'

        tab[0,0] = burn_cen
        tab[1,0] = burn_g1
        tab[2,0] = burn_g2
        tab[3,0] = burn_T
        tab[4,0] = burn_amp

        tab[0,1] = hplt_cen
        tab[1,1] = hplt_g1
        tab[2,1] = hplt_g2
        tab[3,1] = hplt_T
        tab[4,1] = hplt_amp
        tab[5,0] = likep
        tab.show()

        if True: 
            import images
            nx = ny = 20
            levels=8
            h2d = eu.stat.histogram2d(g1vals, g2vals, nx=nx, ny=ny,more=True)
            images.view(h2d['hist'],
                             xdr=[h2d['xcenter'][0], h2d['xcenter'][-1]],
                             ydr=[h2d['ycenter'][0], h2d['ycenter'][-1]],
                             xlabel='g1', ylabel='g2', levels=levels)
            if True:
                gmm=self.get_like_mixture(ngauss=3)
                print gmm.weights_
                print gmm.means_

                covmean=0*gmm.covars_[0].copy()
                for i,cov in enumerate(gmm.covars_):
                    covmean += gmm.weights_[i]*cov
                """
                covmean=0*gmm.precs_[0].copy()
                for i,prec in enumerate(gmm.precs_):
                    cov = numpy.linalg.inv(prec)
                    covmean += gmm.weights_[i]*cov
                """

                wsum=gmm.weights_.sum()
                covmean /= wsum

                print 'weighted means'
                print (gmm.means_[:,0]*gmm.weights_).sum()/wsum,
                print (gmm.means_[:,1]*gmm.weights_).sum()/wsum
                
                print 'weighted error'
                print sqrt(diag(covmean))

                rnd=gmm.sample(g1vals.size*10)
                print rnd.shape
                rh2d = eu.stat.histogram2d(rnd[:,0], rnd[:,1], nx=nx, ny=ny,
                                           xmin=h2d['xlow'][0], xmax=h2d['xhigh'][-1],
                                           ymin=h2d['ylow'][0], ymax=h2d['yhigh'][-1],
                                           more=True)
                rh2d['hist'] = rh2d['hist']*float(g1vals.size)/float(rh2d['hist'].sum())
                images.compare_images(h2d['hist'], rh2d['hist'])

        if False: 
            import images
            model=self.get_maxprob_model()
            images.compare_images(self.image,model,
                                  label1='image [%d,%d]' % self.image.shape,
                                  label2='model')

        key=raw_input('hit a key (q to quit): ')
        if key=='q':
            stop
        print
コード例 #24
0
ファイル: vis.py プロジェクト: esheldon/fitvd
def compare_images(im1_in, im2_in, wt_in, **keys):
    import biggles
    import copy
    import images

    """
    wt = wt_in.copy()
    maxwt = wt.max()
    noiseval = np.sqrt(1.0/maxwt)

    w = np.where(wt <= 0.0)
    if w[0].size > 0:
        wt[w] = maxwt
    noise = np.random.normal(size=wt.shape)
    noise *= np.sqrt(1.0/wt)
    """

    if im1_in.shape != im2_in.shape:
        raise ValueError("images must be the same shape")

    color1 = keys.get('color1', 'blue')
    color2 = keys.get('color2', 'orange')
    colordiff = keys.get('colordiff', 'red')

    label1 = keys.get('label1', 'im1')
    label2 = keys.get('label2', 'im2')

    resid = (im1_in - im2_in)

    im1 = im1_in
    im2 = im2_in

    cen = [(im1.shape[0]-1)/2., (im1.shape[1]-1)/2.]

    labelres = '%s-%s' % (label1, label2)

    biggles.configure('default', 'fontsize_min', 1.)

    # will only be used if type is contour
    tab = biggles.Table(2, 3)
    if 'title' in keys:
        tab.title = keys['title']

    tkeys = copy.deepcopy(keys)
    tkeys.pop('title', None)
    tkeys['show'] = False
    tkeys['file'] = None

    autoscale = True
    tab[0, 0] = images.view(im1, autoscale=autoscale, **tkeys)
    tab[0, 1] = images.view(im2, autoscale=autoscale, **tkeys)
    tab[0, 2] = residplt = images.view(
        resid*np.sqrt(wt_in.clip(min=0)), **tkeys
    )

    wgood = np.where(wt_in > 0.0)
    dof = wgood[0].size
    chi2per = (resid**2 * wt_in).sum()/dof
    lab = biggles.PlotLabel(0.9, 0.9,
                            r'$\chi^2/dof$: %.2f' % chi2per,
                            color='red',
                            halign='right')
    residplt.add(lab)

    cen0 = int(cen[0])
    cen1 = int(cen[1])
    im1rows = im1_in[:, cen1]
    im1cols = im1_in[cen0, :]
    im2rows = im2_in[:, cen1]
    im2cols = im2_in[cen0, :]
    resrows = resid[:, cen1]
    rescols = resid[cen0, :]

    him1rows = biggles.Histogram(im1rows, color=color1)
    him1cols = biggles.Histogram(im1cols, color=color1)
    him2rows = biggles.Histogram(im2rows, color=color2)
    him2cols = biggles.Histogram(im2cols, color=color2)
    hresrows = biggles.Histogram(resrows, color=colordiff)
    hrescols = biggles.Histogram(rescols, color=colordiff)

    him1rows.label = label1
    him2rows.label = label2
    hresrows.label = labelres
    key = biggles.PlotKey(0.1, 0.9,
                          [him1rows, him2rows, hresrows])

    rplt = biggles.FramedPlot()
    rplt.add(him1rows, him2rows, hresrows, key)
    rplt.xlabel = 'Center Rows'

    cplt = biggles.FramedPlot()
    cplt.add(him1cols, him2cols, hrescols)
    cplt.xlabel = 'Center Columns'

    rplt.aspect_ratio = 1
    cplt.aspect_ratio = 1

    tab[1, 0] = rplt
    tab[1, 1] = cplt

    images._writefile_maybe(tab, **keys)
    images._show_maybe(tab, **keys)

    return tab
コード例 #25
0
ファイル: analysis.py プロジェクト: esheldon/espy
def plot_images(**keys):
    """
    Plot a random subset of objects, potentially with 
    some selection

    parameters
    ----------
    run: keyword, string
        The run identifier
    model: keyword, string
        Model name, e.g. 'exp'
    imtype: keyword, string
        'mosaic' or 'composite'
    num: keyword, int
        Number to make images for.  

    type: keyword, string
        'bad-center' or 'any'
    """
    import images

    model=keys['model']
    num=keys['num']
    seed=keys.get('seed',35)
    keys['type']=keys.get('type','any')
    keys['imtype']=keys.get('imtype','mosaic')

    numpy.random.seed(seed)

    data=files.read_output(**keys)
    m=files.open_meds()

    if keys['type']=='bad-center':
        w=select_bad_center(data, model)
    else:
        w=numpy.arange(data.size)

    r=numpy.random.random(w.size)
    s=r.argsort()

    wplot=w[s[0:num]]

    d=files.get_plot_dir(**keys)
    pf=path.join(d,'%(imtype)s-%(type)s-%(run)s-%(index)06d.png')
    if not os.path.exists(d):
        os.makedirs(d)

    for i in xrange(num):
        index=wplot[i]


        im=m.get_mosaic(index)

        if keys['imtype']=='composite':
            cw=m.get_cseg_mosaic(index)
            im *= cw
        elif keys['imtype'] == 'interp':
            iseg=m.interpolate_coadd_seg_mosaic(index)
            w=where( (iseg != (index+1)) & (iseg != 0) )
            im[w] = 0.0


        plt=images.view(im, title='%s' % index,show=False)

        keys['index'] = index
        fname=pf % keys

        print(fname)

        xsize=1800
        ysize=xsize*float(im.shape[1])/im.shape[0]
        plt.write_img(xsize,ysize,fname)
コード例 #26
0
ファイル: wrappers.py プロジェクト: esheldon/admom
def test_admom_residuals(image, cen, guess, sky=0.0, sigsky=1.0):
    """
    Fit adaptive moments to the input image and display the residuals
    """
    import images
    import fimage
    import biggles
    res = admom(image, cen[0], cen[1], guess=guess, sky=sky, sigsky=sigsky,
                nsub=8)

    counts = image.sum()
    wcen=[res['wrow'],res['wcol']]
    fake = fimage.model_image('gauss',image.shape,wcen,res['Irr'],res['Irc'],res['Icc'],
                              counts=counts)

    resid = fake-image

    maxval = max( image.max(), fake.max() )
    minval = 0.0

    levels=7
    tab=biggles.Table(2,3)
    #tab=biggles.Table(3,2)
    implt=images.view(image, levels=levels, show=False, min=minval, max=maxval)
    fakeplt=images.view(fake, levels=levels, show=False, min=minval, max=maxval)
    residplt=images.view(resid, show=False, min=minval, max=maxval)

    sigma = numpy.sqrt((res['Irr']+res['Icc'])/2.0)
    lab = biggles.PlotLabel(0.1,0.9,r'$\sigma$: %0.2f' % sigma, fontsize=4, halign='left')
    fakeplt.add(lab)

    implt.title='original'
    fakeplt.title='gaussian model'
    residplt.title='residuals'


    # cross-sections
    imrows = image[:,wcen[1]]
    imcols = image[wcen[0],:]
    fakerows = fake[:,wcen[1]]
    fakecols = fake[wcen[0],:]
    resrows = resid[:,wcen[1]]
    rescols = resid[wcen[0],:]

    himrows = biggles.Histogram(imrows, color='blue')
    himcols = biggles.Histogram(imcols, color='blue')
    hfakerows = biggles.Histogram(fakerows, color='orange')
    hfakecols = biggles.Histogram(fakecols, color='orange')
    hresrows = biggles.Histogram(resrows, color='red')
    hrescols = biggles.Histogram(rescols, color='red')

    himrows.label = 'image'
    hfakerows.label = 'model'
    hresrows.label = 'resid'
    key = biggles.PlotKey(0.1,0.9,[himrows,hfakerows,hresrows]) 
    rplt=biggles.FramedPlot()
    rplt.add( himrows, hfakerows, hresrows,key )

    cplt=biggles.FramedPlot()
    cplt.add( himcols, hfakecols, hrescols )

    rplt.aspect_ratio=1
    cplt.aspect_ratio=1


    tab[0,0] = implt
    tab[0,1] = fakeplt
    tab[0,2] = residplt
    tab[1,0] = rplt
    tab[1,1] = cplt

    #tab[0,0] = implt
    #tab[0,1] = fakeplt
    #tab[1,0] = residplt
    #tab[1,1] = rplt
    #tab[2,0] = cplt


    tab.show()
コード例 #27
0
ファイル: regauss_sim.py プロジェクト: esheldon/espy
def psfield_compare_model(rsp=None, generator='filter', next=False):
    """
    compare psf reconstructions with the best fit models in the 6th header.
    """

    import images
    import biggles
    from scipy.ndimage.filters import gaussian_filter
    import fimage

    filter='r'
    fnum=2
    if rsp is None:
        rsp=RandomSDSSPSF(1.3,1.5,filter,verbose=True)
        image,meta = rsp.next(meta=True)
    else:
        if rsp.psf is None:
            image,meta = rsp.current(meta=True)
        else:
            if next:
                image,meta = rsp.next(meta=True)
            else:
                image,meta = rsp.current(meta=True)

    cen = [(image.shape[0]-1)/2, (image.shape[1]-1)/2]

    extra='_2G'
    a = 1.0
    b = meta['psf_b'+extra][0,fnum]
    s1 = meta['psf_sigma1'+extra][0,fnum]
    s2 = meta['psf_sigma2'+extra][0,fnum]

    if generator == 'fimage':
        fake1 = fimage.makeimage('gauss',image.shape,cen,s1**2,0,s1**2,counts=1)
        fake2 = fimage.makeimage('gauss',image.shape,cen,s2**2,0,s2**2,counts=1)

        a /= (s1**2 + b*s2**2)
        fake = a*( s1**2*fake1 + b*s2**2*fake2 )
    elif generator == 'imsim':
        import imsim
        fake1 = imsim.mom2disk('gauss',s1**2,0,s1**2,image.shape,cen=cen,counts=1)
        fake2 = imsim.mom2disk('gauss',s2**2,0,s2**2,image.shape,cen=cen,counts=1)

        a /= (s1**2 + b*s2**2)
        fake = a*( s1**2*fake1 + b*s2**2*fake2 )

    elif generator == 'filter':
        a /= (s1**2 + b*s2**2)
        fake1 = numpy.zeros_like(image)
        # convolve delta function with gaussians
        fake1[cen[0],cen[1]] = 1
        fake = a * (s1**2 * gaussian_filter(fake1, (s1,s1)) + b*s2**2*gaussian_filter(fake1, (s2,s2)))
    else:
        raise ValueError("unknown generator type: '%s'" % generator)

    wlog("image counts:",image.sum(),"model counts:",fake.sum())

    resid = fake-image

    wlog("summed residuals:",resid.sum())

    maxval = max( image.max(), fake.max() )
    minval = 0.0

    levels=7
    tab=biggles.Table(2,3)
    #tab=biggles.Table(3,2)
    implt=images.view(image, levels=levels, show=False, min=minval, max=maxval)
    fakeplt=images.view(fake, levels=levels, show=False, min=minval, max=maxval)
    residplt=images.view(resid, show=False, min=minval, max=maxval)

    #sigma = numpy.sqrt((res['Irr']+res['Icc'])/2.0)
    #lab = biggles.PlotLabel(0.1,0.9,r'$\sigma$: %0.3f' % sigma, fontsize=4, halign='left')
    #fakeplt.add(lab)

    implt.title='original'
    fakeplt.title='gaussian '+generator
    residplt.title='residuals'


    # cross-sections
    imrows = image[:,cen[1]]
    imcols = image[cen[0],:]
    fakerows = fake[:,cen[1]]
    fakecols = fake[cen[0],:]
    resrows = resid[:,cen[1]]
    rescols = resid[cen[0],:]

    himrows = biggles.Histogram(imrows, color='blue')
    himcols = biggles.Histogram(imcols, color='blue')
    hfakerows = biggles.Histogram(fakerows, color='orange')
    hfakecols = biggles.Histogram(fakecols, color='orange')
    hresrows = biggles.Histogram(resrows, color='red')
    hrescols = biggles.Histogram(rescols, color='red')

    himrows.label = 'image'
    hfakerows.label = 'model'
    hresrows.label = 'resid'
    key = biggles.PlotKey(0.1,0.9,[himrows,hfakerows,hresrows]) 
    rplt=biggles.FramedPlot()
    rplt.add( himrows, hfakerows, hresrows,key )

    cplt=biggles.FramedPlot()
    cplt.add( himcols, hfakecols, hrescols )

    rplt.aspect_ratio=1
    cplt.aspect_ratio=1


    tab[0,0] = implt
    tab[0,1] = fakeplt
    tab[0,2] = residplt
    tab[1,0] = rplt
    tab[1,1] = cplt

    #tab[0,0] = implt
    #tab[0,1] = fakeplt
    #tab[1,0] = residplt
    #tab[1,1] = rplt
    #tab[2,0] = cplt


    tab.show()


    return rsp
コード例 #28
0
ファイル: coadd.py プロジェクト: esheldon/meds
    def _show_coadd(self, iobj, obs, original_coadd, original_wt, original_seg):
        import biggles
        import images

        tab=biggles.Table(3,3,aspect_ratio=1.0)

        nl=None
        tab[0,0] = images.view(
            np.rot90( obs.image.transpose(),k=2),
            #obs.image,
            nonlinear=nl,
            title='coadd (trans/rot)',
            show=False,
        )
        tab[0,1] = images.view(original_coadd, nonlinear=nl, title='orig coadd', show=False)

        diff = np.rot90( obs.image.transpose(),k=2) - original_coadd
        tab[0,2] = images.view(diff, title='diff', show=False)

        cmin,cmax = obs.weight.min(), obs.weight.max()
        tab[1,0] = images.view(
            np.rot90( obs.weight.transpose(),k=2),
            #obs.weight,
            nonlinear=nl,
            title='weight (trans/rot) minmax: %.3g/%.3g' % (cmin,cmax),
            show=False,
        )
        cmin,cmax = original_wt.min(), original_wt.max()
        tab[1,1] = images.view(original_wt,
                               nonlinear=nl,
                               title='orig weight minmax: %.3g/%.3g' % (cmin,cmax),
                               show=False)

        tab[1,2] = images.view(obs.noise, title='noise', show=False)

        #tab[0,2] = images.view(obs.seg, title='seg', show=False)
        tab[2,0] = images.view(
            np.rot90( obs.seg.transpose(),k=2),
            #obs.seg,
            title='seg (trans/rot)',
            show=False,
        )
        tab[2,1] = images.view(original_seg, title='orig seg', show=False)

        tab[2,2] = images.view(obs.psf.image, title='coadded psf', show=False)
        
        d='plots'
        if not os.path.exists(d):
            try:
                os.makedirs(d)
            except:
                pass

        fname=[
            'object',
            '%06d' % iobj,
            'coadd',
        ]
        fname = '-'.join(fname)
        fname += '.png'
        fname=os.path.join(d, fname)

        #tab.show()
        print("    writing:",fname)
        tab.write_img(1500,1500,fname)
コード例 #29
0
def compare_rgb_images(image,
                       model,
                       diffim,
                       seg=None,
                       weight=None,
                       width=1000,
                       chi2per=None,
                       rng=None,
                       title=None,
                       show=False):
    """
    make a comparison of the image with the model
    """
    import biggles
    import images

    if chi2per is not None:
        diff_title = 'chi2/dof: %.2f' % chi2per
    else:
        diff_title = None

    imrow, imcol = 0, 0
    modrow, modcol = 0, 1

    nrows = 2
    if seg is not None and weight is not None:
        ncols = 3
        arat = image.shape[1] / image.shape[0] * 2 / 3

        diffrow, diffcol = 0, 2
        segrow, segcol = 1, 0
        wtrow, wtcol = 1, 1
    else:
        ncols = 2
        arat = image.shape[1] / image.shape[0]

        diffrow, diffcol = 1, 0

        if seg is not None:
            segrow, segcol = 1, 1
        elif weight is not None:
            wtrow, wtcol = 1, 1

    tab = biggles.Table(nrows, ncols, aspect_ratio=arat)

    tab[imrow, imcol] = images.view(
        image,  # /maxval,
        show=False,
        title='image',
    )
    tab[modrow, modcol] = images.view(
        model,  # /maxval,
        show=False,
        title='model',
    )

    tab[diffrow, diffcol] = images.view(
        diffim,
        show=False,
        title=diff_title,
    )

    if seg is not None:
        tab[segrow, segcol] = plot_seg(seg, rng=rng, width=width, title='seg')

    if weight is not None:
        tab[wtrow, wtcol] = images.view(weight, show=False, title='weight')

    if title is not None:
        tab.title = title

    if show:
        fname = tempfile.mktemp(suffix='.png')
        tab.write_img(width, width * arat, fname)
        show_image(fname)

    return tab
コード例 #30
0
def compare_images_mosaic(im1, im2, **keys):
    import biggles
    import copy
    import images

    show = keys.get('show', True)
    ymin = keys.get('min', None)
    ymax = keys.get('max', None)

    color1 = keys.get('color1', 'blue')
    color2 = keys.get('color2', 'orange')
    colordiff = keys.get('colordiff', 'red')

    nrow = 2
    ncol = 3

    label1 = keys.get('label1', 'im1')
    label2 = keys.get('label2', 'im2')

    cen = keys.get('cen', None)
    if cen is None:
        cen = [(im1.shape[0] - 1) / 2., (im1.shape[1] - 1) / 2.]

    labelres = '%s-%s' % (label1, label2)

    biggles.configure('default', 'fontsize_min', 1.)

    if im1.shape != im2.shape:
        raise ValueError("images must be the same shape")

    #resid = im2-im1
    resid = im1 - im2

    # will only be used if type is contour
    tab = biggles.Table(2, 1)
    if 'title' in keys:
        tab.title = keys['title']

    tkeys = copy.deepcopy(keys)
    tkeys.pop('title', None)
    tkeys['show'] = False
    tkeys['file'] = None

    tkeys['nonlinear'] = None
    # this has no effect
    tkeys['min'] = resid.min()
    tkeys['max'] = resid.max()

    mosaic = np.zeros((im1.shape[0], 3 * im1.shape[1]))
    ncols = im1.shape[1]
    mosaic[:, 0:ncols] = im1
    mosaic[:, ncols:2 * ncols] = im2
    mosaic[:, 2 * ncols:3 * ncols] = resid

    residplt = images.view(mosaic, **tkeys)

    dof = im1.size
    chi2per = (resid**2).sum() / dof
    lab = biggles.PlotLabel(0.9,
                            0.9,
                            r'$\chi^2/npix$: %.3e' % chi2per,
                            color='red',
                            halign='right')
    residplt.add(lab)

    cen0 = int(cen[0])
    cen1 = int(cen[1])
    im1rows = im1[:, cen1]
    im1cols = im1[cen0, :]
    im2rows = im2[:, cen1]
    im2cols = im2[cen0, :]
    resrows = resid[:, cen1]
    rescols = resid[cen0, :]

    him1rows = biggles.Histogram(im1rows, color=color1)
    him1cols = biggles.Histogram(im1cols, color=color1)
    him2rows = biggles.Histogram(im2rows, color=color2)
    him2cols = biggles.Histogram(im2cols, color=color2)
    hresrows = biggles.Histogram(resrows, color=colordiff)
    hrescols = biggles.Histogram(rescols, color=colordiff)

    him1rows.label = label1
    him2rows.label = label2
    hresrows.label = labelres
    key = biggles.PlotKey(0.1, 0.9, [him1rows, him2rows, hresrows])

    rplt = biggles.FramedPlot()
    rplt.add(him1rows, him2rows, hresrows, key)
    rplt.xlabel = 'Center Rows'

    cplt = biggles.FramedPlot()
    cplt.add(him1cols, him2cols, hrescols)
    cplt.xlabel = 'Center Columns'

    rplt.aspect_ratio = 1
    cplt.aspect_ratio = 1

    ctab = biggles.Table(1, 2)
    ctab[0, 0] = rplt
    ctab[0, 1] = cplt

    tab[0, 0] = residplt
    tab[1, 0] = ctab

    images._writefile_maybe(tab, **keys)
    images._show_maybe(tab, **keys)

    return tab
コード例 #31
0
ファイル: atlas_tools.py プロジェクト: esheldon/espy
def view_atlas(**keys):
    """
    View atlas images for the input object

    parameters
    ----------
    cat: optional
        A full structure with run,rerun,camcol,field,id
    run: optional
        Run id
    rerun: optional
        rerun id
    camcol: optional
        camcol id
    field: opt
        field id
    id: opt
        id in field
    band: optional
        Only display this band

    shift:
        Apply sub-pixel astronometric shifts, default False
    """
    import images
    import biggles
    import sdsspy

    biggles.configure( 'default', 'fontsize_min', 1)

    band=keys.get('band',None)
    cat=keys.get('cat',None)
    show=keys.get('show',True)
    color=keys.get('color',False)
    shift=keys.get('shift',False)

    idinfo=get_id_info(**keys)

    imdict=read_atlas(**idinfo)

    nonlinear=keys.get('nonlinear', _default_nonlinear)

    if band is not None:
        bnum=sdsspy.util.FILTERNUM[band]
        bchar=sdsspy.util.FILTERCHAR[band]

        idinfo['bchar']=bchar
        title='%(run)06d-%(camcol)d-%(field)04d-%(id)05d-%(bchar)s' % idinfo
        im=imdict['images'][bnum]

        plt=images.view(im, nonlinear=nonlinear,show=False)

        plt.title=title
        lab=biggles.PlotLabel(0.9,0.9,bchar,color='yellow')
        plt.add(lab)
        if show:
            plt.show()
        return plt
    elif color:
        img=imdict['images'][1].transpose()
        imr=imdict['images'][2].transpose()
        imi=imdict['images'][3].transpose()

        if shift:
            img,imi=shift_images(imdict, img, imi)

        colorim=images.get_color_image(imi,imr,img,
                                       satval=30.,
                                       nonlinear=nonlinear)

        s=imdict['images'][0].shape
        ranges = ((-0.5, -0.5), (s[1]-0.5, s[0]-0.5))

        d = biggles.Density(colorim, ranges)

        plt=biggles.FramedPlot()
        plt.add(d)
        plt.aspect_ratio=s[0]/float(s[1])
        title='%(run)06d-%(camcol)d-%(field)04d-%(id)05d' % idinfo
        plt.title=title
        if show:
            plt.show()
        return plt


    imslist=scale_image_list(imdict['images'], nonlinear)

    nrow=2
    ncol=3
    plt=biggles.FramedArray(nrow,ncol)
    title='%(run)06d-%(camcol)d-%(field)04d-%(id)05d' % idinfo
    plt.title=title

    s=imslist[0].shape
    plt.aspect_ratio = s[0]/float(s[1])*2./3.

    for i in xrange(5):
        bchar=sdsspy.util.FILTERCHAR[i]
        row=i/ncol
        col=i % ncol

        im=imslist[i]
        s=im.shape

        im = im.transpose()
        ranges = ((-0.5, -0.5), (s[1]-0.5, s[0]-0.5))

        d = biggles.Density(im, ranges)

        #labs=get_shaded_label(0.9,0.9,bchar)
        lab=biggles.PlotLabel(0.9,0.9,bchar,color='yellow')
        plt[row,col].add(d)
        plt[row,col].add(lab)

    if show:
        plt.show()
    return plt