コード例 #1
0
    def makegrid(self, nx, ny, returnxy=False):
        """
 return arrays of shape (ny,nx) containing lon,lat coordinates of
 an equally spaced native projection grid.
 if returnxy=True, the x,y values of the grid are returned also.
        """
        dx = (self.urcrnrx - self.llcrnrx) / (nx - 1)
        dy = (self.urcrnry - self.llcrnry) / (ny - 1)
        x = self.llcrnrx + dx * N.indices((ny, nx))[1, :, :]
        y = self.llcrnry + dy * N.indices((ny, nx))[0, :, :]
        lons, lats = self(x, y, inverse=True)
        if returnxy:
            return lons, lats, x, y
        else:
            return lons, lats
コード例 #2
0
ファイル: proj.py プロジェクト: jtomase/matplotlib
    def makegrid(self, nx, ny, returnxy=False):
        """
 return arrays of shape (ny,nx) containing lon,lat coordinates of
 an equally spaced native projection grid.
 if returnxy=True, the x,y values of the grid are returned also.
        """
        dx = (self.urcrnrx - self.llcrnrx) / (nx - 1)
        dy = (self.urcrnry - self.llcrnry) / (ny - 1)
        x = self.llcrnrx + dx * N.indices((ny, nx))[1, :, :]
        y = self.llcrnry + dy * N.indices((ny, nx))[0, :, :]
        lons, lats = self(x, y, inverse=True)
        if returnxy:
            return lons, lats, x, y
        else:
            return lons, lats
コード例 #3
0
def main():
    import pylab
    
    # Create the gaussian data
    Xin, Yin = pylab.mgrid[0:201, 0:201]
    data = gaussian(3, 100, 100, 20, 40)(Xin, Yin) + np.random.random(Xin.shape)
    
    pylab.matshow(data, cmap='gist_rainbow')
    
    params = fitgaussian(data)
    fit = gaussian(*params)
    
    pylab.contour(fit(*pylab.indices(data.shape)), cmap='copper')
    ax = pylab.gca()
    (height, x, y, width_x, width_y) = params
    
    pylab.text(0.95, 0.05, """
    x : %.1f
    y : %.1f
    width_x : %.1f
    width_y : %.1f""" %(x, y, width_x, width_y),
            fontsize=16, horizontalalignment='right',
            verticalalignment='bottom', transform=ax.transAxes)
    
    pylab.show()
コード例 #4
0
def main():
    #from pylab import *
    import pylab

    # Create the gaussian data
    Xin, Yin = pylab.mgrid[0:201, 0:201]
    data = gaussian(3, 100, 100, 20, 40)(Xin, Yin) + np.random.random(
        Xin.shape)

    pylab.matshow(data, cmap='gist_rainbow')

    params = fitgaussian(data)
    fit = gaussian(*params)

    pylab.contour(fit(*pylab.indices(data.shape)), cmap='copper')
    ax = pylab.gca()
    (height, x, y, width_x, width_y) = params

    pylab.text(0.95,
               0.05,
               """
    x : %.1f
    y : %.1f
    width_x : %.1f
    width_y : %.1f""" % (x, y, width_x, width_y),
               fontsize=16,
               horizontalalignment='right',
               verticalalignment='bottom',
               transform=ax.transAxes)

    pylab.show()
コード例 #5
0
def fitgaussian(data):
    """Returns (height, x, y, width_x, width_y)
	the gaussian parameters of a 2D distribution found by a fit"""
    params = moments(data)
    errorfunction = lambda p: ravel(gaussian(*p)(*indices(data.shape)) - data)
    p, success = optimize.leastsq(errorfunction, params)
    return p
コード例 #6
0
ファイル: collapse_gaussfit.py プロジェクト: Fade89/agpy
def wrap_collapse_adaptive(filename,outprefix,redo='no',nsig=5,nrsig=2,doplot=True):
    """
    redo - if not equal to 'no', then...
    if collapse_gaussfit succeeded (to the extent that the .pysav files were written),
    but some part of the file writing or successive procedures failed, re-do those 
    procedures without redoing the whole collapse
    """
    fitsfile = pyfits.open(filename)
    dv,v0,p3 = fitsfile[0].header['CD3_3'],fitsfile[0].header['CRVAL3'],fitsfile[0].header['CRPIX3']
    dr,r0,p1 = fitsfile[0].header['CD1_1'],fitsfile[0].header['CRVAL1'],fitsfile[0].header['CRPIX1']
    dd,d0,p2 = fitsfile[0].header['CD2_2'],fitsfile[0].header['CRVAL2'],fitsfile[0].header['CRPIX2']
    xtora = lambda x: (x-p1+1)*dr+r0    # convert pixel coordinates to RA/Dec/Velocity
    ytodec = lambda y: (y-p2+1)*dd+d0
    vconv = lambda v: (v-p3+1)*dv+v0

    cube = fitsfile[0].data
    cube = where(numpy.isnan(cube),0,cube)

    if redo=='no':
        adaptB = asarray(adaptive_collapse_gaussfit(cube,axis=0,prefix=outprefix+'_triple',
            nsig=nsig,nrsig=nrsig,vconv=vconv,xtora=xtora,ytodec=ytodec,doplot=doplot))
        adaptB[numpy.isnan(adaptB)] = 0
        pickle.dump(adaptB,open('%s_adaptB.pysav' % outprefix,'w'))
    else:
        adaptB = pickle.load(open('%s_adaptB.pysav' % outprefix,'r'))
    db = adaptB
    gcd = double_gaussian(db[3],db[4],db[0],db[1],db[5],db[6])(indices(cube.shape)[0])
    fitsfile[0].data = gcd
    fitsfile.writeto('%s_adaptgausscube.fits' % outprefix,clobber=True)

    gcd[numpy.isnan(gcd)] = 0
    adaptResids = cube-gcd
    fitsfile[0].data = adaptResids
    fitsfile.writeto('%s_adaptgaussresids.fits' % outprefix,clobber=True)


    #adaptB[4] = (adaptB[4]-v0) / dv + p3-1
    #adaptB[3] = (adaptB[3]-v0) / dv + p3-1
    adaptB[4] = (adaptB[4]-p3+1) * dv + v0
    adaptB[3] = (adaptB[3]-p3+1) * dv + v0
    fitsfile[0].data = asarray(adaptB)
    fitsfile.writeto('%s_adaptgausspars.fits' % outprefix,clobber=True)

    fitsfile[0].header.__delitem__('CD3_3')
    fitsfile[0].header.__delitem__('CRVAL3')
    fitsfile[0].header.__delitem__('CRPIX3')
    fitsfile[0].header.__delitem__('CUNIT3')
    fitsfile[0].header.__delitem__('CTYPE3')

    adaptResids[numpy.isnan(adaptResids)] = 0
    totalDResids = adaptResids.sum(axis=0)
    fitsfile[0].data = totalDResids
    fitsfile.writeto('%s_adaptgauss_totalresids.fits' % outprefix,clobber=True)

    return adaptB
コード例 #7
0
def moments(data):
    """Returns (height, x, y, width_x, width_y)
		the gaussian parameters of a 2D distribution by calculating its
		moments
	"""
    total = data.sum()
    bias = data.mean()
    X, Y = indices(data.shape)
    x = (X * data).sum() / total
    y = (Y * data).sum() / total
    col = data[:, int(y)]
    width_x = sqrt(abs((arange(col.size) - y)**2 * col).sum() / col.sum())
    row = data[int(x), :]
    width_y = sqrt(abs((arange(row.size) - x)**2 * row).sum() / row.sum())
    height = data.max()
    return bias, height, x, y, width_x, width_y
コード例 #8
0
def moments(data):
    """Returns (height, x, y, width_x, width_y)
		the gaussian parameters of a 2D distribution by calculating its
		moments
	"""
    #total = data.sum()
    #bias=data.mean()
    bias = np.min(data)  # revised by Kai to make faint object detection easier
    data_this = data - bias
    total = data_this.sum()
    X, Y = indices(data.shape)
    x = (X * data_this).sum() / total
    y = (Y * data_this).sum() / total
    col = data_this[:, int(y)]
    width_x = sqrt(abs((arange(col.size) - y)**2 * col).sum() / col.sum())
    row = data_this[int(x), :]
    width_y = sqrt(abs((arange(row.size) - x)**2 * row).sum() / row.sum())
    height = data_this.max()
    return bias, height, x, y, width_x, width_y
コード例 #9
0
ファイル: collapse_gaussfit.py プロジェクト: Fade89/agpy
def wrap_collapse_gauss(filename,outprefix,redo='no'):
    """

    redo - if not equal to 'no', then...
    if collapse_gaussfit succeeded (to the extent that the .pysav files were written),
    but some part of the file writing or successive procedures failed, re-do those 
    procedures without redoing the whole collapse
    """
    fitsfile = pyfits.open(filename)
    dv,v0,p3 = fitsfile[0].header['CD3_3'],fitsfile[0].header['CRVAL3'],fitsfile[0].header['CRPIX3']

    cube = fitsfile[0].data
    cube = where(numpy.isnan(cube),0,cube)

    if redo=='no':
        doubleB = asarray(collapse_double_gaussfit(cube,axis=0))
        doubleB[numpy.isnan(doubleB)] = 0
        pickle.dump(doubleB,open('%s_doubleB.pysav' % outprefix,'w'))
    else:
        doubleB = pickle.load(open('%s_doubleB.pysav' % outprefix,'r'))
    db = doubleB
    gcd = double_gaussian(db[3],db[4],db[0],db[1],db[5],db[6])(indices(cube.shape)[0])
    fitsfile[0].data = gcd
    fitsfile.writeto('%s_doublegausscube.fits' % outprefix,clobber=True)

    gcd[numpy.isnan(gcd)] = 0
    doubleResids = cube-gcd
    fitsfile[0].data = doubleResids
    fitsfile.writeto('%s_doublegaussresids.fits' % outprefix,clobber=True)


    #doubleB[4] = (doubleB[4]-v0) / dv + p3-1
    #doubleB[3] = (doubleB[3]-v0) / dv + p3-1
    doubleB[4] = (doubleB[4]-p3+1) * dv + v0
    doubleB[3] = (doubleB[3]-p3+1) * dv + v0
    fitsfile[0].data = asarray(doubleB)
    fitsfile.writeto('%s_doublegausspars.fits' % outprefix,clobber=True)

    if redo=='no':
        singleB = asarray(collapse_gaussfit(cube,axis=0))
        pickle.dump(singleB,open('%s_singleB.pysav' % outprefix,'w'))
    else:
        singleB = pickle.load(open('%s_singleB.pysav' % outprefix,'r'))
    gc = gaussian(singleB[1],singleB[0],singleB[2])(indices(cube.shape)[0])
    singleB[1] = (singleB[1]-p3+1) * dv + v0
    fitsfile[0].data = gc
    fitsfile.writeto('%s_singlegausscube.fits' % outprefix,clobber=True)

    gc[numpy.isnan(gc)]=0
    singleResids = cube-gc
    fitsfile[0].data = singleResids
    fitsfile.writeto('%s_singlegaussresids.fits' % outprefix,clobber=True)
    fitsfile[0].data = asarray(singleB)
    fitsfile.writeto('%s_singlegausspars.fits' % outprefix,clobber=True)

    fitsfile[0].header.__delitem__('CD3_3')
    fitsfile[0].header.__delitem__('CRVAL3')
    fitsfile[0].header.__delitem__('CRPIX3')
    fitsfile[0].header.__delitem__('CUNIT3')
    fitsfile[0].header.__delitem__('CTYPE3')

    doubleResids[numpy.isnan(doubleResids)] = 0
    totalDResids = doubleResids.sum(axis=0)
    fitsfile[0].data = totalDResids
    fitsfile.writeto('%s_doublegauss_totalresids.fits' % outprefix,clobber=True)

    singleResids[numpy.isnan(singleResids)] = 0
    totalSResids = singleResids.sum(axis=0)
    fitsfile[0].data = totalSResids
    fitsfile.writeto('%s_singlegauss_totalresids.fits' % outprefix,clobber=True)

    return singleB,doubleB
コード例 #10
0
    def drawmeridians(self,meridians,color='k',linewidth=1., \
                      linestyle='--',dashes=[1,1],labels=[0,0,0,0],\
                      font='rm',fontsize=12):
        """
 draw meridians (longitude lines).

 meridians - list containing longitude values to draw (in degrees).
 color - color to draw meridians (default black).
 linewidth - line width for meridians (default 1.)
 linestyle - line style for meridians (default '--', i.e. dashed).
 dashes - dash pattern for meridians (default [1,1], i.e. 1 pixel on,
  1 pixel off).
 labels - list of 4 values (default [0,0,0,0]) that control whether
  meridians are labelled where they intersect the left, right, top or 
  bottom of the plot. For example labels=[1,0,0,1] will cause meridians
  to be labelled where they intersect the left and bottom of the plot,
  but not the right and top. Labels are drawn using mathtext.
 font - mathtext font used for labels ('rm','tt','it' or 'cal', default 'rm').
 fontsize - font size in points for labels (default 12).
        """
        # get current axes instance.
        ax = pylab.gca()
        # don't draw meridians past latmax, always draw parallel at latmax.
        latmax = 80. # not used for cyl, merc projections.
        # offset for labels.
	yoffset = (self.urcrnry-self.llcrnry)/100./self.aspect
	xoffset = (self.urcrnrx-self.llcrnrx)/100.

        if self.projection not in ['merc','cyl']:
            lats = pylab.arange(-latmax,latmax+1).astype('f')
        else:
            lats = pylab.arange(-90,91).astype('f')
        xdelta = 0.1*(self.xmax-self.xmin)
        ydelta = 0.1*(self.ymax-self.ymin)
        for merid in meridians:
            lons = merid*pylab.ones(len(lats),'f')
            x,y = self(lons,lats)
            # remove points outside domain.
            testx = pylab.logical_and(x>=self.xmin-xdelta,x<=self.xmax+xdelta)
            x = pylab.compress(testx, x)
            y = pylab.compress(testx, y)
            testy = pylab.logical_and(y>=self.ymin-ydelta,y<=self.ymax+ydelta)
            x = pylab.compress(testy, x)
            y = pylab.compress(testy, y)
            if len(x) > 1 and len(y) > 1:
                # split into separate line segments if necessary.
                # (not necessary for mercator or cylindrical).
                xd = (x[1:]-x[0:-1])**2
                yd = (y[1:]-y[0:-1])**2
                dist = pylab.sqrt(xd+yd)
                split = dist > 500000.
                if pylab.asum(split) and self.projection not in ['merc','cyl']:
                   ind = (pylab.compress(split,pylab.squeeze(split*pylab.indices(xd.shape)))+1).tolist()
                   xl = []
                   yl = []
                   iprev = 0
                   ind.append(len(xd))
                   for i in ind:
                       xl.append(x[iprev:i])
                       yl.append(y[iprev:i])
                       iprev = i
                else:
                    xl = [x]
                    yl = [y]
                # draw each line segment.
                for x,y in zip(xl,yl):
                    # skip if only a point.
                    if len(x) > 1 and len(y) > 1:
                        l = Line2D(x,y,linewidth=linewidth,linestyle=linestyle)
                        l.set_color(color)
                        l.set_dashes(dashes)
                        ax.add_line(l)
        # draw labels for meridians.
        # search along edges of map to see if parallels intersect.
        # if so, find x,y location of intersection and draw a label there.
        if self.projection == 'cyl':
            dx = 0.01; dy = 0.01
        else:
            dx = 1000; dy = 1000
        for dolab,side in zip(labels,['l','r','t','b']):
            if not dolab: continue
            # for cyl or merc, don't draw meridians on left or right.
            if self.projection in ['cyl','merc'] and side in ['l','r']: continue
            if side in ['l','r']:
	        nmax = int((self.ymax-self.ymin)/dy+1)
                if self.urcrnry < self.llcrnry:
	            yy = self.llcrnry-dy*pylab.arange(nmax)
                else:
	            yy = self.llcrnry+dy*pylab.arange(nmax)
                if side == 'l':
	            lons,lats = self(self.llcrnrx*pylab.ones(yy.shape,'f'),yy,inverse=True)
                else:
	            lons,lats = self(self.urcrnrx*pylab.ones(yy.shape,'f'),yy,inverse=True)
                lons = pylab.where(lons < 0, lons+360, lons)
                lons = [int(lon*10) for lon in lons.tolist()]
                lats = [int(lat*10) for lat in lats.tolist()]
            else:
	        nmax = int((self.xmax-self.xmin)/dx+1)
                if self.urcrnrx < self.llcrnrx:
	            xx = self.llcrnrx-dx*pylab.arange(nmax)
                else:
	            xx = self.llcrnrx+dx*pylab.arange(nmax)
                if side == 'b':
	            lons,lats = self(xx,self.llcrnry*pylab.ones(xx.shape,'f'),inverse=True)
                else:
	            lons,lats = self(xx,self.urcrnry*pylab.ones(xx.shape,'f'),inverse=True)
                lons = pylab.where(lons < 0, lons+360, lons)
                lons = [int(lon*10) for lon in lons.tolist()]
                lats = [int(lat*10) for lat in lats.tolist()]
            for lon in meridians:
                if lon<0: lon=lon+360.
                # find index of meridian (there may be two, so
                # search from left and right).
                try:
                    nl = lons.index(int(lon*10))
                except:
                    nl = -1
                try:
                    nr = len(lons)-lons[::-1].index(int(lon*10))-1
                except:
                    nr = -1
        	if lon>180:
        	    lonlab = r'$\%s{%g\/^{\circ}\/W}$'%(font,pylab.fabs(lon-360))
        	elif lon<180 and lon != 0:
        	    lonlab = r'$\%s{%g\/^{\circ}\/E}$'%(font,lon)
        	else:
        	    lonlab = r'$\%s{%g\/^{\circ}}$'%(font,lon)
                # meridians can intersect each map edge twice.
                for i,n in enumerate([nl,nr]):
                    lat = lats[n]/10.
                    # no meridians > latmax for projections other than merc,cyl.
                    if self.projection not in ['merc','cyl'] and lat > latmax: continue
                    # don't bother if close to the first label.
                    if i and abs(nr-nl) < 100: continue
                    if n >= 0:
                        if side == 'l':
        	            pylab.text(self.llcrnrx-xoffset,yy[n],lonlab,horizontalalignment='right',verticalalignment='center',fontsize=fontsize)
                        elif side == 'r':
        	            pylab.text(self.urcrnrx+xoffset,yy[n],lonlab,horizontalalignment='left',verticalalignment='center',fontsize=fontsize)
                        elif side == 'b':
        	            pylab.text(xx[n],self.llcrnry-yoffset,lonlab,horizontalalignment='center',verticalalignment='top',fontsize=fontsize)
                        else:
        	            pylab.text(xx[n],self.urcrnry+yoffset,lonlab,horizontalalignment='center',verticalalignment='bottom',fontsize=fontsize)

        # make sure axis ticks are turned off
        ax.set_xticks([]) 
        ax.set_yticks([])
        # set axes limits to fit map region.
        self.set_axes_limits()
コード例 #11
0
ファイル: collapse_gaussfit.py プロジェクト: Fade89/agpy
def double_gerr(xarr):
    return lambda p:xarr-double_gaussian(*p)(*indices(xarr.shape))
コード例 #12
0
def gerr(xarr):
    return lambda p: xarr - gaussian(*p)(*indices(xarr.shape))
コード例 #13
0
def wrap_collapse_adaptive(filename,
                           outprefix,
                           redo='no',
                           nsig=5,
                           nrsig=2,
                           doplot=True):
    """
    redo - if not equal to 'no', then...
    if collapse_gaussfit succeeded (to the extent that the .pysav files were written),
    but some part of the file writing or successive procedures failed, re-do those 
    procedures without redoing the whole collapse
    """
    fitsfile = pyfits.open(filename)
    dv, v0, p3 = fitsfile[0].header['CD3_3'], fitsfile[0].header[
        'CRVAL3'], fitsfile[0].header['CRPIX3']
    dr, r0, p1 = fitsfile[0].header['CD1_1'], fitsfile[0].header[
        'CRVAL1'], fitsfile[0].header['CRPIX1']
    dd, d0, p2 = fitsfile[0].header['CD2_2'], fitsfile[0].header[
        'CRVAL2'], fitsfile[0].header['CRPIX2']
    xtora = lambda x: (
        x - p1 + 1) * dr + r0  # convert pixel coordinates to RA/Dec/Velocity
    ytodec = lambda y: (y - p2 + 1) * dd + d0
    vconv = lambda v: (v - p3 + 1) * dv + v0

    cube = fitsfile[0].data
    cube = where(numpy.isnan(cube), 0, cube)

    if redo == 'no':
        adaptB = asarray(
            adaptive_collapse_gaussfit(cube,
                                       axis=0,
                                       prefix=outprefix + '_triple',
                                       nsig=nsig,
                                       nrsig=nrsig,
                                       vconv=vconv,
                                       xtora=xtora,
                                       ytodec=ytodec,
                                       doplot=doplot))
        adaptB[numpy.isnan(adaptB)] = 0
        pickle.dump(adaptB, open('%s_adaptB.pysav' % outprefix, 'w'))
    else:
        adaptB = pickle.load(open('%s_adaptB.pysav' % outprefix, 'r'))
    db = adaptB
    gcd = double_gaussian(db[3], db[4], db[0], db[1], db[5],
                          db[6])(indices(cube.shape)[0])
    fitsfile[0].data = gcd
    fitsfile.writeto('%s_adaptgausscube.fits' % outprefix, clobber=True)

    gcd[numpy.isnan(gcd)] = 0
    adaptResids = cube - gcd
    fitsfile[0].data = adaptResids
    fitsfile.writeto('%s_adaptgaussresids.fits' % outprefix, clobber=True)

    #adaptB[4] = (adaptB[4]-v0) / dv + p3-1
    #adaptB[3] = (adaptB[3]-v0) / dv + p3-1
    adaptB[4] = (adaptB[4] - p3 + 1) * dv + v0
    adaptB[3] = (adaptB[3] - p3 + 1) * dv + v0
    fitsfile[0].data = asarray(adaptB)
    fitsfile.writeto('%s_adaptgausspars.fits' % outprefix, clobber=True)

    fitsfile[0].header.__delitem__('CD3_3')
    fitsfile[0].header.__delitem__('CRVAL3')
    fitsfile[0].header.__delitem__('CRPIX3')
    fitsfile[0].header.__delitem__('CUNIT3')
    fitsfile[0].header.__delitem__('CTYPE3')

    adaptResids[numpy.isnan(adaptResids)] = 0
    totalDResids = adaptResids.sum(axis=0)
    fitsfile[0].data = totalDResids
    fitsfile.writeto('%s_adaptgauss_totalresids.fits' % outprefix,
                     clobber=True)

    return adaptB
コード例 #14
0
def wrap_collapse_gauss(filename, outprefix, redo='no'):
    """

    redo - if not equal to 'no', then...
    if collapse_gaussfit succeeded (to the extent that the .pysav files were written),
    but some part of the file writing or successive procedures failed, re-do those 
    procedures without redoing the whole collapse
    """
    fitsfile = pyfits.open(filename)
    dv, v0, p3 = fitsfile[0].header['CD3_3'], fitsfile[0].header[
        'CRVAL3'], fitsfile[0].header['CRPIX3']

    cube = fitsfile[0].data
    cube = where(numpy.isnan(cube), 0, cube)

    if redo == 'no':
        doubleB = asarray(collapse_double_gaussfit(cube, axis=0))
        doubleB[numpy.isnan(doubleB)] = 0
        pickle.dump(doubleB, open('%s_doubleB.pysav' % outprefix, 'w'))
    else:
        doubleB = pickle.load(open('%s_doubleB.pysav' % outprefix, 'r'))
    db = doubleB
    gcd = double_gaussian(db[3], db[4], db[0], db[1], db[5],
                          db[6])(indices(cube.shape)[0])
    fitsfile[0].data = gcd
    fitsfile.writeto('%s_doublegausscube.fits' % outprefix, clobber=True)

    gcd[numpy.isnan(gcd)] = 0
    doubleResids = cube - gcd
    fitsfile[0].data = doubleResids
    fitsfile.writeto('%s_doublegaussresids.fits' % outprefix, clobber=True)

    #doubleB[4] = (doubleB[4]-v0) / dv + p3-1
    #doubleB[3] = (doubleB[3]-v0) / dv + p3-1
    doubleB[4] = (doubleB[4] - p3 + 1) * dv + v0
    doubleB[3] = (doubleB[3] - p3 + 1) * dv + v0
    fitsfile[0].data = asarray(doubleB)
    fitsfile.writeto('%s_doublegausspars.fits' % outprefix, clobber=True)

    if redo == 'no':
        singleB = asarray(collapse_gaussfit(cube, axis=0))
        pickle.dump(singleB, open('%s_singleB.pysav' % outprefix, 'w'))
    else:
        singleB = pickle.load(open('%s_singleB.pysav' % outprefix, 'r'))
    gc = gaussian(singleB[1], singleB[0], singleB[2])(indices(cube.shape)[0])
    singleB[1] = (singleB[1] - p3 + 1) * dv + v0
    fitsfile[0].data = gc
    fitsfile.writeto('%s_singlegausscube.fits' % outprefix, clobber=True)

    gc[numpy.isnan(gc)] = 0
    singleResids = cube - gc
    fitsfile[0].data = singleResids
    fitsfile.writeto('%s_singlegaussresids.fits' % outprefix, clobber=True)
    fitsfile[0].data = asarray(singleB)
    fitsfile.writeto('%s_singlegausspars.fits' % outprefix, clobber=True)

    fitsfile[0].header.__delitem__('CD3_3')
    fitsfile[0].header.__delitem__('CRVAL3')
    fitsfile[0].header.__delitem__('CRPIX3')
    fitsfile[0].header.__delitem__('CUNIT3')
    fitsfile[0].header.__delitem__('CTYPE3')

    doubleResids[numpy.isnan(doubleResids)] = 0
    totalDResids = doubleResids.sum(axis=0)
    fitsfile[0].data = totalDResids
    fitsfile.writeto('%s_doublegauss_totalresids.fits' % outprefix,
                     clobber=True)

    singleResids[numpy.isnan(singleResids)] = 0
    totalSResids = singleResids.sum(axis=0)
    fitsfile[0].data = totalSResids
    fitsfile.writeto('%s_singlegauss_totalresids.fits' % outprefix,
                     clobber=True)

    return singleB, doubleB
コード例 #15
0
    def drawmeridians(self,meridians,color='k',linewidth=1., \
                      linestyle='--',dashes=[1,1],labels=[0,0,0,0],\
                      font='rm',fontsize=12):
        """
 draw meridians (longitude lines).

 meridians - list containing longitude values to draw (in degrees).
 color - color to draw meridians (default black).
 linewidth - line width for meridians (default 1.)
 linestyle - line style for meridians (default '--', i.e. dashed).
 dashes - dash pattern for meridians (default [1,1], i.e. 1 pixel on,
  1 pixel off).
 labels - list of 4 values (default [0,0,0,0]) that control whether
  meridians are labelled where they intersect the left, right, top or 
  bottom of the plot. For example labels=[1,0,0,1] will cause meridians
  to be labelled where they intersect the left and bottom of the plot,
  but not the right and top. Labels are drawn using mathtext.
 font - mathtext font used for labels ('rm','tt','it' or 'cal', default 'rm').
 fontsize - font size in points for labels (default 12).
        """
        # get current axes instance.
        ax = pylab.gca()
        # don't draw meridians past latmax, always draw parallel at latmax.
        latmax = 80. # not used for cyl, merc projections.
        # offset for labels.
	yoffset = (self.urcrnry-self.llcrnry)/100./self.aspect
	xoffset = (self.urcrnrx-self.llcrnrx)/100.

        if self.projection not in ['merc','cyl']:
            lats = pylab.arange(-latmax,latmax+1).astype('f')
        else:
            lats = pylab.arange(-90,91).astype('f')
        xdelta = 0.1*(self.xmax-self.xmin)
        ydelta = 0.1*(self.ymax-self.ymin)
        for merid in meridians:
            lons = merid*pylab.ones(len(lats),'f')
            x,y = self(lons,lats)
            # remove points outside domain.
            testx = pylab.logical_and(x>=self.xmin-xdelta,x<=self.xmax+xdelta)
            x = pylab.compress(testx, x)
            y = pylab.compress(testx, y)
            testy = pylab.logical_and(y>=self.ymin-ydelta,y<=self.ymax+ydelta)
            x = pylab.compress(testy, x)
            y = pylab.compress(testy, y)
            if len(x) > 1 and len(y) > 1:
                # split into separate line segments if necessary.
                # (not necessary for mercator or cylindrical).
                xd = (x[1:]-x[0:-1])**2
                yd = (y[1:]-y[0:-1])**2
                dist = pylab.sqrt(xd+yd)
                split = dist > 500000.
                if pylab.asum(split) and self.projection not in ['merc','cyl']:
                   ind = (pylab.compress(split,pylab.squeeze(split*pylab.indices(xd.shape)))+1).tolist()
                   xl = []
                   yl = []
                   iprev = 0
                   ind.append(len(xd))
                   for i in ind:
                       xl.append(x[iprev:i])
                       yl.append(y[iprev:i])
                       iprev = i
                else:
                    xl = [x]
                    yl = [y]
                # draw each line segment.
                for x,y in zip(xl,yl):
                    # skip if only a point.
                    if len(x) > 1 and len(y) > 1:
                        l = Line2D(x,y,linewidth=linewidth,linestyle=linestyle)
                        l.set_color(color)
                        l.set_dashes(dashes)
                        ax.add_line(l)
        # draw labels for meridians.
        # search along edges of map to see if parallels intersect.
        # if so, find x,y location of intersection and draw a label there.
        if self.projection == 'cyl':
            dx = 0.01; dy = 0.01
        else:
            dx = 1000; dy = 1000
        for dolab,side in zip(labels,['l','r','t','b']):
            if not dolab: continue
            # for cyl or merc, don't draw meridians on left or right.
            if self.projection in ['cyl','merc'] and side in ['l','r']: continue
            if side in ['l','r']:
	        nmax = int((self.ymax-self.ymin)/dy+1)
                if self.urcrnry < self.llcrnry:
	            yy = self.llcrnry-dy*pylab.arange(nmax)
                else:
	            yy = self.llcrnry+dy*pylab.arange(nmax)
                if side == 'l':
	            lons,lats = self(self.llcrnrx*pylab.ones(yy.shape,'f'),yy,inverse=True)
                else:
	            lons,lats = self(self.urcrnrx*pylab.ones(yy.shape,'f'),yy,inverse=True)
                lons = pylab.where(lons < 0, lons+360, lons)
                lons = [int(lon*10) for lon in lons.tolist()]
                lats = [int(lat*10) for lat in lats.tolist()]
            else:
	        nmax = int((self.xmax-self.xmin)/dx+1)
                if self.urcrnrx < self.llcrnrx:
	            xx = self.llcrnrx-dx*pylab.arange(nmax)
                else:
	            xx = self.llcrnrx+dx*pylab.arange(nmax)
                if side == 'b':
	            lons,lats = self(xx,self.llcrnry*pylab.ones(xx.shape,'f'),inverse=True)
                else:
	            lons,lats = self(xx,self.urcrnry*pylab.ones(xx.shape,'f'),inverse=True)
                lons = pylab.where(lons < 0, lons+360, lons)
                lons = [int(lon*10) for lon in lons.tolist()]
                lats = [int(lat*10) for lat in lats.tolist()]
            for lon in meridians:
                if lon<0: lon=lon+360.
                # find index of meridian (there may be two, so
                # search from left and right).
                try:
                    nl = lons.index(int(lon*10))
                except:
                    nl = -1
                try:
                    nr = len(lons)-lons[::-1].index(int(lon*10))-1
                except:
                    nr = -1
        	if lon>180:
        	    lonlab = r'$\%s{%g\/^{\circ}\/W}$'%(font,pylab.fabs(lon-360))
        	elif lon<180 and lon != 0:
        	    lonlab = r'$\%s{%g\/^{\circ}\/E}$'%(font,lon)
        	else:
        	    lonlab = r'$\%s{%g\/^{\circ}}$'%(font,lon)
                # meridians can intersect each map edge twice.
                for i,n in enumerate([nl,nr]):
                    lat = lats[n]/10.
                    # no meridians > latmax for projections other than merc,cyl.
                    if self.projection not in ['merc','cyl'] and lat > latmax: continue
                    # don't bother if close to the first label.
                    if i and abs(nr-nl) < 100: continue
                    if n >= 0:
                        if side == 'l':
        	            pylab.text(self.llcrnrx-xoffset,yy[n],lonlab,horizontalalignment='right',verticalalignment='center',fontsize=fontsize)
                        elif side == 'r':
        	            pylab.text(self.urcrnrx+xoffset,yy[n],lonlab,horizontalalignment='left',verticalalignment='center',fontsize=fontsize)
                        elif side == 'b':
        	            pylab.text(xx[n],self.llcrnry-yoffset,lonlab,horizontalalignment='center',verticalalignment='top',fontsize=fontsize)
                        else:
        	            pylab.text(xx[n],self.urcrnry+yoffset,lonlab,horizontalalignment='center',verticalalignment='bottom',fontsize=fontsize)

        # make sure axis ticks are turned off
        ax.set_xticks([]) 
        ax.set_yticks([])
        # set axes limits to fit map region.
        self.set_axes_limits()
コード例 #16
0
ファイル: collapse_gaussfit.py プロジェクト: Fade89/agpy
def gerr(xarr):
    return lambda p:xarr-gaussian(*p)(*indices(xarr.shape))
コード例 #17
0
def double_gerr(xarr):
    return lambda p: xarr - double_gaussian(*p)(*indices(xarr.shape))
コード例 #18
0
ファイル: collapse_gaussfit.py プロジェクト: Fade89/agpy
def triple_gerr(xarr):
    return lambda p:xarr-triple_gaussian(*p)(*indices(xarr.shape))
コード例 #19
0
def triple_gerr(xarr):
    return lambda p: xarr - triple_gaussian(*p)(*indices(xarr.shape))
コード例 #20
0
    img.show()
    return img

img = cropImage()

# read the cropped image directly into a numpy array 
imarray = numpy.array(img)
print("Numpy array shape:", imarray.shape)
print("Cropped image size", img.size)

# Create the gaussian data
data = imarray
pylab.matshow(data, cmap='gist_rainbow')
params = fg.fitgaussian(data)
fit = fg.gaussian(*params)
pylab.contour(fit(*pylab.indices(data.shape)), cmap='copper')
ax = pylab.gca()
(height, x, y, width_x, width_y) = params

legend = """
x : {:.1f}
y : {:.1f}
width_x : {:.1f}
width_y : {:.1f}""".format(x, y, width_x, width_y)
pylab.text(x = 0.95, 
           y = 0.05, 
           s = legend, 
           fontsize = 16, 
           horizontalalignment = 'right', 
           verticalalignment = 'bottom', 
           transform = ax.transAxes)
コード例 #21
0
        # removed 'uranus_070927_ob7-8_mask_v2.0_0pca_coalign_map10.fits',
        # removed 'uranus_070927_ob9-0_mask_v2.0_0pca_coalign_map10.fits',
        # removed 'uranus_091210_ob1-2_mask_v2.0_0pca_coalign_map10.fits',
        # removed 'uranus_091210_ob3-4_mask_v2.0_0pca_coalign_map10.fits',
        # removed 'uranus_091210_ob5-6_mask_v2.0_0pca_coalign_map10.fits',
        # removed 'uranus_091210_ob7-8_mask_v2.0_0pca_coalign_map10.fits',
        'uranus_091216_ob8-9_mask_v2.0_0pca_coalign_map10.fits',
        'uranus_091219_o15-6_mask_v2.0_0pca_coalign_map10.fits',
        'uranus_091220_ob1-2_mask_v2.0_0pca_coalign_map10.fits',
        'uranus_091224_o10-9_mask_v2.0_0pca_coalign_map10.fits',
    ]
    if sample == 'notmars':
        #filelist = [ a for a in filelist  if a.find('mars')==-1 ]
        #filelist = filelist[:4]
        imstack = pylab.zeros([300, 300, len(filelist)])
        xx, yy = pylab.indices([300, 300])
elif sample == 'dec2011':
    filelist = [
        a for b in readcol(
            '/Users/adam/work/bgps_pipeline/plotting/lists/pointsource_ds2_13pca_default.list'
        ) for a in b
    ]
elif sample == 'dec2011notmars':
    filelist = [
        a for b in readcol(
            '/Users/adam/work/bgps_pipeline/plotting/lists/pointsource_ds2_13pca_default.list'
        ) for a in b if 'mars' not in a
    ]
    marslist = [
        a for b in readcol(
            '/Users/adam/work/bgps_pipeline/plotting/lists/pointsource_ds2_13pca_default.list'
コード例 #22
0
# draw the edge of the map projection region (the projection limb)
map.drawmapboundary()
# draw lat/lon grid lines every 30 degrees.
map.drawmeridians(p.arange(0,360,30))
map.drawparallels(p.arange(-90,90,30))
# lat/lon coordinates of five cities.
lats=[40.02,32.73,38.55,48.25,17.29]
lons=[-105.16,-117.16,-77.00,-114.21,-88.10]
cities=['Boulder, CO','San Diego, CA',
        'Washington, DC','Whitefish, MT','Belize City, Belize']
# compute the native map projection coordinates for cities.
x,y = map(lons,lats)
# plot filled circles at the locations of the cities.
map.plot(x,y,'bo')
# plot the names of those five cities.
for name,xpt,ypt in zip(cities,x,y):
    p.text(xpt+50000,ypt+50000,name,fontsize=9)
# make up some data on a regular lat/lon grid.
nlats = 73; nlons = 145; delta = 2.*p.pi/(nlons-1)
lats = (0.5*p.pi-delta*p.indices((nlats,nlons))[0,:,:])
lons = (delta*p.indices((nlats,nlons))[1,:,:])
wave = 0.75*(p.sin(2.*lats)**8*p.cos(4.*lons))
mean = 0.5*p.cos(2.*lats)*((p.sin(2.*lats))**2 + 2.)
# compute native map projection coordinates of lat/lon grid.
x, y = map(lons*180./p.pi, lats*180./p.pi)
# contour data over the map.
cs = map.contour(x,y,wave+mean,15,linewidths=1.5)
p.show()
#p.savefig('wiki_example.ps')

コード例 #23
0
map.drawmeridians(p.arange(0, 360, 30))
map.drawparallels(p.arange(-90, 90, 30))
# lat/lon coordinates of five cities.
lats = [40.02, 32.73, 38.55, 48.25, 17.29]
lons = [-105.16, -117.16, -77.00, -114.21, -88.10]
cities = [
    'Boulder, CO', 'San Diego, CA', 'Washington, DC', 'Whitefish, MT',
    'Belize City, Belize'
]
# compute the native map projection coordinates for cities.
x, y = map(lons, lats)
# plot filled circles at the locations of the cities.
map.plot(x, y, 'bo')
# plot the names of those five cities.
for name, xpt, ypt in zip(cities, x, y):
    p.text(xpt + 50000, ypt + 50000, name, fontsize=9)
# make up some data on a regular lat/lon grid.
nlats = 73
nlons = 145
delta = 2. * p.pi / (nlons - 1)
lats = (0.5 * p.pi - delta * p.indices((nlats, nlons))[0, :, :])
lons = (delta * p.indices((nlats, nlons))[1, :, :])
wave = 0.75 * (p.sin(2. * lats)**8 * p.cos(4. * lons))
mean = 0.5 * p.cos(2. * lats) * ((p.sin(2. * lats))**2 + 2.)
# compute native map projection coordinates of lat/lon grid.
x, y = map(lons * 180. / p.pi, lats * 180. / p.pi)
# contour data over the map.
cs = map.contour(x, y, wave + mean, 15, linewidths=1.5)
p.show()
#p.savefig('wiki_example.ps')
コード例 #24
0
    return img


img = cropImage()

# read the cropped image directly into a numpy array
imarray = numpy.array(img)
print "Numpy array shape:", imarray.shape
print "Cropped image size", img.size

# Create the gaussian data
data = imarray
pylab.matshow(data, cmap='gist_rainbow')
params = fa.fitgaussian(data)
fit = fa.gaussian(*params)
pylab.contour(fit(*pylab.indices(data.shape)), cmap='copper')
ax = pylab.gca()
(height, x, y, width_x, width_y) = params

legend = """
x : {:.1f}
y : {:.1f}
width_x : {:.1f}
width_y : {:.1f}""".format(x, y, width_x, width_y)
pylab.text(x=0.95,
           y=0.05,
           s=legend,
           fontsize=16,
           horizontalalignment='right',
           verticalalignment='bottom',
           transform=ax.transAxes)
コード例 #25
0
from pylab import zeros, ones, indices, uint8
from PIL import Image
rows = 1024
patterns = 7
data = zeros((patterns, rows, rows))
for i in range(patterns):
    divisions = 2 ** (i + 1)
    step = rows / divisions
    period = 2 * step
    data[i] = ones((rows, rows)) * ((indices((rows, rows))[1] % period) > step)
    img = Image.fromarray(255 * data[i].astype(uint8), mode='L')
    img.save("output/pattern_{}.png".format(i + 1))