Example #1
0
    def display(self, xaxis, alpha, new=True):
        """
        E.display(xaxis, alpha = .8)

        :Arguments: xaxis, alpha

        Plots the CI region on the current figure, with respect to
        xaxis, at opacity alpha.

        :Note: The fill color of the envelope will be self.mass
            on the grayscale.
        """
        if new:
            figure()
        if self.ndim == 1:
            if self.mass>0.:
                x = concatenate((xaxis,xaxis[::-1]))
                y = concatenate((self.lo, self.hi[::-1]))
                fill(x,y,facecolor='%f' % self.mass,alpha=alpha, label = ('centered CI ' + str(self.mass)))
            else:
                pyplot(xaxis,self.value,'k-',alpha=alpha, label = ('median'))
        else:
            if self.mass>0.:
                subplot(1,2,1)
                contourf(xaxis[0],xaxis[1],self.lo,cmap=cm.bone)
                colorbar()
                subplot(1,2,2)
                contourf(xaxis[0],xaxis[1],self.hi,cmap=cm.bone)
                colorbar()
            else:
                contourf(xaxis[0],xaxis[1],self.value,cmap=cm.bone)
                colorbar()
Example #2
0
def hinton(W, out_file=None, maxWeight=None):
    """
    Draws a Hinton diagram for visualizing a weight matrix. 
    Temporarily disables matplotlib interactive mode if it is on, 
    otherwise this takes forever.
    """
    reenable = False
    if P.isinteractive():
        P.ioff()
    P.clf()
    height, width = W.shape
    if not maxWeight:
        maxWeight = 2**N.ceil(N.log(N.max(N.abs(W)))/N.log(2))

    P.gca().set_position([0, 0, 1, 1])
    P.fill(N.array([0,width,width,0]),N.array([0,0,height,height]),'gray')
    P.axis('off')
    P.axis('equal')
    for x in xrange(width):
        for y in xrange(height):
            _x = x+1
            _y = y+1
            w = W[y,x]
            if w > 0:
                _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white')
            elif w < 0:
                _blob(_x - 0.5, height - _y + 0.5, min(1,-w/maxWeight),'black')
    if reenable:
        P.ion()
    #P.show()
    if out_file:
        #P.savefig(out_file, format='png', bbox_inches='tight', pad_inches=0)
        fig = P.gcf()
        fig.subplots_adjust()
        fig.savefig(out_file)
def plotSingleXZ(posAll, i):
    ax = pylab.fill([-setup.x-plotFrame,setup.x+plotFrame,setup.x+plotFrame,-setup.x-plotFrame],[-setup.z-plotFrame,-setup.z-plotFrame,setup.z+plotFrame,setup.z+plotFrame],'r')
    bx = pylab.fill([-setup.x,setup.x,setup.x,-setup.x],[-setup.z,-setup.z,setup.z,setup.z],'w')
    pylab.plot([posAll[i][:,0], posAll[i][:,0]], 
               [posAll[i][:,2], posAll[i][:,2]],
               'k.', markersize=5.)
    return
def plotSingleXY(posAll, i):
    ax = pylab.fill([-setup.x-plotFrame,setup.x+plotFrame,setup.x+plotFrame,-setup.x-plotFrame],[-setup.y-plotFrame,-setup.y-plotFrame,setup.y+plotFrame,setup.y+plotFrame],'r')
    bx = pylab.fill([-setup.x,setup.x,setup.x,-setup.x],[-setup.y,-setup.y,setup.y,setup.y],'w')
    pylab.plot([posAll[i][:,0], posAll[i][:,0]], 
               [posAll[i][:,1], posAll[i][:,1]],
               'k.', markersize=5.)
    return
def plotSingleYZ(posAll, i):
    ax = pylab.fill([-setup.y-plotFrame,setup.y+plotFrame,setup.y+plotFrame,-setup.y-plotFrame],[-setup.z-plotFrame,-setup.z-plotFrame,setup.z+plotFrame,setup.z+plotFrame],'r')
    bx = pylab.fill([-setup.y,setup.y,setup.y,-setup.y],[-setup.z,-setup.z,setup.z,setup.z],'w')
    pylab.plot([posAll[i][:,1], posAll[i][:,1]], 
               [posAll[i][:,2], posAll[i][:,2]],
               'r.', markersize=5.)
    return
def hinton(W,filename="hinton.pdf", maxWeight=None):
    """
    Draws a Hinton diagram for visualizing a weight matrix. 
    Temporarily disables matplotlib interactive mode if it is on, 
    otherwise this takes forever.
    """
    reenable = False
    if P.isinteractive():
        P.ioff()
    P.clf()
    ax=P.subplot(111)
    height, width = W.shape
    if not maxWeight:
        maxWeight = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2))

    P.fill(np.array([0,width,width,0]),np.array([0,0,height,height]),'gray')
    P.axis('off')
    #P.axis('equal')
    ax.set_yticklabels(['25','20','15','10','5','0'])
    for x in xrange(width):
        for y in xrange(height):
            _x = x+1
            _y = y+1
            w = W[y,x]
            if w > 0:
                _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white')
            elif w < 0:
                _blob(_x - 0.5, height - _y + 0.5, min(1,-w/maxWeight),'black')
    if reenable:
        P.ion()
    P.title(filename)
    P.savefig(filename)
Example #7
0
    def plot_opt_allocation(self, df, file=None):
        try:
            import pylab
        except ImportError:
            pass
        else:
            xs = df[self.symbols].values
            risks = df['std'].values.tolist()
            pylab.figure()

            r = risks[-1::-1] + risks
            cp = [x[0] for x in xs]
            pylab.fill(risks + [.0], cp + [0.0], "g", label=self.symbols[0])

            for i in range(1, len(self.symbols)):
                cn = [sum(x[0:i]) for x in xs]
                c = cn[-1::-1] + cp
                label = self.symbols[i]  # "x%d" % i
                cr = (i * 32 + 0x80) % 255
                cg = (i * 16 + 0x80) % 255
                cb = (i * 64 + 0x80) % 255
                color = "#%02x%02x%02x" % (cr, cg, cb)

                pylab.fill(r, c, label=label, facecolor=color)
                cp = cn

            pylab.legend()
            pylab.xlabel('standard deviation')
            pylab.ylabel('allocation')
            pylab.title('Optimal allocations (fig 4.12)')

            if file is not None:
                pylab.savefig(file)
            else:
                pylab.show()
Example #8
0
File: genome.py Project: PMBio/sqtl
def plot_posterior_ci(locs, mean, sd, color, alpha_multiplier=0.1, rm=True):
    x_ci = SP.array(list(locs) + list(locs)[::-1])
    y_ci = SP.array(list(mean) + list(mean)[::-1])
    if rm: y_ci = 1. - y_ci
    sds = SP.array(list(sd) + list(-sd)[::-1])
    PL.fill(x_ci, y_ci + sds, color, alpha=alpha_multiplier)
    PL.fill(x_ci, y_ci + 2*sds, color, alpha=2*alpha_multiplier) 
Example #9
0
def fibo_boxes(N=10, x_padding=0., y_padding=0., clr_0=None, fill_alpha=.6):
	F=Fibos(N_stop=N)
	plt.figure(0)
	plt.clf()
	#
	colors_ =  mpl.rcParams['axes.color_cycle']
	dy,dx=range(2)
	x=0
	y=0
	for j,f in enumerate(F[1:]):
		side_len=f
		if clr_0==None:
			clr = colors_[j%len(colors_)]
		else:
			clr = clr_0
		#
		square = zip(*[[x,y], [x+side_len, y], [x+side_len,y+side_len], [x, y+side_len], [x,y]])
		print square
		plt.plot(*square, marker='', ls='-', lw=2.5, color=clr)
		plt.fill(*square, color=clr, alpha=fill_alpha)
		#
		x=x+dx*(side_len + x_padding*side_len) - dy*(F[j] + y_padding*side_len)
		y=y+dy*(side_len + y_padding*side_len) - dx*(F[j] + x_padding*side_len)
		
		#
		dx = (1+dx)%2
		dy = (1+dy)%2
	#
	ax=plt.gca()
	ax.set_ylim([-.1*max(square[1]), 1.1*max(square[1])])
	ax.set_xlim([-.1*max(square[0]), 1.1*max(square[0])])
Example #10
0
def wiggle(Data,SH,skipt=1,maxval=8,lwidth=.1):
        """
        wiggle(Data,SH)
        """
        import pylab
                
        t = range(SH['ns'])
#       t = range(SH['ns'])*SH['dt']/1000000;

        for i in range(0,SH['ntraces'],skipt):
#               trace=zeros(SH['ns']+2)
#               dtrace=Data[:,i]
#               trace[1:SH['ns']]=Data[:,i]
#               trace[SH['ns']+1]=0
                trace=Data[:,i]
                trace[0]=0
                trace[SH['ns']-1]=0     
                pylab.plot(i+trace/maxval,t,color='black',linewidth=lwidth)
                for a in range(len(trace)):
                        if (trace[a]<0):
                                trace[a]=0;
                # pylab.fill(i+Data[:,i]/maxval,t,color='k',facecolor='g')
                pylab.fill(i+Data[:,i]/maxval,t,'k',linewidth=0)
        pylab.title(SH['filename'])
        pylab.grid(True)
Example #11
0
def hinton(W, maxWeight=None):
    """
    Source: http://wiki.scipy.org/Cookbook/Matplotlib/HintonDiagrams
    Draws a Hinton diagram for visualizing a weight matrix.
    Temporarily disables matplotlib interactive mode if it is on,
    otherwise this takes forever.
    """
    reenable = False
    if pl.isinteractive():
        pl.ioff()
    pl.clf()
    height, width = W.shape
    if not maxWeight:
        maxWeight = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2))

    pl.fill(np.array([0,width,width,0]),np.array([0,0,height,height]),'gray')
    pl.axis('off')
    pl.axis('equal')
    for x in xrange(width):
        for y in xrange(height):
            _x = x+1
            _y = y+1
            w = W[y,x]
            if w > 0:
                _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white')
            elif w < 0:
                _blob(_x - 0.5, height - _y + 0.5, min(1,-w/maxWeight),'black')
    if reenable:
        pl.ion()
    pl.show()
Example #12
0
 def fill_gamut_slice (v0, v1, v2):
     '''Fill in a slice of the monitor gamut with the correct colors.'''
     #num_s, num_t = 10, 10
     #num_s, num_t = 25, 25
     num_s, num_t = 50, 50
     dv10 = v1 - v0
     dv21 = v2 - v1
     for i_s in range (num_s):
         s_a = float (i_s)   / float (num_s)
         s_b = float (i_s+1) / float (num_s)
         for i_t in range (num_t):
             t_a = float (i_t)   / float (num_t)
             t_b = float (i_t+1) / float (num_t)
             # vertex coords
             v_aa = v0 + t_a * (dv10 + s_a * dv21)
             v_ab = v0 + t_b * (dv10 + s_a * dv21)
             v_ba = v0 + t_a * (dv10 + s_b * dv21)
             v_bb = v0 + t_b * (dv10 + s_b * dv21)
             # poly coords
             poly_x = [v_aa [0], v_ba [0], v_bb [0], v_ab [0]]
             poly_y = [v_aa [1], v_ba [1], v_bb [1], v_ab [1]]
             # average color
             avg = 0.25 * (v_aa + v_ab + v_ba + v_bb)
             # convert to rgb and scale to maximum displayable brightness
             color_string = get_brightest_irgb_string (avg)
             pylab.fill (poly_x, poly_y, color_string, edgecolor=color_string)
Example #13
0
def plot1d(x,y,cadence,lcolor,lwidth,fcolor,falpha,underfill):

# pad first and last points in case a fill is required

    x = insert(x,[0],[x[0]]) 
    x = append(x,[x[-1]])
    y = insert(y,[0],[-1.0e10]) 
    y = append(y,-1.0e10)

# plot data so that data gaps are not spanned by a line

    ltime = array([],dtype='float64')
    ldata = array([],dtype='float32')
    for i in range(1,len(x)-1):
        if (x[i] - x[i-1]) < 2.0 * cadence / 86400:
            ltime = append(ltime,x[i])
            ldata = append(ldata,y[i])
        else:
            pylab.plot(ltime,ldata,color=lcolor,linestyle='-',linewidth=lwidth)
            ltime = array([],dtype='float64')
            ldata = array([],dtype='float32')
    pylab.plot(ltime,ldata,color=lcolor,linestyle='-',linewidth=lwidth)

# plot the fill color below data time series, with no data gaps

    if underfill:
        pylab.fill(x,y,fc=fcolor,linewidth=0.0,alpha=falpha)

        return
def draw_lorentzian(x,positions,intensities,linewidth,i,vspace):
    for j in range(len(intensities)):
        p = [intensities[j],positions[j],linewidth[j]]
        print p
        lor = Lorentzian(x,p)
        pylab.fill(x,lor+(i*vspace),'b',alpha=0.1)
    return 
Example #15
0
def plot_S2s_over_sequence(S2s_list, label_list, plot_fn, ss_info=None, legend=False, errors_list=None):
    if errors_list != None:
        for S2s, errors, label in zip(S2s_list, errors_list, label_list):
            print range(1, S2s.shape[0]), S2s[1:]
            pylab.errorbar(range(S2s.shape[0]), S2s, fmt="b-", label=label, yerr=errors)
    else:
        for S2s, label in zip(S2s_list, label_list):
            pylab.plot(S2s, "-", label=label)

    # add faded background in SS regions
    if ss_info != None:
        for res_num in ss_info.get_res_nums():
            if ss_info.is_structured(res_num):
                #print "Found SS:", res_num
                x=res_num
                pylab.fill([x-.5,x-.5,x+.5,x+.5], [0,1,1,0], alpha=.3, edgecolor='w')

    #pylab.title("NH order parameters")
    #pylab.ylabel("Order parameter")
    pylab.xlabel("Residue number")
    pylab.ylim(ymax=1)
    pylab.grid()
    if legend: pylab.legend(label_list, prop=matplotlib.font_manager.FontProperties(size='6'), loc='lower right')
    print "Writing ", plot_fn
    pylab.savefig(plot_fn)
Example #16
0
def do_plot(date, flux, status=0):
    xmin = min(date)
    xmax = max(date)
    ymin = min(flux)
    ymax = max(flux)
    xr = xmax - xmin
    yr = ymax - ymin
    try:
        params = {
            "backend": "png",
            "axes.linewidth": 2.5,
            "axes.labelsize": 24,
            "axes.font": "sans-serif",
            "axes.fontweight": "bold",
            "text.fontsize": 12,
            "legend.fontsize": 12,
            "xtick.labelsize": 16,
            "ytick.labelsize": 16,
        }
        rcParams.update(params)
    except:
        print("ERROR -- KEPCLIP: install latex for scientific plotting")
        status = 1

    if status == 0:
        # 		plt.figure(figsize=[12,5])
        plt.clf()
    # 	plt.axes([0.2,0.2,0.94,0.88])
    # 	ltime = [date[0]]; ldata = [flux[0]]
    # 	for i in range(1,len(flux)):
    #            if (date[i-1] > date[i] - 0.025):
    #                ltime.append(date[i])
    #                ldata.append(flux[i])
    #            else:
    #                ltime = n.array(ltime, dtype='float64')
    #                ldata = n.array(ldata, dtype='float64')
    #                plt.plot(ltime,ldata,color='#0000ff',linestyle='-'
    #                	,linewidth=1.0)
    #                ltime = []; ldata = []
    # 	ltime = n.array(ltime, dtype='float64')
    # 	ldata = n.array(ldata, dtype='float64')

    plt.plot(date, flux, color="#0000ff", linestyle="-", linewidth=1.0)
    date = n.insert(date, [0], [date[0]])
    date = n.append(date, [date[-1]])
    flux = n.insert(flux, [0], [0.0])
    flux = n.append(flux, [0.0])
    plt.fill(date, flux, fc="#ffff00", linewidth=0.0, alpha=0.2)
    plt.xlim(xmin - xr * 0.01, xmax + xr * 0.01)
    if ymin - yr * 0.01 <= 0.0:
        plt.ylim(1.0e-10, ymax + yr * 0.01)
    else:
        plt.ylim(ymin - yr * 0.01, ymax + yr * 0.01)
    xlab = "BJD"
    ylab = "e- / cadence"
    plt.xlabel(xlab, {"color": "k"})
    plt.ylabel(ylab, {"color": "k"})
    plt.ion()
    plt.grid()
    plt.ioff()
Example #17
0
    def etch(self, refmask=[0]):
        """Cut away at surface. Can only click polygons for now.
        Optionally input reference mask to guide etching.
        """

        size = self.size
        mask = n.ones((self.size,self.size), dtype='bool')

        print 'Click for points of region to etch (right click to exit).'
        p.figure(1)
        if len(refmask) != 1:
            p.imshow(n.transpose(-refmask), aspect='auto', origin='lower', interpolation='nearest', cmap=p.cm.Greys, extent=(0,1,0,1), vmax=0.5)
        else:
            p.imshow(n.transpose(-self.mask), aspect='auto', origin='lower', interpolation='nearest', cmap=p.cm.Greys, extent=(0,1,0,1), vmax=0.5)
        xy = p.ginput(n=0, timeout=3000)
        xy = n.array(xy)
        
        print 'Calculating remaining region...'
        p.figure(1)
        p.axis([0,1,0,1])
        p.fill(xy[:,0],xy[:,1],'k')

        for i in range(size):
            for j in range(size):
                mask[i,j] = not(point_inside_polygon(float(i)/size, float(j)/size, xy))
        self.mask = self.mask * mask
Example #18
0
def plot_envelope(M,C,mesh):
    """
    plot_envelope(M,C,mesh)


    plots the pointwise mean +/- sd envelope defined by M and C
    along their base mesh.


    :Arguments:

        -   `M`: A Gaussian process mean.

        -   `C`: A Gaussian process covariance

        -   `mesh`: The mesh on which to evaluate the mean and cov.
    """

    try:
        from pylab import fill, plot, clf, axis
        x=concatenate((mesh, mesh[::-1]))
        sig = sqrt(abs(C(mesh)))
        mean = M(mesh)
        y=concatenate((mean-sig, (mean+sig)[::-1]))
        # clf()
        fill(x,y,facecolor='.8',edgecolor='1.')
        plot(mesh, mean, 'k-.')
    except ImportError:
        print "Matplotlib is not installed; plotting is disabled."
Example #19
0
def draw_(g, color_dict):

    'Draw a shapelyGeometry; thanks to Sean Gilles'
    gType = g.geom_type
    if gType == 'Point':
        pl.plot(g.x, g.y, 'k,')
    elif gType == 'LineString':
        x, y = g.xy
        pl.plot(x, y, 'b-', color=color_dict["line"])
    elif gType == 'Polygon':
        #can draw parts as multiple colors
        if not color_dict:
            color_dict={"fill":get_random_color(), 
                        "line":"#666666",
                        "hole_fill":"#FFFFFF", 
                        "hole_line":"#999999" }
    
    
        x, y = g.exterior.xy
        pl.fill(x, y, color=color_dict["fill"], aa=True) 
        pl.plot(x, y, color=color_dict["line"], aa=True, lw=1.0)
        for hole in g.interiors:
            x, y = hole.xy
            pl.fill(x, y, color=color_dict["hole_fill"], aa=True) 
            pl.plot(x, y, color=color_dict["hole_line"], aa=True, lw=1.0)
Example #20
0
    def hinton(W, max_weight=None, names=(names, worst_names)):
        """
        Draws a Hinton diagram for visualizing a weight matrix.
        Temporarily disables matplotlib interactive mode if it is on,
        otherwise this takes forever.
        """
        reenable = False
        if P.isinteractive():
            P.ioff()
        P.clf()
        height, width = W.shape
        if not max_weight:
            max_weight = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2))

        P.fill(np.array([0, width, width, 0]), np.array([0, 0, height, height]), 'gray')
        P.axis('off')
        P.axis('equal')
        cmap = plt.get_cmap('RdYlGn')
        for x in range(width):
            if names:
                plt.text(-0.5, x, names[0][x], fontsize=7, ha='right', va='bottom')
                plt.text(x, height+0.5, names[1][height-x-1], fontsize=7, va='bottom', rotation='vertical', ha='left')
            for y in range(height):
                _x = x+1
                _y = y+1
                w = W[y, x]
                if w > 0:
                    _blob(_x - 0.5, height - _y + 0.5, min(1, w/max_weight), color=cmap(w/max_weight))
                elif w < 0:
                    _blob(_x - 0.5, height - _y + 0.5, min(1, -w/max_weight), 'black')
        if reenable:
            P.ion()
        P.show()
Example #21
0
File: lr.py Project: pekkosk/hotbit
    def plot_spectrum(self, filename, width=0.2, xlim=None):
        """ Make pretty plot of the linear response. 
        
        Parameters:
        ===========
        filename: output file name (&format, supported by matplotlib)
        width:    width of Lorenzian broadening 
        xlim:     energy range for plotting tuple (emin,emax)
        """
        import pylab as pl

        if not self.done:
            self.run()

        e, f = mix.broaden(self.omega * Hartree, self.F, width=width, N=1000, extend=True)
        f = f / max(abs(f))

        pl.plot(e, f, lw=2)
        xs, ys = pl.poly_between(e, 0, f)
        pl.fill(xs, ys, fc="b", ec="b", alpha=0.5)
        pl.ylim(0, 1.2)

        if xlim == None:
            pl.xlim(0, self.emax * Hartree * 1.2)
        else:
            pl.xlim(xlim)
        pl.xlabel("energy (eV)")
        pl.ylabel("linear optical response")
        pl.title("Optical response")
        pl.savefig(filename)
        # pl.show()
        pl.close()
Example #22
0
def drawDef(dfeat,dy,dx,mindef=0.001,distr="father"):
    """
        auxiliary funtion to draw recursive levels of deformation
    """
    from matplotlib.patches import Ellipse
    pylab.ioff()
    if distr=="father":
        py=[0,0,2,2];px=[0,2,0,2]
    if distr=="child":
        py=[0,1,1,2];px=[1,2,0,1]
    ordy=[0,0,1,1];ordx=[0,1,0,1]
    x1=-0.5+dx;x2=2.5+dx
    y1=-0.5+dy;y2=2.5+dy
    if distr=="father":       
        pylab.fill([x1,x1,x2,x2,x1],[y1,y2,y2,y1,y1],"r", alpha=0.15, edgecolor="b",lw=1)    
    for l in range(len(py)):
        aux=dfeat[ordy[l],ordx[l],:].clip(-1,-mindef)
        wh=numpy.exp(-mindef/aux[0])/numpy.exp(1);hh=numpy.exp(-mindef/aux[1])/numpy.exp(1)
        e=Ellipse(xy=[(px[l]+dx),(py[l]+dy)], width=wh, height=hh, alpha=0.35)
        x1=-0.75+dx+px[l];x2=0.75+dx+px[l]
        y1=-0.76+dy+py[l];y2=0.75+dy+py[l]
        col=numpy.array([wh*hh]*3).clip(0,1)
        if distr=="father":
            col[0]=0       
        e.set_facecolor(col)
        pylab.gca().add_artist(e)
        if distr=="father":       
            pylab.fill([x1,x1,x2,x2,x1],[y1,y2,y2,y1,y1],"b", alpha=0.15, edgecolor="b",lw=1)            
def hinton(W, maxWeight=None):
    """
    Draws a Hinton diagram for visualizing a weight matrix. 
    Temporarily disables matplotlib interactive mode if it is on, 
    otherwise this takes forever.
    """
    reenable = False
    if P.isinteractive():
        P.ioff()
    P.clf()
    height, width = W.shape
    if not maxWeight:
        maxWeight = 2**N.ceil(N.log(N.max(N.abs(W)))/N.log(2))

    P.fill(N.array([0,width,width,0]),N.array([0,0,height,height]),'gray')
    P.axis('off')
    P.axis('equal')
    for x in xrange(width):
        for y in xrange(height):
            _x = x+1
            _y = y+1
            w = W[y,x]
            if w > 0:
                _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white')
            elif w < 0:
                _blob(_x - 0.5, height - _y + 0.5, min(1,-w/maxWeight),'black')
    if reenable:
        P.ion()
    P.show()
 def myimshow(*args, **kwargs):
     x0,x1,y0,y1 = imExt(afwimg)
     plt.fill([x0,x0,x1,x1,x0],[y0,y1,y1,y0,y0], color=(1,1,0.8),
              zorder=20)
     plt.imshow(*args, zorder=25, **kwargs)
     plt.xticks([]); plt.yticks([])
     plt.axis(imExt(afwimg))
Example #25
0
def spectrum_subplot (spectrum):
    '''Plot a spectrum, with x-axis the wavelength, and y-axis the intensity.
    The curve is colored at that wavelength by the (approximate) color of a
    pure spectral color at that wavelength, with intensity constant over wavelength.
    (This means that dark looking colors here mean that wavelength is poorly viewed by the eye.

    This is not a complete plotting function, e.g. no file is saved, etc.
    It is assumed that this function is being called by one that handles those things.'''
    (num_wl, num_cols) = spectrum.shape
    # get rgb colors for each wavelength
    rgb_colors = numpy.empty ((num_wl, 3))
    for i in xrange (0, num_wl):
        wl_nm = spectrum [i][0]
        xyz = ciexyz.xyz_from_wavelength (wl_nm)
        rgb_colors [i] = colormodels.rgb_from_xyz (xyz)
    # scale to make brightest rgb value = 1.0
    rgb_max = numpy.max (rgb_colors)
    scaling = 1.0 / rgb_max
    rgb_colors *= scaling        
    # draw color patches (thin vertical lines matching the spectrum curve) in color
    for i in xrange (0, num_wl-1):    # skipping the last one here to stay in range
        x0 = spectrum [i][0]
        x1 = spectrum [i+1][0]
        y0 = spectrum [i][1]
        y1 = spectrum [i+1][1]
        poly_x = [x0,  x1,  x1, x0]
        poly_y = [0.0, 0.0, y1, y0]
        color_string = colormodels.irgb_string_from_rgb (rgb_colors [i])
        pylab.fill (poly_x, poly_y, color_string, edgecolor=color_string)
    # plot intensity as a curve
    pylab.plot (
        spectrum [:,0], spectrum [:,1],
        color='k', linewidth=2.0, antialiased=True)
Example #26
0
def saveHintonDiagram(W, directory):
    maxWeight = None
    #print "Weight: ", W
    """
    Draws a Hinton diagram for visualizing a weight matrix. 
    Temporarily disables matplotlib interactive mode if it is on, 
    otherwise this takes forever.
    """
    reenable = False
    if pylab.isinteractive():
        pylab.ioff()
    pylab.clf()
    height, width = W.shape
    if not maxWeight:
        maxWeight = 2**numpy.ceil(numpy.log(numpy.max(numpy.abs(W)))/numpy.log(2))

    pylab.fill(numpy.array([0,width,width,0]),numpy.array([0,0,height,height]),'gray')
    pylab.axis('off')
    pylab.axis('equal')
    for x in xrange(width):
        for y in xrange(height):
            _x = x+1
            _y = y+1
            w = W[y,x]
            if w > 0:
                _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white')
            elif w < 0:
                _blob(_x - 0.5, height - _y + 0.5, min(1,-w/maxWeight),'black')
    if reenable:
        pylab.ion()
    #pylab.show()
    pylab.savefig(directory)
Example #27
0
def voronoi(cdl,maskPoly,showMap=False):
	"""
	Расчитывает полигоны тиссена для каждой станции из cdl ограниченые контуром полигона
	Возвращает словарь {индекс станции: Полигон shapely}
	Если у станции нету полигона внутри задоного контура, будет стоять None
	"""
	from altCli import metaData
	pl=dict()
	if type(cdl)==dict:
		pl=cdl
	elif isinstance(cdl, metaData):
		pl={ind:(meta['lon'], meta['lat']) for ind,meta in cdl.stMeta.items()}
	else:
		raise ValueError, "First argument should be {ind:(lon, lat)} dict or metaData instance"
	lats=[meta[0] for ind,meta in pl.items()]
	lons=[meta[1] for ind,meta in pl.items()]
	box=list(maskPoly.bounds) #(minx, miny, maxx, maxy) [90, -180, -90, 180]
	bbox=[max(lats) if max(lats)>box[3] else box[3],min(lons) if min(lons)<box[0] else box[0],
	      min(lats) if min(lats)<box[1] else box[1],max(lons) if max(lons)>box[2] else box[2]]
	vl=voronoi_poly.VoronoiPolygons(pl, PlotMap=False)#, BoundingBox=bbox
	result=dict()
	for ind, r in vl.items():
		try:
			res=maskPoly.intersection(r['obj_polygon'])
		except shapely.geos.TopologicalError:
			result[r['info']]=None
			continue
		if res.geom_type=='MultiPolygon':
			point=Point(r["coordinate"][0],r["coordinate"][1])
			for ply in res.geoms:
				if ply.contains(point):
					res=ply
					break
			else:
				plylist=[v for v in res.geoms]
				plylist.sort(key=lambda a: a.area)
				res=plylist[-1]
		elif res.geom_type=='GeometryCollection':
			if res.is_empty:
				res=None
			else:
				print res
		elif res.geom_type=='Polygon':
			pass
		else:
			print res
		result[r['info']]=res

	if showMap is True:
		from pylab import fill,show
		for i,poly in result.items():
			if poly is None: continue
			x,y=[],[]
			for point in list(poly.exterior.coords):
				x.append(point[0])
				y.append(point[1])
			fill(x,y, alpha=0.6)
		show()
	return result
Example #28
0
def run_demo(args):
    """
    @brief a Gaussian Process regression example using an input covariance 
    model. The demo divides the observations along the x-axis and computes in 
    parallel using mpi4py
    """

    np.random.seed(1)

    def f(x):
        """
        @brief the function to predict.
        """
        return x * np.sin(x)
  
    # the inpute data points
    X = np.linspace(0.1, 9.9, 500)

    # make the observations with added noise
    y = f(X).ravel()
    dy = 0.5 + 1.0 * np.random.random(y.shape)
    noise = np.random.normal(0, dy)
    y += noise
    
    # mesh the input space for evaluations of the prediction
    x = np.linspace(-2, 12, 2*len(X))

    
    # instanciate a Gaussian Process model, allowing all params to vary
    gp = GaussianProcessMPI(theta0 = [0.5, 2.0, 1.0], 
                         covfunction=args.covariance, verbose=True, 
                         fixed=[False, False, False])

    # fit to data using Maximum Likelihood Estimation of the parameters
    gp.fit(X, y, dy)

    # make the prediction on the meshed x-axis
    y_pred, sigma = gp.predict(x)
    
    if MPI.COMM_WORLD.Get_rank() == 0:
        
        # plot the function, the prediction and the 95% confidence interval based on
        # the standard deviation
        fig = pl.figure()
        
        pl.plot(x, f(x), 'r:', label=r'$f(x) = x \ \mathrm{sin}(x)$')
        pl.errorbar(X.ravel(), y, dy, label='Observations')
        pl.plot(x, y_pred, label='Prediction')
        pl.fill(np.concatenate([x, x[::-1]]),
                np.concatenate([y_pred - 1.9600 * sigma,
                               (y_pred + 1.9600 * sigma)[::-1]]),
                alpha=.2, fc='DarkGoldenRod', ec="None", label='95% confidence interval')
    
        pl.xlabel('$x$', fontsize=16)
        pl.ylabel('$f(x)$', fontsize=16)
        pl.ylim(-15, 20)
        pl.legend(loc='upper left')
    
        pl.show()
def plot_triangle(c, mesh, color=None, alpha_fill=None, alpha_line=None):
    if not plot: return
    cell = Cell(mesh, c)
    xy = cell.get_vertex_coordinates()
    x = [xy[0], xy[2], xy[4]]
    y = [xy[1], xy[3], xy[5]]
    if not color is None: pl.fill(x, y, color=color, alpha=alpha_fill)
    pl.plot(x + [x[0]], y + [y[0]], color='k', alpha=alpha_line)
Example #30
0
File: genome.py Project: PMBio/sqtl
def plot_genes(chrm, start, end, y, h):
    all_genelocs = read_gene_locs()
    genelocs = []
    for (c, s, e) in all_genelocs.values():
        if (chrm == c) and (s > start) and (e < end):
            genelocs.append([s,e])
    for (x1,x2) in genelocs:
        PL.fill([x1,x2,x2,x1], [y+h, y+h, y-h, y-h], lw=0.5, fill=True, color="k", alpha=0.3)
Example #31
0
def fill_polygon(g, o):
	a = asarray(g.exterior)
	pylab.fill(a[:, 0], a[:, 1], o, alpha=0.5)


def fill_multipolygon(g, o):
	for g in g.geoms:
		fill_polygon(g, o)


if __name__ == "__main__":
	from numpy import asarray
	import pylab

	fig = pylab.figure(1, figsize=(4, 3), dpi=150)
	# pylab.axis([-2.0, 2.0, -1.5, 1.5])
	pylab.axis('tight')

	a = asarray(polygon.exterior)
	pylab.fill(a[:, 0], a[:, 1], 'c')

	plot_point(point_r, 'ro', 'b')
	plot_point(point_g, 'go', 'c')
	plot_point(point_b, 'bo', 'd')

	plot_line(line_r, 'r')
	plot_line(line_g, 'g')
	plot_line(line_b, 'b')

	pylab.show()
Example #32
0
def plot(infile,Q,point_names,efermi=0.0,edos=None,ymin=None,\
        ymax=None,dosarray=None,phonon=False,phdos=None,\
        phunit="cm-1",comp=None,outfile="band.pdf",flip=False):
    """
    infile: str, QE output band file
    Q: list of integer, indices of spacial points starting
        from zero (C or Python order)
    point_names: list of str, the corresponding names of Q
    efermi: float, Fermi level for electron band structure
    edos: str, QE electron DOS output file (three columns,
        namely energy, DOS, int DOS. The first two are used)
    ymin,ymax: float, limits of y-axis
    dosarray: 2D numpy array, one could supply DOS as array
        if it is desirable
    phonon: boolean, False for electron plot; otherwise,
        it will be a phonon plot (affect y-axis)
    phdos: str, QE phonon DOS output file (two columns)
    phunit: str, can be "meV" or "mev", "cm-1" or "cm",
        "THz" or "thz".
    comp: str, compare with other models. first column is
        k-path in unit of 2pi/alat and the rest is eigenvalues.
        It assumes csv file is comma delimited.
    outfile: str, output band structure file
    flip: boolean
        DFT in solid line and external in dashed line.
    """
    # some checks
    if len(Q) != len(point_names):
        raise ValueError("Check your special points!")
    if edos != None:
        print "Reading electron DOS from file."
        assert type(edos) is str
        dosarray = np.genfromtxt(edos)[:, 0:2]
    if phdos != None:
        print "Reading phonon DOS from file."
        assert type(phdos) is str
        dosarray = np.genfromtxt(phdos)
    if dosarray != None:
        print "Plotting dispersions along with DOS."
    if comp != None:
        print "Plot will overlap with " + comp
        import os.path
        extension = os.path.splitext(comp)[1]
        if extension.lower() != ".csv":
            dt = np.genfromtxt(comp)
        else:
            dt = np.genfromtxt(comp, delimiter=",")
        q1 = dt[:, 0]
        b1 = dt[:, 1:]
        del os
    if not flip:
        dftLine = 'k-'
        extLine = 'k--'
    else:
        dftLine = 'k--'
        extLine = 'k-'

    b0 = ReadBand(filename=infile)
    b0.band = np.sort(b0.band)
    # construct the reciprocal path
    sp = b0.kvec[Q]  # spacial points
    q = np.zeros(b0.nks)
    start = 0.0
    for i in range(len(Q) - 1):
        nks = Q[i + 1] - Q[i] + 1
        length = np.linalg.norm(sp[i + 1] - sp[i])
        q[Q[i]:Q[i + 1] + 1] = np.linspace(start,
                                           start + length,
                                           nks,
                                           endpoint=True)
        start += length

    plt.figure(0, (10, 6))
    if dosarray != None: plt.axes([.11, .07, .64, .85])
    plt.xlabel("Reduced wave number", fontsize=18)
    # some conversions
    if phonon == False:
        print "The electronic band structure will be plotted."
        print "All energy will be normalised to E_F = %8.3f eV." % efermi
        b0.band -= efermi
        if dosarray != None: dosarray[:, 0] -= efermi
        if ymax == None:
            ymax = np.ceil(b0.band.max() / 5.0) * 5
        if ymin == None:
            ymin = np.floor(b0.band.min() / 5.0) * 5
        plt.plot(q, [0.0] * len(q), 'r--', lw=1)  # Fermi level
        plt.ylabel("Electron Energy ($\mathrm{eV}$)", fontsize=18)
    else:
        print "The phonon dispersions will be plotted."
        if phunit.lower() == "mev":
            b0.band /= 8.0532
            if dosarray != None: dosarray[:, 0] /= 8.0532
            plt.ylabel("Phonon energy (meV)", fontsize=18)
            if ymax == None:
                ymax = np.ceil(b0.band.max() / 10.0) * 10
            if ymin == None:
                ymin = np.floor(b0.band.min() / 10.0) * 10
        if phunit.lower() == "thz":
            b0.band /= 33.33333
            if dosarray != None: dosarray[:, 0] /= 33.33333
            plt.ylabel("Phonon frequency (THz)", fontsize=18)
            if ymax == None:
                ymax = np.ceil(b0.band.max() / 5.0) * 5
            if ymin == None:
                ymin = np.floor(b0.band.min() / 5.0) * 5
        if phunit == "cm-1" or phunit == "cm":
            plt.ylabel("Phonon frequency ($\mathrm{cm^{-1}}$)", fontsize=18)
            if ymax == None:
                ymax = np.ceil(b0.band.max() / 100.) * 100
            if ymin == None:
                ymin = np.floor(b0.band.min() / 100.) * 100
    # plot the figure and some tweeks
    for n in range(b0.nbnd):
        plt.plot(q, b0.band[:, n], dftLine, lw=1)
    if comp != None:
        for n in range(len(b1[0, :])):
            plt.plot(q1, b1[:, n], extLine, lw=1)
    plt.xticks(q[Q], point_names)
    plt.tick_params(axis='x', labeltop='on', labelsize=15, labelbottom='off')
    plt.yticks(fontsize=15)
    plt.xlim(q[0], q[-1])
    plt.ylim(ymin, ymax)
    plt.grid('on')
    # plot DOS if enabled
    if dosarray != None:
        # crop the dosarray
        mask = (dosarray[:, 1] >= ymin) * (dosarray[:, 1] <= ymax)
        dosarray = dosarray[mask]
        # such that it fills solid color
        dosarray[0, 1] = 0.0
        dosarray[-1, 1] = 0.0
        plt.axes([.78, .07, 0.17, .85])
        plt.plot(dosarray[:, 1], dosarray[:, 0], 'k-', lw=1)
        plt.fill(dosarray[:, 1], dosarray[:, 0], color='lightgrey')
        plt.ylim(ymin, ymax)
        plt.xticks([], [])
        plt.yticks([], [])
        plt.xlabel("DOS", fontsize=18)

    plt.savefig(outfile, dpi=300)
Example #33
0
def multi_colour_swatches_plot(colour_swatches,
                               width=1,
                               height=1,
                               spacing=0,
                               columns=3,
                               text_display=True,
                               text_size='large',
                               text_offset=0.075,
                               background_colour=(1.0, 1.0, 1.0),
                               **kwargs):
    """
    Plots given colours swatches.

    Parameters
    ----------
    colour_swatches : list
        ColourSwatch sequence.
    width : numeric, optional
        Colour swatch width.
    height : numeric, optional
        Colour swatch height.
    spacing : numeric, optional
        Colour swatches spacing.
    columns : int, optional
        Colour swatches columns count.
    text_display : bool, optional
        Display colour text.
    text_size : numeric, optional
        Colour text size.
    text_offset : numeric, optional
        Colour text offset.
    background_colour : array_like or unicode, optional
        Background colour.

    Other Parameters
    ----------------
    \**kwargs : dict, optional
        {:func:`colour.plotting.render`},
        Please refer to the documentation of the previously listed definition.

    Returns
    -------
    Figure
        Current figure or None.

    Examples
    --------
    >>> cp1 = ColourSwatch(RGB=(0.45293517, 0.31732158, 0.26414773))
    >>> cp2 = ColourSwatch(RGB=(0.77875824, 0.57726450, 0.50453169))
    >>> multi_colour_swatches_plot([cp1, cp2])  # doctest: +SKIP
    """

    canvas(**kwargs)

    offset_X = offset_Y = 0
    x_min, x_max, y_min, y_max = 0, width, 0, height
    for i, colour_swatch in enumerate(colour_swatches):
        if i % columns == 0 and i != 0:
            offset_X = 0
            offset_Y -= height + spacing

        x_0, x_1 = offset_X, offset_X + width
        y_0, y_1 = offset_Y, offset_Y + height

        pylab.fill(
            (x_0, x_1, x_1, x_0), (y_0, y_0, y_1, y_1),
            color=colour_swatches[i].RGB)
        if colour_swatch.name is not None and text_display:
            pylab.text(
                x_0 + text_offset,
                y_0 + text_offset,
                colour_swatch.name,
                clip_on=True,
                size=text_size)

        offset_X += width + spacing

    x_max = min(len(colour_swatches), columns)
    x_max = x_max * width + x_max * spacing - spacing
    y_min = offset_Y

    matplotlib.pyplot.gca().patch.set_facecolor(background_colour)

    settings = {
        'x_tighten': True,
        'y_tighten': True,
        'x_ticker': False,
        'y_ticker': False,
        'limits': (x_min, x_max, y_min, y_max),
        'aspect': 'equal'
    }
    settings.update(kwargs)

    return render(**settings)
Example #34
0
def main():
    """
    위 0, 1, 2차 함수의 적분
    :return:
    """
    # rect0 함수의 도움말을 표시
    # 도움말은 def rect0() 바로 아래의 문자열
    help(rect0)
    # 적분 구간 시작점
    x_begin = 0.0
    # 적분 구간 끝 점
    x_end = 1.0
    # 적분 구간을 몇개의 구획으로 나눌 것인가
    n_interval = 8

    # 이론적 엄밀해
    exact = (g(x_end) - g(x_begin))
    print "exact solution =", exact

    # 함수 rect0 를 호출하여 수치 적분을 계산
    integration_0 = rect0(f, x_begin, x_end, n_interval)
    print "integration_0 =", integration_0, "err =", integration_0 - exact

    # 함수 trapezoid1 를 호출하여 수치 적분을 계산
    integration_1 = trapezoid1(f, x_begin, x_end, n_interval)
    print "integration_1 =", integration_1, "err =", integration_1 - exact

    # 함수 simpson2 를 호출하여 수치 적분을 계산
    integration_2 = simpson2(f, x_begin, x_end, n_interval)
    print "integration_2 =", integration_2, "err =", integration_2 - exact

    # 적분 결과를 그림으로 표시하기 위하여 pylab 모듈로 부터 특정 기능을 불러 들임
    from pylab import fill, bar, show, xlim, ylim, grid
    # 엄밀해 그림 시작
    n_plot = 100
    delta_x_plot = (float(x_end) - x_begin) / n_plot
    x = [x_begin + k * delta_x_plot for k in xrange(n_plot)]
    y = [f(x[k]) for k in xrange(n_plot)]
    x += [x_end, x_end, x_begin]
    y += [f(x_end), 0.0, 0.0]

    fill(x, y)
    # 엄밀해 그림 끝

    # rect0()
    # 0차 적분 그림 시작
    n_plot = n_interval
    delta_x_plot = (float(x_end) - x_begin) / n_plot
    x = [x_begin + k * delta_x_plot for k in xrange(n_plot)]
    y = [f(xk + 0.5 * delta_x_plot) for xk in x]
    x += [x_end]
    y += [0]

    bar(x, y, width=delta_x_plot, color='g', alpha=0.3)
    # 0차 적분 그림 끝

    # trapezoid1()
    # 1차 적분 그림 시작
    n_plot = n_interval
    delta_x_plot = (float(x_end) - float(x_begin)) / n_plot
    x = [x_begin + k * delta_x_plot for k in xrange(n_plot)]
    y = [f(xk) for xk in x]
    x += [x_end, x_end, x_begin]
    y += [f(x_end), 0.0, 0.0]

    fill(x, y, color='r', alpha=0.2)
    # 1차 적분 그림 끝

    xlim((x_begin, x_end))
    ylim((0.0, ylim()[1]))

    grid()
    show()
Example #35
0
def plotlc(cmdLine):

    global aid, bid, cid, did, eid, fid, mask

# load button

    pylab.ion()
    pylab.clf()
    pylab.axes([0.06,0.02,0.22,0.1])
    pylab.text(0.5,0.5,'LOAD',fontsize=24,weight='heavy',
               horizontalalignment='center',verticalalignment='center')
    pylab.setp(pylab.gca(),xticklabels=[],xticks=[],yticklabels=[],yticks=[])
    pylab.fill([0.0,1.0,1.0,0.0,0.0],[0.0,0.0,1.0,1.0,0.0],'#ffffee')
    xlim(0.0,1.0)
    ylim(0.0,1.0)
    aid = connect('button_press_event',clicker1)

# save button

    pylab.axes([0.2933,0.02,0.22,0.1])
    pylab.text(0.5,0.5,'SAVE',fontsize=24,weight='heavy',
               horizontalalignment='center',verticalalignment='center')
    pylab.setp(pylab.gca(),xticklabels=[],xticks=[],yticklabels=[],yticks=[])
    pylab.fill([0.0,1.0,1.0,0.0,0.0],[0.0,0.0,1.0,1.0,0.0],'#ffffee')
    xlim(0.0,1.0)
    ylim(0.0,1.0)
    bid = connect('button_press_event',clicker2)

# clear button

    pylab.axes([0.5266,0.02,0.22,0.1])
    pylab.text(0.5,0.5,'CLEAR',fontsize=24,weight='heavy',
               horizontalalignment='center',verticalalignment='center')
    pylab.setp(pylab.gca(),xticklabels=[],xticks=[],yticklabels=[],yticks=[])
    pylab.fill([0.0,1.0,1.0,0.0,0.0],[0.0,0.0,1.0,1.0,0.0],'#ffffee')
    xlim(0.0,1.0)
    ylim(0.0,1.0)
    cid = connect('button_press_event',clicker3)

# print button

    pylab.axes([0.76,0.02,0.22,0.1])
    pylab.text(0.5,0.5,'PRINT',fontsize=24,weight='heavy',
               horizontalalignment='center',verticalalignment='center')
    pylab.setp(pylab.gca(),xticklabels=[],xticks=[],yticklabels=[],yticks=[])
    pylab.fill([0.0,1.0,1.0,0.0,0.0],[0.0,0.0,1.0,1.0,0.0],'#ffffee')
    xlim(0.0,1.0)
    ylim(0.0,1.0)
    did = connect('button_press_event',clicker4)

# light curve

    pylab.axes([0.06,0.213,0.92,0.77])
    pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
    pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
    ltime = []; ldata = []
    work1 = instr[1].data.field(0) + bjdref
    work2 = instr[1].data.field(col) / cade
    for i in range(len(work1)):
        if numpy.isfinite(work1[i]) or numpy.isfinite(work2[i]):
            ltime.append(work1[i])
            ldata.append(work2[i])
        else:
            ltime = array(ltime, dtype=float64) - barytime0
            ldata = array(ldata, dtype=float64) / 10**nrm
            plot(ltime,ldata,color=lcolor,linestyle='-',linewidth=lwidth)
            ltime = []; ldata = []
    ltime = array(ltime, dtype=float64) - barytime0
    ldata = array(ldata, dtype=float64) / 10**nrm
    plot(ltime,ldata,color=lcolor,linestyle='-',linewidth=lwidth)
    fill(barytime,flux,fc=fcolor,linewidth=0.0,alpha=falpha)
    xlabel(xlab, {'color' : 'k'})
    ylabel(ylab, {'color' : 'k'})
    grid()

# plot masks

    for i in range(len(mask)):
        t = float(mask[i])
        plot([t,t],[ymin,ymax],color='g',linestyle='-',linewidth=0.5)
    nt = 0
    for i in range(int(len(mask)/2)):
        t1 = float(mask[nt])
        t2 = float(mask[nt+1])
        nt += 2
        fill([t1,t1,t2,t2,t1],[ymin,ymax,ymax,ymin,ymin],
             fc='g',linewidth=0.0,alpha=0.5)
       
      
# plot ranges

    xlim(xmin-xr*0.01,xmax+xr*0.01)
    if ymin-yr*0.01 <= 0.0:
        ylim(1.0e-10,ymax+yr*0.01)
    else:
        ylim(ymin-yr*0.01,ymax+yr*0.01)
 
# ranges

    eid = connect('key_press_event',clicker6)

# render plot

    if cmdLine: 
        pylab.show()
    else: 
        pylab.ion()
        pylab.plot([])
        pylab.ioff()
Example #36
0
def h1line(self,
           log=False,
           cumulative=False,
           differential=False,
           cumdir=1,
           filled=False,
           orientation='horizontal',
           **kwargs):
    """ plot the histogram's  bincontent with a line using pylab.plot. 
        Parameters:
          log    : if true create logartihmic plot
          cumulative : plot the cumulative histogram
          filled : if true fill the region below the line 

          (all other kwargs will be passed to pylab.plot or pylab.fill)
          Note: pylab.plot and pylab.fill take quite different kwargs.
    """

    bincontent, binerror = _h1_transform_bins(self, differential, cumulative,
                                              cumdir)

    nonzerobc = bincontent[bincontent > 0]
    if len(nonzerobc) == 0:
        return

    nbins = self.nbins[0]

    xpoints = n.zeros(2 * (nbins + 1), dtype=float)
    ypoints = n.zeros(2 * (nbins + 1), dtype=float)

    for i in range(nbins):
        xpoints[1 + 2 * i] = self.binedges[i]
        xpoints[2 + 2 * i] = self.binedges[i + 1]
        ypoints[1 + 2 * i] = bincontent[i]
        ypoints[2 + 2 * i] = bincontent[i]

    xpoints[0] = self.binedges[0]
    ypoints[0] = 0
    xpoints[-1] = self.binedges[-1]
    ypoints[-1] = 0
    # TODO eventually add another point to close area?

    ax = p.gca()
    if orientation == 'vertical':
        xpoints, ypoints = ypoints, xpoints
        axis_name = 'x'
    else:
        axis_name = 'y'

    _set_logscale(ax, log, axis=axis_name)

    kw = {"label": kwargs.pop('label', self.title)}
    kw.update(kwargs)

    if filled:
        artists = p.fill(xpoints, ypoints, **kw)
    else:
        artists = p.plot(xpoints, ypoints, **kw)

    _h1label(self)

    return artists
clf.fit(X, y)

# Make the prediction on the meshed x-axis
y_lower = clf.predict(xx)

clf.set_params(loss='ls')
clf.fit(X, y)

# Make the prediction on the meshed x-axis
y_pred = clf.predict(xx)

# Plot the function, the prediction and the 95% confidence interval based on
# the MSE
fig = pl.figure()
pl.plot(xx, f(xx), 'g:', label=u'$f(x) = x\,\sin(x)$')
pl.plot(X, y, 'b.', markersize=10, label=u'Observations')
pl.plot(xx, y_pred, 'r-', label=u'Prediction')
pl.plot(xx, y_upper, 'k-')
pl.plot(xx, y_lower, 'k-')
pl.fill(np.concatenate([xx, xx[::-1]]),
        np.concatenate([y_upper, y_lower[::-1]]),
        alpha=.5,
        fc='b',
        ec='None',
        label='95% prediction interval')
pl.xlabel('$x$')
pl.ylabel('$f(x)$')
pl.ylim(-10, 20)
pl.legend(loc='upper left')
pl.show()
def radioactive_decay():

    # define the number of markers in x and y
    nx = 50
    ny = 50

    # estimate the number of half-lifes needed to decay all markers
    nest = int(math.log(nx * ny) / math.log(2))

    # allocate storage for the number of markers that are decayed at
    # each half-life.  For safety, we allocate space for 2x our estimate
    hist_decay = numpy.zeros(2 * nest)

    # define the length of a marker side
    L = 0.8

    # create a list of marker objects, one at each grid location
    markers = []
    for i in range(nx):
        for j in range(ny):
            markers.append(Marker(i, j))

    # loop over half-lives, and re-evaluate the marker state
    for t in range(2 * nest):

        pylab.clf()

        # the margins are funny -- we pick them to ensure that the
        # plot size is an integer multiple of the number of markers in
        # each dimension
        pylab.subplots_adjust(left=0.0493333,
                              right=0.9506666,
                              bottom=0.0493333,
                              top=0.9506666)

        # draw the current state
        for m in markers:

            if m.state == 1:
                c = "r"
            else:
                c = "w"

            pylab.fill([
                m.xc - L / 2, m.xc - L / 2, m.xc + L / 2, m.xc + L / 2,
                m.xc - L / 2
            ], [
                m.yc - L / 2, m.yc + L / 2, m.yc + L / 2, m.yc - L / 2,
                m.yc - L / 2
            ], c)

        nd = num_decayed(markers)
        hist_decay[t] = nd

        ax = pylab.axis([-1, nx + 1, -1, ny + 1])
        pylab.axis("off")

        pylab.text(-1,
                   -1,
                   "number decayed = %d" % (nd),
                   horizontalalignment="left",
                   verticalalignment="top")

        f = pylab.gcf()
        f.set_size_inches(7.5, 7.5)

        outfile = "radioactive_decay_%04d.png" % t
        pylab.savefig(outfile)

        print(t, nd)

        # if all are decayed, stop making plots
        if nd == nx * ny:
            break

        # now give each marker a chance to "decay"
        for m in markers:
            m.decay()

    # now make a plot of the number that decayed as a function of half-life
    pylab.clf()
    pylab.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9)

    tsmooth = numpy.arange(1000) * t / 1000.
    pred = nx * ny * (1.0 / 2.0)**tsmooth

    pylab.plot(tsmooth, pred, color="b")

    time = numpy.arange(t - 1)
    pylab.scatter(time,
                  nx * ny - hist_decay[0:t - 1],
                  color="b",
                  label="parent")
    pylab.scatter(time, hist_decay[0:t - 1], color="r", label="daughter")

    pylab.axis([0, numpy.max(time) + 1, 0, 1.1 * nx * ny])
    pylab.xlabel("half life")

    leg = pylab.legend(loc=2)
    ltext = leg.get_texts()
    pylab.setp(ltext, fontsize='small')
    leg.draw_frame(0)

    outfile = "radioactive_decay_%04d.png" % (t + 1)
    pylab.savefig(outfile)
Example #39
0
	def makeCorre(self):
	        P.close()
		mode = self.splittage.get()
		annotate = self.annotate.get()
		allosteryResidues = self.fullAllosteryResidues
		allosteryValues = self.fullAllosteryValues
		mutationalityList = self.fullMutationalityList
		
		#### If we only want to output the plotted values, need to sort that out here
		
		if mode == 1:
	#		print allosteryResidues, allosteryValues
			allosteryNegative = []
			allosteryPositive = []
			mutNegative = []
			mutPositive = []
			for element in range(len(allosteryResidues)):
				if allosteryValues[element] <= 0:
					allosteryNegative.append(-allosteryValues[element])
					allosteryPositive.append(0)
					mutNegative.append(mutationalityList[element])
					mutPositive.append(0)
				else:
					allosteryNegative.append(0)
					allosteryPositive.append(allosteryValues[element])
					mutNegative.append(0)
					mutPositive.append(mutationalityList[element])
#			P.ion()
			fig = P.figure(figsize = (18, 10))
			gs = gridspec.GridSpec(1, 2)
			ax1 = P.subplot(gs[0])
			ax2 = P.subplot(gs[1])
	#		print mutationalityList
	#		print mutationalityList
			ax1.plot(allosteryNegative, mutNegative, 'xb')
			ax1.set_ylabel('Mutation Frequency')
			ax1.set_xlabel('$\mathrm{\Delta}$(T$\mathrm{\Delta}$S) [Negative Values]')
			ax1.set_ylim(-0.001, 0.75)
			ax1.set_xlim(0, 0.35)

			if annotate == 1:
         			for i in range(len(allosteryNegative)):
         			    if mutNegative != 0:
                 			    P.annotate(i, xy=(allosteryNegative[i], mutNegative[i]), xytext=(allosteryNegative[i], mutNegative[i]))
			ax2.plot(allosteryPositive, mutPositive, 'xr')
			ax2.set_ylabel('Mutation Frequency')
			ax2.set_xlabel('$\mathrm{\Delta}$(T$\mathrm{\Delta}$S) [Positive Values]')
			if annotate == 1:
         			for i in range(len(allosteryPositive)):
         			    if mutPositive != 0:
                 			    P.annotate(i, xy=(allosteryPositive[i], mutPositive[i]), xytext=(allosteryPositive[i], mutPositive[i]))
			ax2.set_ylim(-0.001, 0.75)
			P.show()

		else:
	#		print allosteryResidues, allosteryValues
			for element in range(len(allosteryValues)):
				if allosteryValues[element] <= 0:
					allosteryValues[element] *= -1

			averageAllostery = np.average(allosteryValues)
			averageMutation = np.average(mutationalityList)
		
#			P.ion()
			fig = P.figure(figsize = (18, 10))
#                        print "\n\n", len(allosteryValues), len(mutationalityList), "\n\n"
			P.plot(allosteryValues, mutationalityList, 'xb')
			P.fill([0, averageAllostery, averageAllostery, 0], [0, 0, averageMutation, averageMutation], 'r', alpha=0.5) 
			P.ylabel('Mutation Frequency')
			P.xlabel('$\mathrm{\Delta}$(T$\mathrm{\Delta}$S)')
			if annotate == 1:
         			for i in range(len(allosteryValues)):
         			    P.annotate(i, xy=(allosteryValues[i], mutationalityList[i]), xytext=(allosteryValues[i], mutationalityList[i]))
         		if self.corrYminVal > self.corrYmaxVal:
         		         print "Lower bound for Y axis set higher than upper bound, ignoring upper bound"
         		         self.corrYmaxVal = 100
         		if self.corrXminVal > self.corrXmaxVal:
         		         print "Lower bound for X axis set higher than upper bound, ignoring upper bound"
         		         self.corrXmaxVal = 100			
			P.ylim(0.01*self.corrYminVal*np.max(mutationalityList), 0.01*self.corrYmaxVal*np.max(mutationalityList))
			P.xlim(0.01*self.corrXminVal*np.max(allosteryValues), 0.01*self.corrXmaxVal*np.max(allosteryValues))
			P.show()
#			P.draw()
#			P.ioff()
			P.savefig('./CorrelationPlot.png')
			
			aboveKaboveM = 0
			aboveKbelowM = 0
			belowKaboveM = 0
			belowKbelowM = 0
			for i in range(len(allosteryValues)):
				if allosteryValues[i] >= averageAllostery:
					if mutationalityList[i] >= averageMutation:
						aboveKaboveM += 1
					else:
						aboveKbelowM += 1
				else:
					if mutationalityList[i] >= averageMutation:
						belowKaboveM += 1
					else:
						belowKbelowM += 1
			print "Given that the allostery is below the average:"
			print "There are", belowKaboveM, "residues above the average mutation factor, and", belowKbelowM, "below it."
			print "Given that the allostery is above the average:"
			print "There are", aboveKaboveM, "residues above the average mutation factor, and", aboveKbelowM, "below it."
			
			self.makeCSVs()
Example #40
0
        from matplotlib.delaunay.triangulate import Triangulation
        from matplotlib.patches import Polygon
        # Lets figure out convex halls for each chunk/label pair
        for target in utargets:
            t_mask = targets == target
            for chunk in uchunks:
                tc_mask = np.logical_and(t_mask, chunk == chunks)
                tc_samples = dataset.samples[tc_mask]
                tr = Triangulation(tc_samples[:, 0], tc_samples[:, 1])
                poly = pl.fill(
                    tc_samples[tr.hull, 0],
                    tc_samples[tr.hull, 1],
                    closed=True,
                    facecolor=targets_colors[target],
                    #fill=False,
                    alpha=0.01,
                    edgecolor='gray',
                    linestyle='dotted',
                    linewidth=0.5,
                )

    pl.legend(scatterpoints=1)
    if clf and not estimates_were_enabled:
        clf.ca.disable('estimates')
    Pion()
    pl.axis('tight')
    #pl.show()


##REF: Name was automagically refactored
Example #41
0
def HR_radius():

    # solar temperature
    T_sun = 5777.

    # temperature plotting range
    Tmin = 2000
    Tmax = 60000

    # luminosity plotting range
    Lmin = 1.e-4
    Lmax = 1.e6

    # draw radius lines? (1 = yes, 0 = no)
    draw_radii = 1

    # draw the WD region?
    draw_WDs = 1

    # label the stars by mass?
    label_masses = 1

    #-------------------------------------------------------------------------
    # main sequence data taken from Carroll & Ostlie, Appendix G
    nstars = 11
    M = numpy.zeros(nstars, numpy.float64)
    T = numpy.zeros(nstars, numpy.float64)
    R = numpy.zeros(nstars, numpy.float64)
    L = numpy.zeros(nstars, numpy.float64)

    # spectral type
    spectralTypes = [
        'O8', 'B0', 'B3', 'B5', 'A0', 'A5', 'F5', 'Sun', 'K5', 'M0', 'M5'
    ]

    # mass (solar masses)
    M[:] = [23, 17.5, 7.6, 5.9, 2.9, 1.8, 1.2, 1, 0.67, 0.51, 0.21]

    # temperature (K)
    T[:] = [
        35800, 32500, 18800, 15200, 9800, 8190, 6650, T_sun, 4410, 3840, 3170
    ]

    # radius (solar radii)
    R[:] = [10.0, 6.7, 3.8, 3.2, 2.2, 1.8, 1.2, 1.0, 0.80, 0.63, 0.29]

    # luminosity (solar luminosities)
    L[:] = [
        147000, 32500, 1580, 480, 39.4, 12.3, 2.56, 1.0, 0.216, 0.077, 0.0076
    ]

    #-------------------------------------------------------------------------

    ax = pylab.subplot(111)
    ax.set_xscale('log')
    ax.set_yscale('log')

    # draw and label the main sequence
    pylab.scatter(T, L, s=100, marker="+", color="r", lw=2)
    pylab.plot(T, L, 'b-')
    n = 0
    while (n < len(spectralTypes)):

        if (label_masses):
            if (M[n] >= 1.0):
                pylab.text(1.05 * T[n],
                           L[n],
                           "%4.1f $M_\odot$" % (M[n]),
                           fontsize=10,
                           horizontalalignment="right",
                           verticalalignment="center",
                           color="r")
            else:
                pylab.text(1.05 * T[n],
                           L[n],
                           "%3.2f $M_\odot$" % (M[n]),
                           fontsize=10,
                           horizontalalignment="right",
                           verticalalignment="center",
                           color="r")

        pylab.text(0.9 * T[n], L[n], spectralTypes[n])

        n += 1

    if (draw_radii):

        # draw in lines of constant radius
        Rvals = [0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000, 10000]

        nTpts = 25
        dlogT = (math.log10(Tmax) - math.log10(Tmin)) / (nTpts - 1)

        Tplot = 10.0**(numpy.arange(nTpts) * dlogT + math.log10(Tmin))

        n = 0
        while (n < len(Rvals)):

            # L/L_sun = (R/R_sun)**2 (T/T_sun)**4
            # compute L in L_sun units
            L = Rvals[n]**2 * (Tplot / T_sun)**4

            pylab.plot(Tplot, L, linestyle='--', color="0.5")

            # draw in labels -- here we space the T position of the labels equally
            # in log, by empericallly picking T = 40000 for L = 1.e-4 and
            # T = 3000 for L = 1.e4, and doing a line in log-space
            slope = (math.log10(40000) -
                     math.log10(3000)) / (math.log10(1.e-4) - math.log10(1.e4))
            xpos = math.log10(40000) + slope * (math.log10(Rvals[n]) -
                                                math.log10(1.e-4))
            xpos = 10.0**xpos

            ypos = Rvals[n]**2 * (xpos / T_sun)**4

            if (xpos > Tmin and xpos < Tmax and ypos > Lmin and ypos < Lmax):
                pylab.text(xpos,
                           ypos,
                           "%g $R_\odot$" % (Rvals[n]),
                           color="0.5")

            n += 1

    if (draw_WDs):

        # draw a box along the R = 0.01 R_sun line to indicate the approximate
        # position of the white dwarfs
        L3 = 0.01**2 * (30000. / T_sun)**4
        L75 = 0.01**2 * (7500. / T_sun)**4
        pylab.fill([30000, 30000, 7500, 7500],
                   [1.5 * L3, 0.66 * L3, 0.66 * L75, 1.5 * L75],
                   alpha=0.20,
                   facecolor="b")

        L15 = 0.01**2 * (15000. / T_sun)**4
        pylab.text(15000,
                   L15,
                   "white dwarfs",
                   color="b",
                   horizontalalignment="center")

    # draw x-axis (temperature) labels in a few spots
    Tplot = [40000, 20000, 10000, 5000, 2500]
    Tlabels = []
    n = 0
    while (n < len(Tplot)):
        Tlabels.append("%5.0f" % (Tplot[n]))
        n += 1

    locs, labels = pylab.xticks(Tplot, Tlabels)

    # reverse the x-axis
    pylab.axis([Tmin, Tmax, Lmin, Lmax])
    ax = pylab.gca()
    ax.set_xlim(ax.get_xlim()[::-1])

    # turn off minor ticks
    minorLocator = pylab.NullLocator()
    ax.xaxis.set_minor_locator(minorLocator)

    pylab.xlabel("$T$ (K)")
    pylab.ylabel(r"$L/L_\odot$")

    pylab.subplots_adjust(left=0.125, right=0.95, bottom=0.1, top=0.95)

    f = pylab.gcf()
    f.set_size_inches(6.0, 7.0)

    pylab.savefig("HR_radius.png")
Example #42
0
def keppixseries(infile,
                 outfile,
                 plotfile,
                 plottype,
                 filter,
                 function,
                 cutoff,
                 clobber,
                 verbose,
                 logfile,
                 status,
                 cmdLine=False):

    # input arguments

    status = 0
    seterr(all="ignore")

    # log the call

    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile, hashline, verbose)
    call = 'KEPPIXSERIES -- '
    call += 'infile=' + infile + ' '
    call += 'outfile=' + outfile + ' '
    call += 'plotfile=' + plotfile + ' '
    call += 'plottype=' + plottype + ' '
    filt = 'n'
    if (filter): filt = 'y'
    call += 'filter=' + filt + ' '
    call += 'function=' + function + ' '
    call += 'cutoff=' + str(cutoff) + ' '
    overwrite = 'n'
    if (clobber): overwrite = 'y'
    call += 'clobber=' + overwrite + ' '
    chatter = 'n'
    if (verbose): chatter = 'y'
    call += 'verbose=' + chatter + ' '
    call += 'logfile=' + logfile
    kepmsg.log(logfile, call + '\n', verbose)

    # start time

    kepmsg.clock('KEPPIXSERIES started at', logfile, verbose)

    # test log file

    logfile = kepmsg.test(logfile)

    # clobber output file

    if clobber: status = kepio.clobber(outfile, logfile, verbose)
    if kepio.fileexists(outfile):
        message = 'ERROR -- KEPPIXSERIES: ' + outfile + ' exists. Use --clobber'
        status = kepmsg.err(logfile, message, verbose)

# open TPF FITS file

    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, barytime, status = \
            kepio.readTPF(infile,'TIME',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, tcorr, status = \
            kepio.readTPF(infile,'TIMECORR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, cadno, status = \
            kepio.readTPF(infile,'CADENCENO',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, fluxpixels, status = \
            kepio.readTPF(infile,'FLUX',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, errpixels, status = \
            kepio.readTPF(infile,'FLUX_ERR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, qual, status = \
            kepio.readTPF(infile,'QUALITY',logfile,verbose)

# read mask defintion data from TPF file

    if status == 0:
        maskimg, pixcoord1, pixcoord2, status = kepio.readMaskDefinition(
            infile, logfile, verbose)

# print target data

    if status == 0:
        print('')
        print('      KepID:  %s' % kepid)
        print(' RA (J2000):  %s' % ra)
        print('Dec (J2000): %s' % dec)
        print('     KepMag:  %s' % kepmag)
        print('   SkyGroup:    %2s' % skygroup)
        print('     Season:    %2s' % str(season))
        print('    Channel:    %2s' % channel)
        print('     Module:    %2s' % module)
        print('     Output:     %1s' % output)
        print('')

# how many quality = 0 rows?

    if status == 0:
        npts = 0
        nrows = len(fluxpixels)
        for i in range(nrows):
            if qual[i] == 0 and \
                    numpy.isfinite(barytime[i]) and \
                    numpy.isfinite(fluxpixels[i,ydim*xdim/2]):
                npts += 1
        time = empty((npts))
        timecorr = empty((npts))
        cadenceno = empty((npts))
        quality = empty((npts))
        pixseries = empty((ydim, xdim, npts))
        errseries = empty((ydim, xdim, npts))

# construct output light curves

    if status == 0:
        np = 0
        for i in range(ydim):
            for j in range(xdim):
                npts = 0
                for k in range(nrows):
                    if qual[k] == 0 and \
                    numpy.isfinite(barytime[k]) and \
                    numpy.isfinite(fluxpixels[k,ydim*xdim/2]):
                        time[npts] = barytime[k]
                        timecorr[npts] = tcorr[k]
                        cadenceno[npts] = cadno[k]
                        quality[npts] = qual[k]
                        pixseries[i, j, npts] = fluxpixels[k, np]
                        errseries[i, j, npts] = errpixels[k, np]
                        npts += 1
                np += 1

# define data sampling

    if status == 0 and filter:
        tpf, status = kepio.openfits(infile, 'readonly', logfile, verbose)
    if status == 0 and filter:
        cadence, status = kepkey.cadence(tpf[1], infile, logfile, verbose)
        tr = 1.0 / (cadence / 86400)
        timescale = 1.0 / (cutoff / tr)

# define convolution function

    if status == 0 and filter:
        if function == 'boxcar':
            filtfunc = numpy.ones(numpy.ceil(timescale))
        elif function == 'gauss':
            timescale /= 2
            dx = numpy.ceil(timescale * 10 + 1)
            filtfunc = kepfunc.gauss()
            filtfunc = filtfunc([1.0, dx / 2 - 1.0, timescale],
                                linspace(0, dx - 1, dx))
        elif function == 'sinc':
            dx = numpy.ceil(timescale * 12 + 1)
            fx = linspace(0, dx - 1, dx)
            fx = fx - dx / 2 + 0.5
            fx /= timescale
            filtfunc = numpy.sinc(fx)
        filtfunc /= numpy.sum(filtfunc)

# pad time series at both ends with noise model

    if status == 0 and filter:
        for i in range(ydim):
            for j in range(xdim):
                ave, sigma = kepstat.stdev(pixseries[i, j, :len(filtfunc)])
                padded = numpy.append(kepstat.randarray(numpy.ones(len(filtfunc)) * ave, \
                                                            numpy.ones(len(filtfunc)) * sigma), pixseries[i,j,:])
                ave, sigma = kepstat.stdev(pixseries[i, j, -len(filtfunc):])
                padded = numpy.append(padded, kepstat.randarray(numpy.ones(len(filtfunc)) * ave, \
                                                                    numpy.ones(len(filtfunc)) * sigma))

                # convolve data

                if status == 0:
                    convolved = convolve(padded, filtfunc, 'same')

# remove padding from the output array

                if status == 0:
                    outdata = convolved[len(filtfunc):-len(filtfunc)]

# subtract low frequencies

                if status == 0:
                    outmedian = median(outdata)
                    pixseries[i,
                              j, :] = pixseries[i, j, :] - outdata + outmedian

# construct output file

    if status == 0 and ydim * xdim < 1000:
        instruct, status = kepio.openfits(infile, 'readonly', logfile, verbose)
        status = kepkey.history(call, instruct[0], outfile, logfile, verbose)
        hdulist = HDUList(instruct[0])
        cols = []
        cols.append(
            Column(name='TIME',
                   format='D',
                   unit='BJD - 2454833',
                   disp='D12.7',
                   array=time))
        cols.append(
            Column(name='TIMECORR',
                   format='E',
                   unit='d',
                   disp='E13.6',
                   array=timecorr))
        cols.append(
            Column(name='CADENCENO', format='J', disp='I10', array=cadenceno))
        cols.append(Column(name='QUALITY', format='J', array=quality))
        for i in range(ydim):
            for j in range(xdim):
                colname = 'COL%d_ROW%d' % (i + column, j + row)
                cols.append(
                    Column(name=colname,
                           format='E',
                           disp='E13.6',
                           array=pixseries[i, j, :]))
        hdu1 = new_table(ColDefs(cols))
        try:
            hdu1.header.update('INHERIT', True, 'inherit the primary header')
        except:
            status = 0
        try:
            hdu1.header.update('EXTNAME', 'PIXELSERIES', 'name of extension')
        except:
            status = 0
        try:
            hdu1.header.update(
                'EXTVER', instruct[1].header['EXTVER'],
                'extension version number (not format version)')
        except:
            status = 0
        try:
            hdu1.header.update('TELESCOP', instruct[1].header['TELESCOP'],
                               'telescope')
        except:
            status = 0
        try:
            hdu1.header.update('INSTRUME', instruct[1].header['INSTRUME'],
                               'detector type')
        except:
            status = 0
        try:
            hdu1.header.update('OBJECT', instruct[1].header['OBJECT'],
                               'string version of KEPLERID')
        except:
            status = 0
        try:
            hdu1.header.update('KEPLERID', instruct[1].header['KEPLERID'],
                               'unique Kepler target identifier')
        except:
            status = 0
        try:
            hdu1.header.update('RADESYS', instruct[1].header['RADESYS'],
                               'reference frame of celestial coordinates')
        except:
            status = 0
        try:
            hdu1.header.update('RA_OBJ', instruct[1].header['RA_OBJ'],
                               '[deg] right ascension from KIC')
        except:
            status = 0
        try:
            hdu1.header.update('DEC_OBJ', instruct[1].header['DEC_OBJ'],
                               '[deg] declination from KIC')
        except:
            status = 0
        try:
            hdu1.header.update('EQUINOX', instruct[1].header['EQUINOX'],
                               'equinox of celestial coordinate system')
        except:
            status = 0
        try:
            hdu1.header.update('TIMEREF', instruct[1].header['TIMEREF'],
                               'barycentric correction applied to times')
        except:
            status = 0
        try:
            hdu1.header.update('TASSIGN', instruct[1].header['TASSIGN'],
                               'where time is assigned')
        except:
            status = 0
        try:
            hdu1.header.update('TIMESYS', instruct[1].header['TIMESYS'],
                               'time system is barycentric JD')
        except:
            status = 0
        try:
            hdu1.header.update('BJDREFI', instruct[1].header['BJDREFI'],
                               'integer part of BJD reference date')
        except:
            status = 0
        try:
            hdu1.header.update('BJDREFF', instruct[1].header['BJDREFF'],
                               'fraction of the day in BJD reference date')
        except:
            status = 0
        try:
            hdu1.header.update('TIMEUNIT', instruct[1].header['TIMEUNIT'],
                               'time unit for TIME, TSTART and TSTOP')
        except:
            status = 0
        try:
            hdu1.header.update('TSTART', instruct[1].header['TSTART'],
                               'observation start time in BJD-BJDREF')
        except:
            status = 0
        try:
            hdu1.header.update('TSTOP', instruct[1].header['TSTOP'],
                               'observation stop time in BJD-BJDREF')
        except:
            status = 0
        try:
            hdu1.header.update('LC_START', instruct[1].header['LC_START'],
                               'mid point of first cadence in MJD')
        except:
            status = 0
        try:
            hdu1.header.update('LC_END', instruct[1].header['LC_END'],
                               'mid point of last cadence in MJD')
        except:
            status = 0
        try:
            hdu1.header.update('TELAPSE', instruct[1].header['TELAPSE'],
                               '[d] TSTOP - TSTART')
        except:
            status = 0
        try:
            hdu1.header.update('LIVETIME', instruct[1].header['LIVETIME'],
                               '[d] TELAPSE multiplied by DEADC')
        except:
            status = 0
        try:
            hdu1.header.update('EXPOSURE', instruct[1].header['EXPOSURE'],
                               '[d] time on source')
        except:
            status = 0
        try:
            hdu1.header.update('DEADC', instruct[1].header['DEADC'],
                               'deadtime correction')
        except:
            status = 0
        try:
            hdu1.header.update('TIMEPIXR', instruct[1].header['TIMEPIXR'],
                               'bin time beginning=0 middle=0.5 end=1')
        except:
            status = 0
        try:
            hdu1.header.update('TIERRELA', instruct[1].header['TIERRELA'],
                               '[d] relative time error')
        except:
            status = 0
        try:
            hdu1.header.update('TIERABSO', instruct[1].header['TIERABSO'],
                               '[d] absolute time error')
        except:
            status = 0
        try:
            hdu1.header.update('INT_TIME', instruct[1].header['INT_TIME'],
                               '[s] photon accumulation time per frame')
        except:
            status = 0
        try:
            hdu1.header.update('READTIME', instruct[1].header['READTIME'],
                               '[s] readout time per frame')
        except:
            status = 0
        try:
            hdu1.header.update('FRAMETIM', instruct[1].header['FRAMETIM'],
                               '[s] frame time (INT_TIME + READTIME)')
        except:
            status = 0
        try:
            hdu1.header.update('NUM_FRM', instruct[1].header['NUM_FRM'],
                               'number of frames per time stamp')
        except:
            status = 0
        try:
            hdu1.header.update('TIMEDEL', instruct[1].header['TIMEDEL'],
                               '[d] time resolution of data')
        except:
            status = 0
        try:
            hdu1.header.update('DATE-OBS', instruct[1].header['DATE-OBS'],
                               'TSTART as UTC calendar date')
        except:
            status = 0
        try:
            hdu1.header.update('DATE-END', instruct[1].header['DATE-END'],
                               'TSTOP as UTC calendar date')
        except:
            status = 0
        try:
            hdu1.header.update('BACKAPP', instruct[1].header['BACKAPP'],
                               'background is subtracted')
        except:
            status = 0
        try:
            hdu1.header.update('DEADAPP', instruct[1].header['DEADAPP'],
                               'deadtime applied')
        except:
            status = 0
        try:
            hdu1.header.update('VIGNAPP', instruct[1].header['VIGNAPP'],
                               'vignetting or collimator correction applied')
        except:
            status = 0
        try:
            hdu1.header.update('GAIN', instruct[1].header['GAIN'],
                               '[electrons/count] channel gain')
        except:
            status = 0
        try:
            hdu1.header.update('READNOIS', instruct[1].header['READNOIS'],
                               '[electrons] read noise')
        except:
            status = 0
        try:
            hdu1.header.update('NREADOUT', instruct[1].header['NREADOUT'],
                               'number of read per cadence')
        except:
            status = 0
        try:
            hdu1.header.update('TIMSLICE', instruct[1].header['TIMSLICE'],
                               'time-slice readout sequence section')
        except:
            status = 0
        try:
            hdu1.header.update('MEANBLCK', instruct[1].header['MEANBLCK'],
                               '[count] FSW mean black level')
        except:
            status = 0
        hdulist.append(hdu1)
        hdulist.writeto(outfile)
        status = kepkey.new('EXTNAME', 'APERTURE', 'name of extension',
                            instruct[2], outfile, logfile, verbose)
        pyfits.append(outfile, instruct[2].data, instruct[2].header)
        status = kepio.closefits(instruct, logfile, verbose)
    else:
        message = 'WARNING -- KEPPIXSERIES: output FITS file requires > 999 columns. Non-compliant with FITS convention.'

        kepmsg.warn(logfile, message)

# plot style

    if status == 0:
        try:
            params = {
                'backend': 'png',
                'axes.linewidth': 2.0,
                'axes.labelsize': 32,
                'axes.font': 'sans-serif',
                'axes.fontweight': 'bold',
                'text.fontsize': 8,
                'legend.fontsize': 8,
                'xtick.labelsize': 12,
                'ytick.labelsize': 12
            }
            pylab.rcParams.update(params)
        except:
            pass

# plot pixel array

    fmin = 1.0e33
    fmax = -1.033
    if status == 0:
        pylab.figure(num=None, figsize=[12, 12])
        pylab.clf()
        dx = 0.93 / xdim
        dy = 0.94 / ydim
        ax = pylab.axes([0.06, 0.05, 0.93, 0.94])
        pylab.gca().xaxis.set_major_formatter(
            pylab.ScalarFormatter(useOffset=False))
        pylab.gca().yaxis.set_major_formatter(
            pylab.ScalarFormatter(useOffset=False))
        pylab.gca().xaxis.set_major_locator(
            matplotlib.ticker.MaxNLocator(integer=True))
        pylab.gca().yaxis.set_major_locator(
            matplotlib.ticker.MaxNLocator(integer=True))
        labels = ax.get_yticklabels()
        setp(labels, 'rotation', 90, fontsize=12)
        pylab.xlim(numpy.min(pixcoord1) - 0.5, numpy.max(pixcoord1) + 0.5)
        pylab.ylim(numpy.min(pixcoord2) - 0.5, numpy.max(pixcoord2) + 0.5)
        pylab.xlabel('time', {'color': 'k'})
        pylab.ylabel('arbitrary flux', {'color': 'k'})
        for i in range(ydim):
            for j in range(xdim):
                tmin = amin(time)
                tmax = amax(time)
                try:
                    numpy.isfinite(amin(pixseries[i, j, :]))
                    numpy.isfinite(amin(pixseries[i, j, :]))
                    fmin = amin(pixseries[i, j, :])
                    fmax = amax(pixseries[i, j, :])
                except:
                    ugh = 1
                xmin = tmin - (tmax - tmin) / 40
                xmax = tmax + (tmax - tmin) / 40
                ymin = fmin - (fmax - fmin) / 20
                ymax = fmax + (fmax - fmin) / 20
                if kepstat.bitInBitmap(maskimg[i, j], 2):
                    pylab.axes([0.06 + float(j) * dx, 0.05 + i * dy, dx, dy],
                               axisbg='lightslategray')
                elif maskimg[i, j] == 0:
                    pylab.axes([0.06 + float(j) * dx, 0.05 + i * dy, dx, dy],
                               axisbg='black')
                else:
                    pylab.axes([0.06 + float(j) * dx, 0.05 + i * dy, dx, dy])
                if j == int(xdim / 2) and i == 0:
                    pylab.setp(pylab.gca(), xticklabels=[], yticklabels=[])
                elif j == 0 and i == int(ydim / 2):
                    pylab.setp(pylab.gca(), xticklabels=[], yticklabels=[])
                else:
                    pylab.setp(pylab.gca(), xticklabels=[], yticklabels=[])
                ptime = time * 1.0
                ptime = numpy.insert(ptime, [0], ptime[0])
                ptime = numpy.append(ptime, ptime[-1])
                pflux = pixseries[i, j, :] * 1.0
                pflux = numpy.insert(pflux, [0], -1000.0)
                pflux = numpy.append(pflux, -1000.0)
                pylab.plot(time,
                           pixseries[i, j, :],
                           color='#0000ff',
                           linestyle='-',
                           linewidth=0.5)
                if not kepstat.bitInBitmap(maskimg[i, j], 2):
                    pylab.fill(ptime,
                               pflux,
                               fc='lightslategray',
                               linewidth=0.0,
                               alpha=1.0)
                pylab.fill(ptime,
                           pflux,
                           fc='#FFF380',
                           linewidth=0.0,
                           alpha=1.0)
                if 'loc' in plottype:
                    pylab.xlim(xmin, xmax)
                    pylab.ylim(ymin, ymax)
                if 'glob' in plottype:
                    pylab.xlim(xmin, xmax)
                    pylab.ylim(1.0e-10, numpy.nanmax(pixseries) * 1.05)
                if 'full' in plottype:
                    pylab.xlim(xmin, xmax)
                    pylab.ylim(1.0e-10, ymax * 1.05)

# render plot

        if cmdLine:
            pylab.show()
        else:
            pylab.ion()
            pylab.plot([])
            pylab.ioff()
        if plotfile.lower() != 'none':
            pylab.savefig(plotfile)

# stop time

    if status == 0:
        kepmsg.clock('KEPPIXSERIES ended at', logfile, verbose)

    return
Example #43
0
def kepprfphot(infile,outroot,columns,rows,fluxes,border,background,focus,prfdir,ranges,
               tolerance,ftolerance,qualflags,plt,clobber,verbose,logfile,status,cmdLine=False): 

# input arguments

    status = 0
    seterr(all="ignore") 

# log the call 

    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile,hashline,verbose)
    call = 'KEPPRFPHOT -- '
    call += 'infile='+infile+' '
    call += 'outroot='+outroot+' '
    call += 'columns='+columns+' '
    call += 'rows='+rows+' '
    call += 'fluxes='+fluxes+' '
    call += 'border='+str(border)+' '
    bground = 'n'
    if (background): bground = 'y'
    call += 'background='+bground+' '
    focs = 'n'
    if (focus): focs = 'y'
    call += 'focus='+focs+' '
    call += 'prfdir='+prfdir+' '
    call += 'ranges='+ranges+' '
    call += 'xtol='+str(tolerance)+' '
    call += 'ftol='+str(ftolerance)+' '
    quality = 'n'
    if (qualflags): quality = 'y'
    call += 'qualflags='+quality+' '
    plotit = 'n'
    if (plt): plotit = 'y'
    call += 'plot='+plotit+' '
    overwrite = 'n'
    if (clobber): overwrite = 'y'
    call += 'clobber='+overwrite+ ' '
    chatter = 'n'
    if (verbose): chatter = 'y'
    call += 'verbose='+chatter+' '
    call += 'logfile='+logfile
    kepmsg.log(logfile,call+'\n',verbose)

# test log file

    logfile = kepmsg.test(logfile)

# start time

    kepmsg.clock('KEPPRFPHOT started at',logfile,verbose)

# number of sources

    if status == 0:
        work = fluxes.strip()
        work = re.sub(' ',',',work)
        work = re.sub(';',',',work)
        nsrc = len(work.split(','))

# construct inital guess vector for fit 

    if status == 0:
        guess = []
        try:
            f = fluxes.strip().split(',')
            x = columns.strip().split(',')
            y = rows.strip().split(',')
            for i in range(len(f)):
                f[i] = float(f[i])
        except:
            f = fluxes
            x = columns
            y = rows
        nsrc = len(f)
        for i in range(nsrc):
            try:
                guess.append(float(f[i]))
            except:
                message = 'ERROR -- KEPPRF: Fluxes must be floating point numbers'
                status = kepmsg.err(logfile,message,verbose)
        if status == 0:
            if len(x) != nsrc or len(y) != nsrc:
                message = 'ERROR -- KEPFIT:FITMULTIPRF: Guesses for rows, columns and '
                message += 'fluxes must have the same number of sources'
                status = kepmsg.err(logfile,message,verbose)
        if status == 0:
            for i in range(nsrc):
                try:
                    guess.append(float(x[i]))
                except:
                    message = 'ERROR -- KEPPRF: Columns must be floating point numbers'
                    status = kepmsg.err(logfile,message,verbose)
        if status == 0:
            for i in range(nsrc):
                try:
                    guess.append(float(y[i]))
                except:
                    message = 'ERROR -- KEPPRF: Rows must be floating point numbers'
                    status = kepmsg.err(logfile,message,verbose)
        if status == 0 and background:
            if border == 0:
                guess.append(0.0)
            else:
                for i in range((border+1)*2):
                    guess.append(0.0)
        if status == 0 and focus:
            guess.append(1.0); guess.append(1.0); guess.append(0.0)

# clobber output file

    for i in range(nsrc):
        outfile = '%s_%d.fits' % (outroot, i)
        if clobber: status = kepio.clobber(outfile,logfile,verbose)
        if kepio.fileexists(outfile): 
            message = 'ERROR -- KEPPRFPHOT: ' + outfile + ' exists. Use --clobber'
            status = kepmsg.err(logfile,message,verbose)

# open TPF FITS file

    if status == 0:
        try:
            kepid, channel, skygroup, module, output, quarter, season, \
                ra, dec, column, row, kepmag, xdim, ydim, barytime, status = \
                kepio.readTPF(infile,'TIME',logfile,verbose)
        except:
            message = 'ERROR -- KEPPRFPHOT: is %s a Target Pixel File? ' % infile
            status = kepmsg.err(logfile,message,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, tcorr, status = \
            kepio.readTPF(infile,'TIMECORR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, cadno, status = \
            kepio.readTPF(infile,'CADENCENO',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, fluxpixels, status = \
            kepio.readTPF(infile,'FLUX',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, errpixels, status = \
            kepio.readTPF(infile,'FLUX_ERR',logfile,verbose)
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, poscorr1, status = \
            kepio.readTPF(infile,'POS_CORR1',logfile,verbose)
        if status != 0:
            poscorr1 = numpy.zeros((len(barytime)),dtype='float32')
            poscorr1[:] = numpy.nan
            status = 0
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, poscorr2, status = \
            kepio.readTPF(infile,'POS_CORR2',logfile,verbose)
        if status != 0:
            poscorr2 = numpy.zeros((len(barytime)),dtype='float32')
            poscorr2[:] = numpy.nan
            status = 0
    if status == 0:
        kepid, channel, skygroup, module, output, quarter, season, \
            ra, dec, column, row, kepmag, xdim, ydim, qual, status = \
            kepio.readTPF(infile,'QUALITY',logfile,verbose)
    if status == 0:
        struct, status = kepio.openfits(infile,'readonly',logfile,verbose)
    if status == 0:
        tstart, tstop, bjdref, cadence, status = kepio.timekeys(struct,infile,logfile,verbose,status)

# input file keywords and mask map

    if status == 0:
        cards0 = struct[0].header.cards
        cards1 = struct[1].header.cards
        cards2 = struct[2].header.cards
        maskmap = copy(struct[2].data)
        npix = numpy.size(numpy.nonzero(maskmap)[0])

# print target data

    if status == 0 and verbose:
        print('')
        print(('      KepID:  %s' % kepid))
        print((' RA (J2000):  %s' % ra))
        print(('Dec (J2000): %s' % dec))
        print(('     KepMag:  %s' % kepmag))
        print(('   SkyGroup:    %2s' % skygroup))
        print(('     Season:    %2s' % str(season)))
        print(('    Channel:    %2s' % channel))
        print(('     Module:    %2s' % module))
        print(('     Output:     %1s' % output))
        print('')

# determine suitable PRF calibration file

    if status == 0:
        if int(module) < 10:
            prefix = 'kplr0'
        else:
            prefix = 'kplr'
        prfglob = prfdir + '/' + prefix + str(module) + '.' + str(output) + '*' + '_prf.fits'
        try:
            prffile = glob.glob(prfglob)[0]
        except:
            message = 'ERROR -- KEPPRFPHOT: No PRF file found in ' + prfdir
            status = kepmsg.err(logfile,message,verbose)

# read PRF images

    if status == 0:
        prfn = [0,0,0,0,0]
        crpix1p = numpy.zeros((5),dtype='float32')
        crpix2p = numpy.zeros((5),dtype='float32')
        crval1p = numpy.zeros((5),dtype='float32')
        crval2p = numpy.zeros((5),dtype='float32')
        cdelt1p = numpy.zeros((5),dtype='float32')
        cdelt2p = numpy.zeros((5),dtype='float32')
        for i in range(5):
            prfn[i], crpix1p[i], crpix2p[i], crval1p[i], crval2p[i], cdelt1p[i], cdelt2p[i], status \
                = kepio.readPRFimage(prffile,i+1,logfile,verbose)    
        PRFx = arange(0.5,shape(prfn[0])[1]+0.5)
        PRFy = arange(0.5,shape(prfn[0])[0]+0.5)
        PRFx = (PRFx - size(PRFx) / 2) * cdelt1p[0]
        PRFy = (PRFy - size(PRFy) / 2) * cdelt2p[0]

# interpolate the calibrated PRF shape to the target position

    if status == 0:
        prf = zeros(shape(prfn[0]),dtype='float32')
        prfWeight = zeros((5),dtype='float32')
        for i in range(5):
            prfWeight[i] = sqrt((column - crval1p[i])**2 + (row - crval2p[i])**2)
            if prfWeight[i] == 0.0:
                prfWeight[i] = 1.0e6
            prf = prf + prfn[i] / prfWeight[i]
        prf = prf / nansum(prf)
        prf = prf / cdelt1p[0] / cdelt2p[0]

# location of the data image centered on the PRF image (in PRF pixel units)

    if status == 0:
        prfDimY = ydim / cdelt1p[0]
        prfDimX = xdim / cdelt2p[0]
        PRFy0 = (shape(prf)[0] - prfDimY) / 2
        PRFx0 = (shape(prf)[1] - prfDimX) / 2

# construct input pixel image

    if status == 0:
        DATx = arange(column,column+xdim)
        DATy = arange(row,row+ydim)

# interpolation function over the PRF

    if status == 0:
        splineInterpolation = scipy.interpolate.RectBivariateSpline(PRFx,PRFy,prf,kx=3,ky=3)

# construct mesh for background model

    if status == 0:
        bx = numpy.arange(1.,float(xdim+1))
        by = numpy.arange(1.,float(ydim+1))
        xx, yy = numpy.meshgrid(numpy.linspace(bx.min(), bx.max(), xdim),
                                numpy.linspace(by.min(), by.max(), ydim))

# Get time ranges for new photometry, flag good data

    if status == 0:
        barytime += bjdref
        tstart,tstop,status = kepio.timeranges(ranges,logfile,verbose)
        incl = numpy.zeros((len(barytime)),dtype='int')
        for rownum in range(len(barytime)):
            for winnum in range(len(tstart)):
                if barytime[rownum] >= tstart[winnum] and \
                        barytime[rownum] <= tstop[winnum] and \
                        (qual[rownum] == 0 or qualflags) and \
                        numpy.isfinite(barytime[rownum]) and \
                        numpy.isfinite(numpy.nansum(fluxpixels[rownum,:])):
                    incl[rownum] = 1
        if not numpy.in1d(1,incl):
            message = 'ERROR -- KEPPRFPHOT: No legal data within the range ' + ranges
            status = kepmsg.err(logfile,message,verbose)

# filter out bad data

    if status == 0:
        n = 0
        nincl = (incl == 1).sum()
        tim = zeros((nincl),'float64')
        tco = zeros((nincl),'float32')
        cad = zeros((nincl),'float32')
        flu = zeros((nincl,len(fluxpixels[0])),'float32')
        fer = zeros((nincl,len(fluxpixels[0])),'float32')
        pc1 = zeros((nincl),'float32')
        pc2 = zeros((nincl),'float32')
        qua = zeros((nincl),'float32')
        for rownum in range(len(barytime)):
            if incl[rownum] == 1:
                tim[n] = barytime[rownum]
                tco[n] = tcorr[rownum]
                cad[n] = cadno[rownum]
                flu[n,:] = fluxpixels[rownum]
                fer[n,:] = errpixels[rownum]
                pc1[n] = poscorr1[rownum]
                pc2[n] = poscorr2[rownum]
                qua[n] = qual[rownum]
                n += 1
        barytime = tim * 1.0
        tcorr = tco * 1.0
        cadno = cad * 1.0
        fluxpixels = flu * 1.0
        errpixels = fer * 1.0
        poscorr1 = pc1 * 1.0
        poscorr2 = pc2 * 1.0
        qual = qua * 1.0

# initialize plot arrays

    if status == 0:
        t = numpy.array([],dtype='float64')
        fl = []; dx = []; dy = []; bg = []; fx = []; fy = []; fa = []; rs = []; ch = []
        for i in range(nsrc):
            fl.append(numpy.array([],dtype='float32'))
            dx.append(numpy.array([],dtype='float32'))
            dy.append(numpy.array([],dtype='float32'))

# Preparing fit data message

    if status == 0:
        progress = numpy.arange(nincl)
        if verbose:
            txt  = 'Preparing...'
            sys.stdout.write(txt)
            sys.stdout.flush()

# single processor version

    if status == 0:# and not cmdLine:
        oldtime = 0.0
        for rownum in range(numpy.min([80,len(barytime)])):
            try:
                if barytime[rownum] - oldtime > 0.5:
                    ftol = 1.0e-10; xtol = 1.0e-10
            except:
                pass
            args = (fluxpixels[rownum,:],errpixels[rownum,:],DATx,DATy,nsrc,border,xx,yy,PRFx,PRFy,splineInterpolation,
                    guess,ftol,xtol,focus,background,rownum,80,float(x[i]),float(y[i]),False)
            guess = PRFfits(args)
            ftol = ftolerance; xtol = tolerance; oldtime = barytime[rownum]

# Fit the time series: multi-processing

    if status == 0 and cmdLine:
        anslist = []
        cad1 = 0; cad2 = 50
        for i in range(int(nincl/50) + 1):
            try:
                fluxp = fluxpixels[cad1:cad2,:]
                errp = errpixels[cad1:cad2,:]
                progress = numpy.arange(cad1,cad2)
            except:
                fluxp = fluxpixels[cad1:nincl,:]
                errp = errpixels[cad1:nincl,:]
                progress = numpy.arange(cad1,nincl)
            try:
                args = zip(fluxp,errp,itertools.repeat(DATx),itertools.repeat(DATy),
                                      itertools.repeat(nsrc),itertools.repeat(border),itertools.repeat(xx),
                                      itertools.repeat(yy),itertools.repeat(PRFx),itertools.repeat(PRFy),
                                      itertools.repeat(splineInterpolation),itertools.repeat(guess),
                                      itertools.repeat(ftolerance),itertools.repeat(tolerance),
                                      itertools.repeat(focus),itertools.repeat(background),progress,
                                      itertools.repeat(numpy.arange(cad1,nincl)[-1]),
                                      itertools.repeat(float(x[0])),
                                      itertools.repeat(float(y[0])),itertools.repeat(True))
                p = multiprocessing.Pool()
                model = [0.0]
                model = p.imap(PRFfits,args,chunksize=1)
                p.close()
                p.join()
                cad1 += 50; cad2 += 50
                ans = array([array(item) for item in zip(*model)])
                try:
                    anslist = numpy.concatenate((anslist,ans.transpose()),axis=0)
                except:
                    anslist = ans.transpose()
                guess = anslist[-1]
                ans = anslist.transpose()
            except:
                pass
            
# single processor version

    if status == 0 and not cmdLine:
        oldtime = 0.0; ans = []
#        for rownum in xrange(1,10):
        for rownum in range(nincl):
            proctime = time.time()
            try:
                if barytime[rownum] - oldtime > 0.5:
                    ftol = 1.0e-10; xtol = 1.0e-10
            except:
                pass
            args = (fluxpixels[rownum,:],errpixels[rownum,:],DATx,DATy,nsrc,border,xx,yy,PRFx,PRFy,splineInterpolation,
                    guess,ftol,xtol,focus,background,rownum,nincl,float(x[0]),float(y[0]),True)
            guess = PRFfits(args)
            ans.append(guess)
            ftol = ftolerance; xtol = tolerance; oldtime = barytime[rownum]
        ans = array(ans).transpose()

# unpack the best fit parameters

    if status == 0:
        flux = []; OBJx = []; OBJy = []
        na = shape(ans)[1]
        for i in range(nsrc):
            flux.append(ans[i,:])
            OBJx.append(ans[nsrc+i,:])
            OBJy.append(ans[nsrc*2+i,:])
        try:
            bterms = border + 1
            if bterms == 1:
                b = ans[nsrc*3,:]
            else:
                b = array([])
                bkg = []
                for i in range(na):
                    bcoeff = array([ans[nsrc*3:nsrc*3+bterms,i],ans[nsrc*3+bterms:nsrc*3+bterms*2,i]])
                    bkg.append(kepfunc.polyval2d(xx,yy,bcoeff))
                    b = numpy.append(b,nanmean(bkg[-1].reshape(bkg[-1].size)))
        except:
            b = zeros((na))
        if focus:
            wx = ans[-3,:]; wy = ans[-2,:]; angle = ans[-1,:]
        else:
            wx = ones((na)); wy = ones((na)); angle = zeros((na))
        
# constuct model PRF in detector coordinates

    if status == 0:
        residual = []; chi2 = []
        for i in range(na):
            f = empty((nsrc))
            x = empty((nsrc))
            y = empty((nsrc))
            for j in range(nsrc):
                f[j] = flux[j][i]
                x[j] = OBJx[j][i]
                y[j] = OBJy[j][i]
            PRFfit = kepfunc.PRF2DET(f,x,y,DATx,DATy,wx[i],wy[i],angle[i],splineInterpolation)
            if background and bterms == 1:
                PRFfit = PRFfit + b[i]
            if background and bterms > 1:
                PRFfit = PRFfit + bkg[i]

# calculate residual of DATA - FIT

            xdim = shape(xx)[1]
            ydim = shape(yy)[0]
            DATimg = numpy.empty((ydim,xdim))
            n = 0
            for k in range(ydim):
                for j in range(xdim):
                    DATimg[k,j] = fluxpixels[i,n]
                    n += 1
            PRFres = DATimg - PRFfit
            residual.append(numpy.nansum(PRFres) / npix)
    
# calculate the sum squared difference between data and model

            chi2.append(abs(numpy.nansum(numpy.square(DATimg - PRFfit) / PRFfit)))

# load the output arrays

    if status == 0:
        otime = barytime - bjdref
        otimecorr = tcorr
        ocadenceno = cadno
        opos_corr1 = poscorr1
        opos_corr2 = poscorr2
        oquality = qual
        opsf_bkg = b
        opsf_focus1 = wx
        opsf_focus2 = wy
        opsf_rotation = angle
        opsf_residual = residual
        opsf_chi2 = chi2
        opsf_flux_err = numpy.empty((na)); opsf_flux_err.fill(numpy.nan)
        opsf_centr1_err = numpy.empty((na)); opsf_centr1_err.fill(numpy.nan)
        opsf_centr2_err = numpy.empty((na)); opsf_centr2_err.fill(numpy.nan)
        opsf_bkg_err = numpy.empty((na)); opsf_bkg_err.fill(numpy.nan)
        opsf_flux = []
        opsf_centr1 = []
        opsf_centr2 = []
        for i in range(nsrc):
            opsf_flux.append(flux[i])
            opsf_centr1.append(OBJx[i])
            opsf_centr2.append(OBJy[i])

# load the plot arrays

    if status == 0:
        t = barytime
        for i in range(nsrc):
            fl[i] = flux[i]
            dx[i] = OBJx[i]
            dy[i] = OBJy[i]
        bg = b
        fx = wx
        fy = wy
        fa = angle
        rs = residual
        ch = chi2
                
# construct output primary extension

    if status == 0:
        for j in range(nsrc):
            hdu0 = pyfits.PrimaryHDU()
            for i in range(len(cards0)):
                if cards0[i].key not in list(hdu0.header.keys()):
                    hdu0.header.update(cards0[i].key, cards0[i].value, cards0[i].comment)
                else:
                    hdu0.header.cards[cards0[i].key].comment = cards0[i].comment
            status = kepkey.history(call,hdu0,outfile,logfile,verbose)
            outstr = HDUList(hdu0)

# construct output light curve extension

            col1 = Column(name='TIME',format='D',unit='BJD - 2454833',array=otime)
            col2 = Column(name='TIMECORR',format='E',unit='d',array=otimecorr)
            col3 = Column(name='CADENCENO',format='J',array=ocadenceno)
            col4 = Column(name='PSF_FLUX',format='E',unit='e-/s',array=opsf_flux[j])
            col5 = Column(name='PSF_FLUX_ERR',format='E',unit='e-/s',array=opsf_flux_err)
            col6 = Column(name='PSF_BKG',format='E',unit='e-/s/pix',array=opsf_bkg)
            col7 = Column(name='PSF_BKG_ERR',format='E',unit='e-/s',array=opsf_bkg_err)
            col8 = Column(name='PSF_CENTR1',format='E',unit='pixel',array=opsf_centr1[j])
            col9 = Column(name='PSF_CENTR1_ERR',format='E',unit='pixel',array=opsf_centr1_err)
            col10 = Column(name='PSF_CENTR2',format='E',unit='pixel',array=opsf_centr2[j])
            col11 = Column(name='PSF_CENTR2_ERR',format='E',unit='pixel',array=opsf_centr2_err)
            col12 = Column(name='PSF_FOCUS1',format='E',array=opsf_focus1)
            col13 = Column(name='PSF_FOCUS2',format='E',array=opsf_focus2)
            col14 = Column(name='PSF_ROTATION',format='E',unit='deg',array=opsf_rotation)
            col15 = Column(name='PSF_RESIDUAL',format='E',unit='e-/s',array=opsf_residual)
            col16 = Column(name='PSF_CHI2',format='E',array=opsf_chi2)
            col17 = Column(name='POS_CORR1',format='E',unit='pixel',array=opos_corr1)
            col18 = Column(name='POS_CORR2',format='E',unit='pixel',array=opos_corr2)
            col19 = Column(name='SAP_QUALITY',format='J',array=oquality)
            cols = ColDefs([col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,col11,
                            col12,col13,col14,col15,col16,col17,col18,col19])
            hdu1 = new_table(cols)
            for i in range(len(cards1)):
                if (cards1[i].key not in list(hdu1.header.keys()) and
                    cards1[i].key[:4] not in ['TTYP','TFOR','TUNI','TDIS','TDIM','WCAX','1CTY',
                                              '2CTY','1CRP','2CRP','1CRV','2CRV','1CUN','2CUN',
                                              '1CDE','2CDE','1CTY','2CTY','1CDL','2CDL','11PC',
                                              '12PC','21PC','22PC']):
                    hdu1.header.update(cards1[i].key, cards1[i].value, cards1[i].comment)
            outstr.append(hdu1)

# construct output mask bitmap extension

            hdu2 = ImageHDU(maskmap)
            for i in range(len(cards2)):
                if cards2[i].key not in list(hdu2.header.keys()):
                    hdu2.header.update(cards2[i].key, cards2[i].value, cards2[i].comment)
                else:
                    hdu2.header.cards[cards2[i].key].comment = cards2[i].comment
            outstr.append(hdu2)

# write output file

            outstr.writeto(outroot + '_' + str(j) + '.fits',checksum=True)

# close input structure

            status = kepio.closefits(struct,logfile,verbose)            

# clean up x-axis unit

    if status == 0:
        barytime0 = float(int(t[0] / 100) * 100.0)
        t -= barytime0
        t = numpy.insert(t,[0],[t[0]]) 
        t = numpy.append(t,[t[-1]])
        xlab = 'BJD $-$ %d' % barytime0

# plot the light curves

    if status == 0:
        bg = numpy.insert(bg,[0],[-1.0e10]) 
        bg = numpy.append(bg,-1.0e10)
        fx = numpy.insert(fx,[0],[fx[0]]) 
        fx = numpy.append(fx,fx[-1])
        fy = numpy.insert(fy,[0],[fy[0]]) 
        fy = numpy.append(fy,fy[-1])
        fa = numpy.insert(fa,[0],[fa[0]]) 
        fa = numpy.append(fa,fa[-1])
        rs = numpy.insert(rs,[0],[-1.0e10]) 
        rs = numpy.append(rs,-1.0e10)
        ch = numpy.insert(ch,[0],[-1.0e10]) 
        ch = numpy.append(ch,-1.0e10)
        for i in range(nsrc):

# clean up y-axis units

            nrm = math.ceil(math.log10(numpy.nanmax(fl[i]))) - 1.0
            fl[i] /= 10**nrm
            if nrm == 0:
                ylab1 = 'e$^-$ s$^{-1}$'
            else:
                ylab1 = '10$^{%d}$ e$^-$ s$^{-1}$' % nrm
            xx = copy(dx[i])
            yy = copy(dy[i])
            ylab2 = 'offset (pixels)'
            
# data limits

            xmin = numpy.nanmin(t)
            xmax = numpy.nanmax(t)
            ymin1 = numpy.nanmin(fl[i])
            ymax1 = numpy.nanmax(fl[i])
            ymin2 = numpy.nanmin(xx)
            ymax2 = numpy.nanmax(xx)
            ymin3 = numpy.nanmin(yy)
            ymax3 = numpy.nanmax(yy)
            ymin4 = numpy.nanmin(bg[1:-1])
            ymax4 = numpy.nanmax(bg[1:-1])
            ymin5 = numpy.nanmin([numpy.nanmin(fx),numpy.nanmin(fy)])
            ymax5 = numpy.nanmax([numpy.nanmax(fx),numpy.nanmax(fy)])
            ymin6 = numpy.nanmin(fa[1:-1])
            ymax6 = numpy.nanmax(fa[1:-1])
            ymin7 = numpy.nanmin(rs[1:-1])
            ymax7 = numpy.nanmax(rs[1:-1])
            ymin8 = numpy.nanmin(ch[1:-1])
            ymax8 = numpy.nanmax(ch[1:-1])
            xr = xmax - xmin
            yr1 = ymax1 - ymin1
            yr2 = ymax2 - ymin2
            yr3 = ymax3 - ymin3
            yr4 = ymax4 - ymin4
            yr5 = ymax5 - ymin5
            yr6 = ymax6 - ymin6
            yr7 = ymax7 - ymin7
            yr8 = ymax8 - ymin8
            fl[i] = numpy.insert(fl[i],[0],[0.0]) 
            fl[i] = numpy.append(fl[i],0.0)

# plot style

            try:
                params = {'backend': 'png',
                          'axes.linewidth': 2.5,
                          'axes.labelsize': 24,
                          'axes.font': 'sans-serif',
                          'axes.fontweight' : 'bold',
                          'text.fontsize': 12,
                          'legend.fontsize': 12,
                          'xtick.labelsize': 12,
                          'ytick.labelsize': 12}
                pylab.rcParams.update(params)
            except:
                pass

# define size of plot on monitor screen

            pylab.figure(str(i+1) + ' ' + str(time.asctime(time.localtime())),figsize=[12,16])

# delete any fossil plots in the matplotlib window

            pylab.clf()

# position first axes inside the plotting window

            ax = pylab.axes([0.11,0.523,0.78,0.45])

# force tick labels to be absolute rather than relative

            pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
            pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))

# no x-label

            pylab.setp(pylab.gca(),xticklabels=[])

# plot flux vs time

            ltime = numpy.array([],dtype='float64')
            ldata = numpy.array([],dtype='float32')
            dt = 0
            work1 = 2.0 * cadence / 86400
            for j in range(1,len(t)-1):
                dt = t[j] - t[j-1]
                if dt < work1:
                    ltime = numpy.append(ltime,t[j])
                    ldata = numpy.append(ldata,fl[i][j])
                else:
                    pylab.plot(ltime,ldata,color='#0000ff',linestyle='-',linewidth=1.0)
                    ltime = numpy.array([],dtype='float64')
                    ldata = numpy.array([],dtype='float32')
            pylab.plot(ltime,ldata,color='#0000ff',linestyle='-',linewidth=1.0)

# plot the fill color below data time series, with no data gaps

            pylab.fill(t,fl[i],fc='#ffff00',linewidth=0.0,alpha=0.2)

# define plot x and y limits

            pylab.xlim(xmin - xr * 0.01, xmax + xr * 0.01)
            if ymin1 - yr1 * 0.01 <= 0.0:
                pylab.ylim(1.0e-10, ymax1 + yr1 * 0.01)
            else:
                pylab.ylim(ymin1 - yr1 * 0.01, ymax1 + yr1 * 0.01)
           
# plot labels

#            pylab.xlabel(xlab, {'color' : 'k'})
            try:
                pylab.ylabel('Source (' + ylab1 + ')', {'color' : 'k'})
            except:
                ylab1 = '10**%d e-/s' % nrm
                pylab.ylabel('Source (' + ylab1 + ')', {'color' : 'k'})

# make grid on plot

            pylab.grid()

# plot centroid tracks - position second axes inside the plotting window

            if focus and background:
                axs = [0.11,0.433,0.78,0.09]
            elif background or focus:
                axs = [0.11,0.388,0.78,0.135]
            else:
                axs = [0.11,0.253,0.78,0.27]
            ax1 = pylab.axes(axs)

# force tick labels to be absolute rather than relative

            pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
            pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
            pylab.setp(pylab.gca(),xticklabels=[])

# plot dx vs time

            ltime = numpy.array([],dtype='float64')
            ldata = numpy.array([],dtype='float32')
            dt = 0
            work1 = 2.0 * cadence / 86400
            for j in range(1,len(t)-1):
                dt = t[j] - t[j-1]
                if dt < work1:
                    ltime = numpy.append(ltime,t[j])
                    ldata = numpy.append(ldata,xx[j-1])
                else:
                    ax1.plot(ltime,ldata,color='r',linestyle='-',linewidth=1.0)
                    ltime = numpy.array([],dtype='float64')
                    ldata = numpy.array([],dtype='float32')
            ax1.plot(ltime,ldata,color='r',linestyle='-',linewidth=1.0)

# define plot x and y limits

            pylab.xlim(xmin - xr * 0.01, xmax + xr * 0.01)
            pylab.ylim(ymin2 - yr2 * 0.03, ymax2 + yr2 * 0.03)
           
# plot labels

            ax1.set_ylabel('X-' + ylab2, color='k', fontsize=11)

# position second axes inside the plotting window

            ax2 = ax1.twinx()

# force tick labels to be absolute rather than relative

            pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
            pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
            pylab.setp(pylab.gca(),xticklabels=[])

# plot dy vs time

            ltime = numpy.array([],dtype='float64')
            ldata = numpy.array([],dtype='float32')
            dt = 0
            work1 = 2.0 * cadence / 86400
            for j in range(1,len(t)-1):
                dt = t[j] - t[j-1]
                if dt < work1:
                    ltime = numpy.append(ltime,t[j])
                    ldata = numpy.append(ldata,yy[j-1])
                else:
                    ax2.plot(ltime,ldata,color='g',linestyle='-',linewidth=1.0)
                    ltime = numpy.array([],dtype='float64')
                    ldata = numpy.array([],dtype='float32')
            ax2.plot(ltime,ldata,color='g',linestyle='-',linewidth=1.0)

# define plot y limits

            pylab.xlim(xmin - xr * 0.01, xmax + xr * 0.01)
            pylab.ylim(ymin3 - yr3 * 0.03, ymax3 + yr3 * 0.03)
           
# plot labels

            ax2.set_ylabel('Y-' + ylab2, color='k',fontsize=11)

# background - position third axes inside the plotting window

            if background and focus:
                axs = [0.11,0.343,0.78,0.09]
            if background and not focus:
                axs = [0.11,0.253,0.78,0.135]
            if background:
                ax1 = pylab.axes(axs)

# force tick labels to be absolute rather than relative

                pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
                pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
                pylab.setp(pylab.gca(),xticklabels=[])

# plot background vs time

                ltime = numpy.array([],dtype='float64')
                ldata = numpy.array([],dtype='float32')
                dt = 0
                work1 = 2.0 * cadence / 86400
                for j in range(1,len(t)-1):
                    dt = t[j] - t[j-1]
                    if dt < work1:
                        ltime = numpy.append(ltime,t[j])
                        ldata = numpy.append(ldata,bg[j])
                    else:
                        ax1.plot(ltime,ldata,color='#0000ff',linestyle='-',linewidth=1.0)
                        ltime = numpy.array([],dtype='float64')
                        ldata = numpy.array([],dtype='float32')
                ax1.plot(ltime,ldata,color='#0000ff',linestyle='-',linewidth=1.0)

# plot the fill color below data time series, with no data gaps

                pylab.fill(t,bg,fc='#ffff00',linewidth=0.0,alpha=0.2)

# define plot x and y limits

                pylab.xlim(xmin - xr * 0.01, xmax + xr * 0.01)
                pylab.ylim(ymin4 - yr4 * 0.03, ymax4 + yr4 * 0.03)
           
# plot labels

                ax1.set_ylabel('Background \n(e$^-$ s$^{-1}$ pix$^{-1}$)', 
                               multialignment='center', color='k',fontsize=11)

# make grid on plot

                pylab.grid()

# position focus axes inside the plotting window

            if focus and background:
                axs = [0.11,0.253,0.78,0.09]
            if focus and not background:
                axs = [0.11,0.253,0.78,0.135]
            if focus:
                ax1 = pylab.axes(axs)

# force tick labels to be absolute rather than relative
                
                pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
                pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
                pylab.setp(pylab.gca(),xticklabels=[])

# plot x-axis PSF width vs time

                ltime = numpy.array([],dtype='float64')
                ldata = numpy.array([],dtype='float32')
                dt = 0
                work1 = 2.0 * cadence / 86400
                for j in range(1,len(t)-1):
                    dt = t[j] - t[j-1]
                    if dt < work1:
                        ltime = numpy.append(ltime,t[j])
                        ldata = numpy.append(ldata,fx[j])
                    else:
                        ax1.plot(ltime,ldata,color='r',linestyle='-',linewidth=1.0)
                        ltime = numpy.array([],dtype='float64')
                        ldata = numpy.array([],dtype='float32')
                ax1.plot(ltime,ldata,color='r',linestyle='-',linewidth=1.0)

# plot y-axis PSF width vs time

                ltime = numpy.array([],dtype='float64')
                ldata = numpy.array([],dtype='float32')
                dt = 0
                work1 = 2.0 * cadence / 86400
                for j in range(1,len(t)-1):
                    dt = t[j] - t[j-1]
                    if dt < work1:
                        ltime = numpy.append(ltime,t[j])
                        ldata = numpy.append(ldata,fy[j])
                    else:
                        ax1.plot(ltime,ldata,color='g',linestyle='-',linewidth=1.0)
                        ltime = numpy.array([],dtype='float64')
                        ldata = numpy.array([],dtype='float32')
                ax1.plot(ltime,ldata,color='g',linestyle='-',linewidth=1.0)

# define plot x and y limits

                pylab.xlim(xmin - xr * 0.01, xmax + xr * 0.01)
                pylab.ylim(ymin5 - yr5 * 0.03, ymax5 + yr5 * 0.03)
           
# plot labels

                ax1.set_ylabel('Pixel Scale\nFactor', 
                               multialignment='center', color='k',fontsize=11)

# Focus rotation - position second axes inside the plotting window

                ax2 = ax1.twinx()

# force tick labels to be absolute rather than relative

                pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
                pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
                pylab.setp(pylab.gca(),xticklabels=[])

# plot dy vs time

                ltime = numpy.array([],dtype='float64')
                ldata = numpy.array([],dtype='float32')
                dt = 0
                work1 = 2.0 * cadence / 86400
                for j in range(1,len(t)-1):
                    dt = t[j] - t[j-1]
                    if dt < work1:
                        ltime = numpy.append(ltime,t[j])
                        ldata = numpy.append(ldata,fa[j])
                    else:
                        ax2.plot(ltime,ldata,color='#000080',linestyle='-',linewidth=1.0)
                        ltime = numpy.array([],dtype='float64')
                        ldata = numpy.array([],dtype='float32')
                ax2.plot(ltime,ldata,color='#000080',linestyle='-',linewidth=1.0)

# define plot y limits
                
                pylab.xlim(xmin - xr * 0.01, xmax + xr * 0.01)
                pylab.ylim(ymin6 - yr6 * 0.03, ymax6 + yr6 * 0.03)
           
# plot labels

                ax2.set_ylabel('Rotation (deg)', color='k',fontsize=11)

# fit residuals - position fifth axes inside the plotting window

            axs = [0.11,0.163,0.78,0.09]
            ax1 = pylab.axes(axs)

# force tick labels to be absolute rather than relative

            pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
            pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
            pylab.setp(pylab.gca(),xticklabels=[])

# plot residual vs time

            ltime = numpy.array([],dtype='float64')
            ldata = numpy.array([],dtype='float32')
            dt = 0
            work1 = 2.0 * cadence / 86400
            for j in range(1,len(t)-1):
                dt = t[j] - t[j-1]
                if dt < work1:
                    ltime = numpy.append(ltime,t[j])
                    ldata = numpy.append(ldata,rs[j])
                else:
                    ax1.plot(ltime,ldata,color='b',linestyle='-',linewidth=1.0)
                    ltime = numpy.array([],dtype='float64')
                    ldata = numpy.array([],dtype='float32')
            ax1.plot(ltime,ldata,color='b',linestyle='-',linewidth=1.0)

# plot the fill color below data time series, with no data gaps

            pylab.fill(t,rs,fc='#ffff00',linewidth=0.0,alpha=0.2)

# define plot x and y limits

            pylab.xlim(xmin - xr * 0.01, xmax + xr * 0.01)
            pylab.ylim(ymin7 - yr7 * 0.03, ymax7 + yr7 * 0.03)
           
# plot labels

            ax1.set_ylabel('Residual \n(e$^-$ s$^{-1}$)', 
                           multialignment='center', color='k',fontsize=11)

# make grid on plot

            pylab.grid()

# fit chi square - position sixth axes inside the plotting window

            axs = [0.11,0.073,0.78,0.09]
            ax1 = pylab.axes(axs)

# force tick labels to be absolute rather than relative

            pylab.gca().xaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))
            pylab.gca().yaxis.set_major_formatter(pylab.ScalarFormatter(useOffset=False))

# plot background vs time

            ltime = numpy.array([],dtype='float64')
            ldata = numpy.array([],dtype='float32')
            dt = 0
            work1 = 2.0 * cadence / 86400
            for j in range(1,len(t)-1):
                dt = t[j] - t[j-1]
                if dt < work1:
                    ltime = numpy.append(ltime,t[j])
                    ldata = numpy.append(ldata,ch[j])
                else:
                    ax1.plot(ltime,ldata,color='b',linestyle='-',linewidth=1.0)
                    ltime = numpy.array([],dtype='float64')
                    ldata = numpy.array([],dtype='float32')
            ax1.plot(ltime,ldata,color='b',linestyle='-',linewidth=1.0)

# plot the fill color below data time series, with no data gaps

            pylab.fill(t,ch,fc='#ffff00',linewidth=0.0,alpha=0.2)

# define plot x and y limits

            pylab.xlim(xmin - xr * 0.01, xmax + xr * 0.01)
            pylab.ylim(ymin8 - yr8 * 0.03, ymax8 + yr8 * 0.03)
           
# plot labels

            ax1.set_ylabel('$\chi^2$ (%d dof)' % (npix-len(guess)-1),color='k',fontsize=11)
            pylab.xlabel(xlab, {'color' : 'k'})

# make grid on plot

            pylab.grid()

# render plot

            if status == 0:
                pylab.savefig(outroot + '_' + str(i) + '.png')
            if status == 0 and plt:
                if cmdLine: 
                    pylab.show(block=True)
                else: 
                    pylab.ion()
                    pylab.plot([])
                    pylab.ioff()
        
# stop time

    kepmsg.clock('\n\nKEPPRFPHOT ended at',logfile,verbose)

    return
Example #44
0
def kepbinary(infile, outfile, datacol, m1, m2, r1, r2, period, bjd0, eccn,
              omega, inclination, c1, c2, c3, c4, albedo, depth, contamination,
              gamma, fitparams, eclipses, dopboost, tides, job, clobber,
              verbose, logfile, status):

    # startup parameters

    status = 0
    labelsize = 24
    ticksize = 16
    xsize = 17
    ysize = 7
    lcolor = '#0000ff'
    lwidth = 1.0
    fcolor = '#ffff00'
    falpha = 0.2

    # log the call

    hashline = '----------------------------------------------------------------------------'
    kepmsg.log(logfile, hashline, verbose)
    call = 'KEPBINARY -- '
    call += 'infile=' + infile + ' '
    call += 'outfile=' + outfile + ' '
    call += 'datacol=' + datacol + ' '
    call += 'm1=' + str(m1) + ' '
    call += 'm2=' + str(m2) + ' '
    call += 'r1=' + str(r1) + ' '
    call += 'r2=' + str(r2) + ' '
    call += 'period=' + str(period) + ' '
    call += 'bjd0=' + str(bjd0) + ' '
    call += 'eccn=' + str(eccn) + ' '
    call += 'omega=' + str(omega) + ' '
    call += 'inclination=' + str(inclination) + ' '
    call += 'c1=' + str(c1) + ' '
    call += 'c2=' + str(c2) + ' '
    call += 'c3=' + str(c3) + ' '
    call += 'c4=' + str(c4) + ' '
    call += 'albedo=' + str(albedo) + ' '
    call += 'depth=' + str(depth) + ' '
    call += 'contamination=' + str(contamination) + ' '
    call += 'gamma=' + str(gamma) + ' '
    call += 'fitparams=' + str(fitparams) + ' '
    eclp = 'n'
    if (eclipses): eclp = 'y'
    call += 'eclipses=' + eclp + ' '
    boost = 'n'
    if (dopboost): boost = 'y'
    call += 'dopboost=' + boost + ' '
    distort = 'n'
    if (tides): distort = 'y'
    call += 'tides=' + distort + ' '
    call += 'job=' + str(job) + ' '
    overwrite = 'n'
    if (clobber): overwrite = 'y'
    call += 'clobber=' + overwrite + ' '
    chatter = 'n'
    if (verbose): chatter = 'y'
    call += 'verbose=' + chatter + ' '
    call += 'logfile=' + logfile
    kepmsg.log(logfile, call + '\n', verbose)

    # start time

    kepmsg.clock('KEPBINARY started at', logfile, verbose)

    # test log file

    logfile = kepmsg.test(logfile)

    # check and format the list of fit parameters

    if status == 0 and job == 'fit':
        allParams = [m1, m2, r1, r2, period, bjd0, eccn, omega, inclination]
        allNames = [
            'm1', 'm2', 'r1', 'r2', 'period', 'bjd0', 'eccn', 'omega',
            'inclination'
        ]
        fitparams = re.sub('\|', ',', fitparams.strip())
        fitparams = re.sub('\.', ',', fitparams.strip())
        fitparams = re.sub(';', ',', fitparams.strip())
        fitparams = re.sub(':', ',', fitparams.strip())
        fitparams = re.sub('\s+', ',', fitparams.strip())
        fitparams, status = kepio.parselist(fitparams, logfile, verbose)
        for fitparam in fitparams:
            if fitparam.strip() not in allNames:
                message = 'ERROR -- KEPBINARY: unknown field in list of fit parameters'
                status = kepmsg.err(logfile, message, verbose)

# clobber output file

    if status == 0:
        if clobber: status = kepio.clobber(outfile, logfile, verbose)
        if kepio.fileexists(outfile):
            message = 'ERROR -- KEPBINARY: ' + outfile + ' exists. Use --clobber'
            status = kepmsg.err(logfile, message, verbose)

# open input file

    if status == 0:
        instr, status = kepio.openfits(infile, 'readonly', logfile, verbose)
    if status == 0:
        tstart, tstop, bjdref, cadence, status = kepio.timekeys(
            instr, infile, logfile, verbose, status)
    if status == 0:
        try:
            work = instr[0].header['FILEVER']
            cadenom = 1.0
        except:
            cadenom = cadence

# check the data column exists

    if status == 0:
        try:
            instr[1].data.field(datacol)
        except:
            message = 'ERROR -- KEPBINARY: ' + datacol + ' column does not exist in ' + infile + '[1]'
            status = kepmsg.err(logfile, message, verbose)

# fudge non-compliant FITS keywords with no values

    if status == 0:
        instr = kepkey.emptykeys(instr, file, logfile, verbose)

# read table structure

    if status == 0:
        table, status = kepio.readfitstab(infile, instr[1], logfile, verbose)

# filter input data table

    if status == 0:
        try:
            nanclean = instr[1].header['NANCLEAN']
        except:
            naxis2 = 0
            try:
                for i in range(len(table.field(0))):
                    if numpy.isfinite(table.field('barytime')[i]) and \
                            numpy.isfinite(table.field(datacol)[i]):
                        table[naxis2] = table[i]
                        naxis2 += 1
                        instr[1].data = table[:naxis2]
            except:
                for i in range(len(table.field(0))):
                    if numpy.isfinite(table.field('time')[i]) and \
                            numpy.isfinite(table.field(datacol)[i]):
                        table[naxis2] = table[i]
                        naxis2 += 1
                        instr[1].data = table[:naxis2]
            comment = 'NaN cadences removed from data'
            status = kepkey.new('NANCLEAN', True, comment, instr[1], outfile,
                                logfile, verbose)

# read table columns

    if status == 0:
        try:
            time = instr[1].data.field('barytime')
        except:
            time, status = kepio.readfitscol(infile, instr[1].data, 'time',
                                             logfile, verbose)
        indata, status = kepio.readfitscol(infile, instr[1].data, datacol,
                                           logfile, verbose)
    if status == 0:
        time = time + bjdref
        indata = indata / cadenom

# limb-darkening cofficients

    if status == 0:
        limbdark = numpy.array([c1, c2, c3, c4], dtype='float32')

# time details for model

    if status == 0:
        npt = len(time)
        exptime = numpy.zeros((npt), dtype='float64')
        dtype = numpy.zeros((npt), dtype='int')
        for i in range(npt):
            try:
                exptime[i] = time[i + 1] - time[i]
            except:
                exptime[i] = time[i] - time[i - 1]

# calculate binary model

    if status == 0:
        tmodel = kepsim.transitModel(1.0, m1, m2, r1, r2, period, inclination,
                                     bjd0, eccn, omega, depth, albedo, c1, c2,
                                     c3, c4, gamma, contamination, npt, time,
                                     exptime, dtype, eclipses, dopboost, tides)

# re-normalize binary model to data

    if status == 0 and (job == 'overlay' or job == 'fit'):
        dmedian = numpy.median(indata)
        tmodel = tmodel / numpy.median(tmodel) * dmedian

# define arrays of floating and frozen parameters

    if status == 0 and job == 'fit':
        params = []
        paramNames = []
        arguments = []
        argNames = []
        for i in range(len(allNames)):
            if allNames[i] in fitparams:
                params.append(allParams[i])
                paramNames.append(allNames[i])
            else:
                arguments.append(allParams[i])
                argNames.append(allNames[i])
        params.append(dmedian)
        params = numpy.array(params, dtype='float32')

# subtract model from data

    if status == 0 and job == 'fit':
        deltam = numpy.abs(indata - tmodel)

# fit statistics

    if status == 0 and job == 'fit':
        aveDelta = numpy.sum(deltam) / npt
        chi2 = math.sqrt(
            numpy.sum(
                (indata - tmodel) * (indata - tmodel) / (npt - len(params))))

# fit model to data using downhill simplex

    if status == 0 and job == 'fit':
        print ''
        print '%4s %11s %11s' % ('iter', 'delta', 'chi^2')
        print '----------------------------'
        print '%4d %.5E %.5E' % (0, aveDelta, chi2)
        bestFit = scipy.optimize.fmin(
            fitModel,
            params,
            args=(paramNames, dmedian, m1, m2, r1, r2, period, bjd0, eccn,
                  omega, inclination, depth, albedo, c1, c2, c3, c4, gamma,
                  contamination, npt, time, exptime, indata, dtype, eclipses,
                  dopboost, tides),
            maxiter=1e4)

# calculate best fit binary model

    if status == 0 and job == 'fit':
        print ''
        for i in range(len(paramNames)):
            if 'm1' in paramNames[i].lower():
                m1 = bestFit[i]
                print '  M1 = %.3f Msun' % bestFit[i]
            elif 'm2' in paramNames[i].lower():
                m2 = bestFit[i]
                print '  M2 = %.3f Msun' % bestFit[i]
            elif 'r1' in paramNames[i].lower():
                r1 = bestFit[i]
                print '  R1 = %.4f Rsun' % bestFit[i]
            elif 'r2' in paramNames[i].lower():
                r2 = bestFit[i]
                print '  R2 = %.4f Rsun' % bestFit[i]
            elif 'period' in paramNames[i].lower():
                period = bestFit[i]
            elif 'bjd0' in paramNames[i].lower():
                bjd0 = bestFit[i]
                print 'BJD0 = %.8f' % bestFit[i]
            elif 'eccn' in paramNames[i].lower():
                eccn = bestFit[i]
                print '   e = %.3f' % bestFit[i]
            elif 'omega' in paramNames[i].lower():
                omega = bestFit[i]
                print '   w = %.3f deg' % bestFit[i]
            elif 'inclination' in paramNames[i].lower():
                inclination = bestFit[i]
                print '   i = %.3f deg' % bestFit[i]
        flux = bestFit[-1]
        print ''
        tmodel = kepsim.transitModel(flux, m1, m2, r1, r2, period, inclination,
                                     bjd0, eccn, omega, depth, albedo, c1, c2,
                                     c3, c4, gamma, contamination, npt, time,
                                     exptime, dtype, eclipses, dopboost, tides)

# subtract model from data

    if status == 0:
        deltaMod = indata - tmodel

# standard deviation of model

    if status == 0:
        stdDev = math.sqrt(
            numpy.sum((indata - tmodel) * (indata - tmodel)) / npt)

# clean up x-axis unit

    if status == 0:
        time0 = float(int(tstart / 100) * 100.0)
        ptime = time - time0
        xlab = 'BJD $-$ %d' % time0

# clean up y-axis units

    if status == 0:
        nrm = len(str(int(indata.max()))) - 1
        pout = indata / 10**nrm
        pmod = tmodel / 10**nrm
        pres = deltaMod / stdDev
        if job == 'fit' or job == 'overlay':
            try:
                ylab1 = 'Flux (10$^%d$ e$^-$ s$^{-1}$)' % nrm
                ylab2 = 'Residual ($\sigma$)'
            except:
                ylab1 = 'Flux (10**%d e-/s)' % nrm
                ylab2 = 'Residual (sigma)'
        else:
            ylab1 = 'Normalized Flux'

# dynamic range of model plot

    if status == 0 and job == 'model':
        xmin = ptime.min()
        xmax = ptime.max()
        ymin = tmodel.min()
        ymax = tmodel.max()

# dynamic range of model/data overlay or fit

    if status == 0 and (job == 'overlay' or job == 'fit'):
        xmin = ptime.min()
        xmax = ptime.max()
        ymin = pout.min()
        ymax = pout.max()
        tmin = pmod.min()
        tmax = pmod.max()
        ymin = numpy.array([ymin, tmin]).min()
        ymax = numpy.array([ymax, tmax]).max()
        rmin = pres.min()
        rmax = pres.max()

# pad the dynamic range

    if status == 0:
        xr = (xmax - xmin) / 80
        yr = (ymax - ymin) / 40
        if job == 'overlay' or job == 'fit':
            rr = (rmax - rmin) / 40

# set up plot style

    if status == 0:
        labelsize = 24
        ticksize = 16
        xsize = 17
        ysize = 7
        lcolor = '#0000ff'
        lwidth = 1.0
        fcolor = '#ffff00'
        falpha = 0.2
        params = {
            'backend': 'png',
            'axes.linewidth': 2.5,
            'axes.labelsize': 24,
            'axes.font': 'sans-serif',
            'axes.fontweight': 'bold',
            'text.fontsize': 12,
            'legend.fontsize': 12,
            'xtick.labelsize': 16,
            'ytick.labelsize': 16
        }
        pylab.rcParams.update(params)
        pylab.figure(figsize=[14, 10])
        pylab.clf()

        # main plot window

        ax = pylab.axes([0.05, 0.3, 0.94, 0.68])
        pylab.gca().xaxis.set_major_formatter(
            pylab.ScalarFormatter(useOffset=False))
        pylab.gca().yaxis.set_major_formatter(
            pylab.ScalarFormatter(useOffset=False))
        labels = ax.get_yticklabels()
        setp(labels, 'rotation', 90, fontsize=12)

# plot model time series

    if status == 0 and job == 'model':
        pylab.plot(ptime,
                   tmodel,
                   color='#0000ff',
                   linestyle='-',
                   linewidth=1.0)
        ptime = numpy.insert(ptime, [0.0], ptime[0])
        ptime = numpy.append(ptime, ptime[-1])
        tmodel = numpy.insert(tmodel, [0.0], 0.0)
        tmodel = numpy.append(tmodel, 0.0)
        pylab.fill(ptime, tmodel, fc='#ffff00', linewidth=0.0, alpha=0.2)

# plot data time series and best fit

    if status == 0 and (job == 'overlay' or job == 'fit'):
        pylab.plot(ptime, pout, color='#0000ff', linestyle='-', linewidth=1.0)
        ptime = numpy.insert(ptime, [0.0], ptime[0])
        ptime = numpy.append(ptime, ptime[-1])
        pout = numpy.insert(pout, [0], 0.0)
        pout = numpy.append(pout, 0.0)
        pylab.fill(ptime, pout, fc='#ffff00', linewidth=0.0, alpha=0.2)
        pylab.plot(ptime[1:-1], pmod, color='r', linestyle='-', linewidth=2.0)

# ranges and labels

    if status == 0:
        pylab.xlim(xmin - xr, xmax + xr)
        pylab.ylim(ymin - yr, ymax + yr)
        pylab.xlabel(xlab, {'color': 'k'})
        pylab.ylabel(ylab1, {'color': 'k'})

# residual plot window

    if status == 0 and (job == 'overlay' or job == 'fit'):
        ax = pylab.axes([0.05, 0.07, 0.94, 0.23])
        pylab.gca().xaxis.set_major_formatter(
            pylab.ScalarFormatter(useOffset=False))
        pylab.gca().yaxis.set_major_formatter(
            pylab.ScalarFormatter(useOffset=False))
        labels = ax.get_yticklabels()
        setp(labels, 'rotation', 90, fontsize=12)

# plot residual time series

    if status == 0 and (job == 'overlay' or job == 'fit'):
        pylab.plot([ptime[0], ptime[-1]], [0.0, 0.0],
                   color='r',
                   linestyle='--',
                   linewidth=1.0)
        pylab.plot([ptime[0], ptime[-1]], [-1.0, -1.0],
                   color='r',
                   linestyle='--',
                   linewidth=1.0)
        pylab.plot([ptime[0], ptime[-1]], [1.0, 1.0],
                   color='r',
                   linestyle='--',
                   linewidth=1.0)
        pylab.plot(ptime[1:-1],
                   pres,
                   color='#0000ff',
                   linestyle='-',
                   linewidth=1.0)
        pres = numpy.insert(pres, [0], rmin)
        pres = numpy.append(pres, rmin)
        pylab.fill(ptime, pres, fc='#ffff00', linewidth=0.0, alpha=0.2)

# ranges and labels of residual time series

    if status == 0 and (job == 'overlay' or job == 'fit'):
        pylab.xlim(xmin - xr, xmax + xr)
        pylab.ylim(rmin - rr, rmax + rr)
        pylab.xlabel(xlab, {'color': 'k'})
        pylab.ylabel(ylab2, {'color': 'k'})

# display the plot

    if status == 0:
        pylab.draw()
    # polyhedron
    for k in range(m):
        edge = X[[k,k+1],:] + 0.1 * matrix([1., 0., 0., -1.], (2,2)) * \
            (X[2*[k],:] - X[2*[k+1],:])
        pylab.plot(edge[:, 0], edge[:, 1], 'k')

    # 1000 points on the unit circle
    nopts = 1000
    angles = matrix([a * 2.0 * pi / nopts for a in range(nopts)], (1, nopts))
    circle = matrix(0.0, (2, nopts))
    circle[0, :], circle[1, :] = R * cos(angles), R * sin(angles)
    circle += xc[:, nopts * [0]]

    # plot maximum inscribed disk
    pylab.fill(circle[0, :].T, circle[1, :].T, facecolor='#F0F0F0')
    pylab.plot([xc[0]], [xc[1]], 'ko')
    pylab.title('Chebyshev center (fig 8.5)')
    pylab.axis('equal')
    pylab.axis('off')

# Maximum volume enclosed ellipsoid center
#
# minimize    -log det B
# subject to  ||B * gk||_2 + gk'*c <= hk,  k=1,...,m
#
# with variables  B and c.
#
# minimize    -log det L
# subject to  ||L' * gk||_2^2 / (hk - gk'*c) <= hk - gk'*c,  k=1,...,m
#
Example #46
0
def scatter(df,
            x,
            y,
            size=None,
            color=None,
            groupby=None,
            color_dict={},
            legend=True):
    """ Generate scatter plot

    Parameters
    ----------
    df : pandas.DataFrame
    x, y : str
      columns to use for x- and y-axis
    size, color : str, optional
      columns to use for size and color of scatter
    groupby : str or list, optional
      column or columns to group plots by, generating subplots for
      each member of the grouping

    Results
    -------

    (Eventually) Return a str full of html/javascript that shows this
    scatter when loaded into a web browser

    For now, just use matplotlib
    """
    for col in [x, y, size, color]:
        if col != None:
            assert col in df, 'Column "%s" not found in DataFrame' % col  # TODO: say which param has the bad col name
    # TODO: check that groupby appears and there are not too many groups

    if color != None and color_dict == {}:
        color_vals = pl.unique(df[color].__array__())
        assert len(color_vals) <= 6, 'color can have at most 6 distinct values'
        color_dict = dict([[col_i, colors[i]]
                           for i, col_i in enumerate(color_vals)])
    if groupby != None:
        groups = df.groupby(groupby)

        n = len(groups)
        c = pl.ceil(pl.sqrt(n))
        r = pl.ceil(n / c)

        prev_subplot = None
        for i, (g, sub_df) in enumerate(groups):
            prev_subplot = pl.subplot(r,
                                      c,
                                      i + 1,
                                      sharex=prev_subplot,
                                      sharey=prev_subplot)
            pl.title('\n\n%s = %s' % (groupby, g),
                     fontsize='small',
                     verticalalignment='top')
            scatter(sub_df,
                    x,
                    y,
                    size,
                    color,
                    color_dict=color_dict,
                    legend=False)

            if i == (r - 1) * c:
                pl.xlabel(x, ha='left')
            else:
                pl.xlabel('')

            if i == 0:
                pl.ylabel(y, va='top')
            else:
                pl.ylabel('')

        pl.yticks([])
        pl.xticks([])
        pl.subplots_adjust(wspace=0, hspace=0)
        pl.legend(loc='upper left', bbox_to_anchor=(1, 1))

    else:
        if size == None:
            s = 100
        else:
            s = 10 + 500 * (df[size] - df[size].min()) / (df[size].max() -
                                                          df[size].min())
            s[pl.isnan(s)] = 100

        if color_dict:
            c = df[color].map(color_dict)
        else:
            c = [colors[0] for _ in df[y]]

        # Requirements
        #   Show category name and color
        #   Show marker size and number
        #   Mouse-over to highlight all markers of that color, or near that size
        #   Select only certain parts of the data
        #   Select marker to see all data associated with it
        pl.scatter(jitter(df, x).__array__(),
                   jitter(df, y).__array__(),
                   s=s,
                   c=list(c),
                   linewidths=0,
                   alpha=.5)

        for label in color_dict:
            pl.fill([0], [0], color=color_dict[label], label=label)
        pl.xlabel(x)
        pl.ylabel(y)

        if legend:
            pl.legend()
Example #47
0
def plot_decision_boundary_2d(dataset,
                              clf=None,
                              targets=None,
                              regions=None,
                              maps=None,
                              maps_res=50,
                              vals=None,
                              data_callback=None):
    """Plot a scatter of a classifier's decision boundary and data points

    Assumes data is 2d (no way to visualize otherwise!!)

    Parameters
    ----------
    dataset : `Dataset`
      Data points to visualize (might be the data `clf` was train on, or
      any novel data).
    clf : `Classifier`, optional
      Trained classifier
    targets : string, optional
      What samples attributes to use for targets.  If None and clf is
      provided, then `clf.params.targets_attr` is used.
    regions : string, optional
      Plot regions (polygons) around groups of samples with the same
      attribute (and target attribute) values. E.g. chunks.
    maps : string in {'targets', 'estimates'}, optional
      Either plot underlying colored maps, such as clf predictions
      within the spanned regions, or estimates from the classifier
      (might not work for some).
    maps_res : int, optional
      Number of points in each direction to evaluate.
      Points are between axis limits, which are set automatically by
      matplotlib.  Higher number will yield smoother decision lines but come
      at the cost of O^2 classifying time/memory.
    vals : array of floats, optional
      Where to draw the contour lines if maps='estimates'
    data_callback : callable, optional
      Callable object to preprocess the new data points.
      Classified points of the form samples = data_callback(xysamples).
      I.e. this can be a function to normalize them, or cache them
      before they are classified.
    """
    if vals is None:
        vals = [-1, 0, 1]

    if False:
        ## from mvpa2.misc.data_generators import *
        ## from mvpa2.clfs.svm import *
        ## from mvpa2.clfs.knn import *
        ## ds = dumb_feature_binary_dataset()
        dataset = normal_feature_dataset(nfeatures=2,
                                         nchunks=5,
                                         snr=10,
                                         nlabels=4,
                                         means=[[0, 1], [1, 0], [1, 1], [0,
                                                                         0]])
        dataset.samples += dataset.sa.chunks[:,
                                             None] * 0.1  # slight shifts for chunks ;)
        #dataset = normal_feature_dataset(nfeatures=2, nlabels=3, means=[ [0,1], [1,0], [1,1] ])
        #dataset = normal_feature_dataset(nfeatures=2, nlabels=2, means=[ [0,1], [1,0] ])
        #clf = LinearCSVMC(C=-1)
        clf = kNN(4)  #LinearCSVMC(C=-1)
        clf.train(dataset)
        #clf = None
        #plot_decision_boundary_2d(ds, clf)
        targets = 'targets'
        regions = 'chunks'
        #maps = 'estimates'
        maps = 'targets'
        #maps = None #'targets'
        res = 50
        vals = [-1, 0, 1]
        data_callback = None
        pl.clf()

    if dataset.nfeatures != 2:
        raise ValueError('Can only plot a decision boundary in 2D')

    Pioff()
    a = pl.gca()  # f.add_subplot(1,1,1)

    attrmap = None
    if clf:
        estimates_were_enabled = clf.ca.is_enabled('estimates')
        clf.ca.enable('estimates')

        if targets is None:
            targets = clf.get_space()
        # Lets reuse classifiers attrmap if it is good enough
        attrmap = clf._attrmap
        predictions = clf.predict(dataset)

    targets_sa_name = targets  # bad Yarik -- will rebind targets to actual values
    targets_lit = dataset.sa[targets_sa_name].value
    utargets_lit = dataset.sa[targets_sa_name].unique

    if not (attrmap is not None and len(attrmap)
            and set(clf._attrmap.keys()).issuperset(utargets_lit)):
        # create our own
        attrmap = AttributeMap(mapnumeric=True)

    targets = attrmap.to_numeric(targets_lit)
    utargets = attrmap.to_numeric(utargets_lit)

    vmin = min(utargets)
    vmax = max(utargets)
    cmap = pl.cm.RdYlGn  # argument

    # Scatter points
    if clf:
        all_hits = predictions == targets_lit
    else:
        all_hits = np.ones((len(targets), ), dtype=bool)

    targets_colors = {}
    for l in utargets:
        targets_mask = targets == l
        s = dataset[targets_mask]
        targets_colors[l] = c \
            = cmap((l-vmin)/float(vmax-vmin))

        # We want to plot hits and misses with different symbols
        hits = all_hits[targets_mask]
        misses = np.logical_not(hits)
        scatter_kwargs = dict(c=[c], zorder=10 + (l - vmin))

        if sum(hits):
            a.scatter(s.samples[hits, 0],
                      s.samples[hits, 1],
                      marker='o',
                      label='%s [%d]' % (attrmap.to_literal(l), sum(hits)),
                      **scatter_kwargs)
        if sum(misses):
            a.scatter(s.samples[misses, 0],
                      s.samples[misses, 1],
                      marker='x',
                      label='%s [%d] (miss)' %
                      (attrmap.to_literal(l), sum(misses)),
                      edgecolor=[c],
                      **scatter_kwargs)

    (xmin, xmax) = a.get_xlim()
    (ymin, ymax) = a.get_ylim()
    extent = (xmin, xmax, ymin, ymax)

    # Create grid to evaluate, predict it
    (x, y) = np.mgrid[xmin:xmax:np.complex(0, maps_res),
                      ymin:ymax:np.complex(0, maps_res)]
    news = np.vstack((x.ravel(), y.ravel())).T
    try:
        news = data_callback(news)
    except TypeError:  # Not a callable object
        pass

    imshow_kwargs = dict(origin='lower',
                         zorder=1,
                         aspect='auto',
                         interpolation='bilinear',
                         alpha=0.9,
                         cmap=cmap,
                         vmin=vmin,
                         vmax=vmax,
                         extent=extent)

    if maps is not None:
        if clf is None:
            raise ValueError(
                "Please provide classifier for plotting maps of %s" % maps)
        predictions_new = clf.predict(news)

    if maps == 'estimates':
        # Contour and show predictions
        trained_targets = attrmap.to_numeric(clf.ca.trained_targets)

        if len(trained_targets) == 2:
            linestyles = []
            for v in vals:
                if v == 0:
                    linestyles.append('solid')
                else:
                    linestyles.append('dashed')
            vmin, vmax = -3, 3  # Gives a nice tonal range ;)
            map_ = 'estimates'  # should actually depend on estimates
        else:
            vals = (trained_targets[:-1] + trained_targets[1:]) / 2.
            linestyles = ['solid'] * len(vals)
            map_ = 'targets'

        try:
            clf.ca.estimates.reshape(x.shape)
            a.imshow(map_values.T, **imshow_kwargs)
            CS = a.contour(x,
                           y,
                           map_values,
                           vals,
                           zorder=6,
                           linestyles=linestyles,
                           extent=extent,
                           colors='k')
        except ValueError as e:
            print("Sorry - plotting of estimates isn't full supported for %s. " \
                  "Got exception %s" % (clf, e))
    elif maps == 'targets':
        map_values = attrmap.to_numeric(predictions_new).reshape(x.shape)
        a.imshow(map_values.T, **imshow_kwargs)
        #CS = a.contour(x, y, map_values, vals, zorder=6,
        #               linestyles=linestyles, extent=extent, colors='k')

    # Plot regions belonging to the same pair of attribute given
    # (e.g. chunks) and targets attribute
    if regions:
        chunks_sa = dataset.sa[regions]
        chunks_lit = chunks_sa.value
        uchunks_lit = chunks_sa.value
        chunks_attrmap = AttributeMap(mapnumeric=True)
        chunks = chunks_attrmap.to_numeric(chunks_lit)
        uchunks = chunks_attrmap.to_numeric(uchunks_lit)

        from matplotlib.delaunay.triangulate import Triangulation
        from matplotlib.patches import Polygon
        # Lets figure out convex halls for each chunk/label pair
        for target in utargets:
            t_mask = targets == target
            for chunk in uchunks:
                tc_mask = np.logical_and(t_mask, chunk == chunks)
                tc_samples = dataset.samples[tc_mask]
                tr = Triangulation(tc_samples[:, 0], tc_samples[:, 1])
                poly = pl.fill(
                    tc_samples[tr.hull, 0],
                    tc_samples[tr.hull, 1],
                    closed=True,
                    facecolor=targets_colors[target],
                    #fill=False,
                    alpha=0.01,
                    edgecolor='gray',
                    linestyle='dotted',
                    linewidth=0.5,
                )

    pl.legend(scatterpoints=1)
    if clf and not estimates_were_enabled:
        clf.ca.disable('estimates')
    Pion()
    pl.axis('tight')
Example #48
0
# Perform a unary union of the polygon spots, dissolving them into a
# collection of polygon patches
patches = unary_union(spots)

if __name__ == "__main__":
    # Illustrate the results using matplotlib's pylab interface
    pylab.figure(num=None, figsize=(4, 4), dpi=180)

    for patch in patches.geoms:
        assert patch.geom_type in ['Polygon']
        assert patch.is_valid

        # Fill and outline each patch
        x, y = patch.exterior.xy
        pylab.fill(x, y, color='#cccccc', aa=True)
        pylab.plot(x, y, color='#666666', aa=True, lw=1.0)

        # Do the same for the holes of the patch
        for hole in patch.interiors:
            x, y = hole.xy
            pylab.fill(x, y, color='#ffffff', aa=True)
            pylab.plot(x, y, color='#999999', aa=True, lw=1.0)

    # Plot the original points
    pylab.plot([p.x for p in points], [p.y for p in points], 'b,', alpha=0.75)

    # Write the number of patches and the total patch area to the figure
    pylab.text(
        -25, 25,
        "Patches: %d, total area: %.2f" % (len(patches.geoms), patches.area))
        toSee[x][y] = False
        rgb = im.getpixel((x, h - 1 - y))
        for i in range(3):
            col[i] += rgb[i]
        np = 1
        for a, b in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
            if a >= 0 and a < w and b >= 0 and b < h and toSee[a][b]:
                c2, n2 = getCol(a, b, P, False)
                for i in range(3):
                    col[i] += c2[i]
                np += n2
    return col, np


sn = 0
for p in vs:
    ps = vs[p]
    if len(ps) > 2:
        P = convex_hull(ps)
        col, np = getCol(max(0, min(w - 1, int(p.x * w / rat))),
                         max(0, min(h - 1, int(p.y * h))), P)
        sn += np
        for i in range(3):
            col[i] /= np * 255
        x, y = setToLists(P)
        pl.fill(x, y, alpha=0.9, color=col)
print(sn, w * h)
xc, yc = setToLists(cs)
# pl.scatter(xc, yc, linewidths=0.5, color='black')

pl.show()
Example #50
0
def _draw_triangle(p1, p2, p3, **kwargs):
    tmp = n.vstack((p1,p2,p3))
    x,y = [x[0] for x in zip(tmp.transpose())]
    p.fill(x,y, **kwargs)
def radial_velocity():

    # set the masses
    M_star1 = M_sun  # star 1's mass
    M_star2 = 0.2 * M_sun  # planet's mass (exaggerated)

    # set the semi-major axis of the star 2 (and derive that of star 1)
    # M_star2 a_star2 = -M_star1 a_star1 (center of mass)
    a_star2 = 0.5 * AU
    a_star1 = (M_star2 / M_star1) * a_star2

    # set the eccentricity
    ecc = 0.0

    # set the angle to rotate the semi-major axis wrt the observer
    theta = 0.0

    # set the incliination wrt the observer.
    inc = 88.75  # degrees

    # create the solar system container
    ss = solarsystem(M_star1=M_star1, M_star2=M_star2)

    # set the radii and temperatures -- dimensionless -- we are going
    # to exaggerate their scale
    R1 = 20
    R2 = 2

    rad_scal = 0.01 * AU

    # set the temperatures
    T1 = 5000  # K
    T2 = 1000  # K

    # set the initial position of the planet -- perihelion

    # we are going to put the center of mass at the origin and star 2
    # initially on the +x axis and the star 1 initially on the -x axis
    x_star1_init = -a_star1 * (1.0 - ecc) * math.cos(theta)
    y_star1_init = -a_star1 * (1.0 - ecc) * math.sin(theta)

    x_star2_init = a_star2 * (1.0 - ecc) * math.cos(theta)
    y_star2_init = a_star2 * (1.0 - ecc) * math.sin(theta)

    # Kepler's laws should tell us the orbital period
    # P^2 = 4 pi^2 (a_star1 + a_star2)^3 / (G (M_star1 + M_star2))
    period = math.sqrt(4 * math.pi**2 * (a_star1 + a_star2)**3 /
                       (G * (M_star1 + M_star2)))

    print "period = ", period / year

    # compute the velocities.

    # first compute the velocity of the reduced mass at perihelion
    # (C&O Eq. 2.33)
    v_mu = math.sqrt((G * (M_star1 + M_star2) / (a_star1 + a_star2)) *
                     (1.0 + ecc) / (1.0 - ecc))

    # then v_star2 = (mu/m_star2)*v_mu
    vx_star2_init = -(M_star1 / (M_star1 + M_star2)) * v_mu * math.sin(theta)
    vy_star2_init = (M_star1 / (M_star1 + M_star2)) * v_mu * math.cos(theta)

    # then v_star1 = (mu/m_star1)*v_mu
    vx_star1_init = (M_star2 / (M_star1 + M_star2)) * v_mu * math.sin(theta)
    vy_star1_init = -(M_star2 / (M_star1 + M_star2)) * v_mu * math.cos(theta)

    # set the timestep in terms of the orbital period
    dt = period / 360.0
    tmax = period  # maximum integration time

    integrate_system(ss, x_star1_init, y_star1_init, vx_star1_init,
                     vy_star1_init, x_star2_init, y_star2_init, vx_star2_init,
                     vy_star2_init, dt, tmax)

    # apply the projection to account for the inclination wrt the
    # observer
    ss.y_star1[0:ss.npts] = ss.y_star1[0:ss.npts] * math.cos(inc * deg_to_rad)
    ss.y_star2[0:ss.npts] = ss.y_star2[0:ss.npts] * math.cos(inc * deg_to_rad)

    # we will keep one star fixed and draw the relative `orbit' of the
    # other
    x_rel = ss.x_star1 - ss.x_star2
    y_rel = ss.y_star1 - ss.y_star2

    # cut angle -- we don't want to plot the orbit where the stationary
    # star is (origin), so specify the angle wrt the +y axis where we
    # don't plot
    cut_angle = 20 * deg_to_rad

    frac = cut_angle / (2.0 * math.pi)

    # star 2 starts on the -x axis.  3/4 through the orbit, it will
    # be behind the star 1.  Compute the range of steps to skip plotting
    cut_index1 = 0.75 * ss.npts - frac * ss.npts
    cut_index2 = 0.75 * ss.npts + frac * ss.npts

    print cut_index1, cut_index2, ss.npts

    # light curve

    # first compute the fluxes -- since we are going to normalize,
    # don't worry about the pi and sigma (Stefan-Boltzmann constant)

    # here we are assuming that R2 < R1
    R1 = float(R1)
    R2 = float(R2)

    f1 = float(R1**2 * T1**4)
    f2 = float(R2**2 * T2**4)

    f_normal = f1 + f2
    f_star2_transit = (R1**2 - R2**2) * T1**4 + R2**2 * T2**4
    f_star2_blocked = f1

    # relative fluxes -- normalized to normal
    f_star2_transit = f_star2_transit / f_normal
    f_star2_blocked = f_star2_blocked / f_normal

    print "f_star2_transit = ", f_star2_transit
    print "f_star2_blocked = ", f_star2_blocked

    # determine the times of the eclipses / transits
    # t_a = star 2 begins to pass in front of star 1
    # t_b = star 2 fully in front of star 1
    # t_c = star 2 begins to finish its transit of star 1
    # t_d = star 2 fully finished with transit
    # t_e = star 2 begins to go behind star 1
    # t_f = star 2 fully behind star 1
    # t_g = star 2 begins to emerge from behind star 1
    # t_h = star 2 fully emerged from behind star 1
    t_a = t_b = t_c = t_d = t_e = t_f = t_g = t_h = -1.0

    n = 0
    while (n < ss.npts):

        if (y_rel[n] <= 0):

            # star 2 in front of star 1
            if (x_rel[n] + R2 * rad_scal > -R1 * rad_scal and t_a == -1):
                t_a = ss.t[n]

            if (x_rel[n] - R2 * rad_scal >= -R1 * rad_scal and t_b == -1):
                t_b = ss.t[n]

            if (x_rel[n] + R2 * rad_scal > R1 * rad_scal and t_c == -1):
                t_c = ss.t[n]

            if (x_rel[n] - R2 * rad_scal >= R1 * rad_scal and t_d == -1):
                t_d = ss.t[n]

        else:

            # star 2 behind star 1
            if (x_rel[n] - R2 * rad_scal < R1 * rad_scal and t_e == -1):
                t_e = ss.t[n]

            if (x_rel[n] + R2 * rad_scal <= R1 * rad_scal and t_f == -1):
                t_f = ss.t[n]

            if (x_rel[n] - R2 * rad_scal < -R1 * rad_scal and t_g == -1):
                t_g = ss.t[n]

            if (x_rel[n] + R2 * rad_scal <= -R1 * rad_scal and t_h == -1):
                t_h = ss.t[n]

        n += 1

    # make an array of the flux vs. time -- this is the light curve
    f_system = numpy.zeros(ss.npts, numpy.float64)

    n = 0
    while (n < ss.npts):

        f_system[n] = 1.0

        # star 2 passing in front of star 1

        if (ss.t[n] >= t_a and ss.t[n] < t_b):
            # linearly interpolate between f = 1 at t = t_a and
            # f = f_star2_transit at t = t_b
            slope = (f_star2_transit - 1.0) / (t_b - t_a)
            f_system[n] = slope * (ss.t[n] - t_b) + f_star2_transit

        elif (ss.t[n] >= t_b and ss.t[n] < t_c):
            f_system[n] = f_star2_transit

        elif (ss.t[n] >= t_c and ss.t[n] < t_d):
            # linearly interpolate between f = f_star2_transit at
            # t = t_c and f = 1 at t = t_d
            slope = (1.0 - f_star2_transit) / (t_d - t_c)
            f_system[n] = slope * (ss.t[n] - t_d) + 1.0

        # star 2 passing behind star 1

        elif (ss.t[n] >= t_e and ss.t[n] < t_f):
            # linearly interpolate between f = 1 at t = t_e and
            # f = f_star2_blocked at t = t_f
            slope = (f_star2_blocked - 1.0) / (t_f - t_e)
            f_system[n] = slope * (ss.t[n] - t_f) + f_star2_blocked

        elif (ss.t[n] >= t_f and ss.t[n] < t_g):
            f_system[n] = f_star2_blocked

        elif (ss.t[n] >= t_g and ss.t[n] < t_h):
            # linearly interpolate between f = f_star2_blocked
            # at t = t_g and f = 1 at t = t_h
            slope = (1.0 - f_star2_blocked) / (t_h - t_g)
            f_system[n] = slope * (ss.t[n] - t_h) + 1.0

        n += 1

    # ================================================================
    # plotting
    # ================================================================

    iframe = 0

    n = 0
    while (n < ss.npts):

        pylab.clf()

        pylab.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.9)

        pylab.subplot(211)

        a = pylab.gca()
        a.set_aspect("equal", "datalim")
        pylab.axis("off")

        if (y_rel[n] < 0.0):
            # star 2 is in front of star 1

            # plot star 1's orbit position -- set to be the origin
            xc1, yc1 = circle(0, 0, R1 * rad_scal)
            pylab.fill(xc1, yc1, 'r', ec="none")

            # plot star 2's relative orbit and position
            xc2, yc2 = circle(x_rel[n], y_rel[n], R2 * rad_scal)
            pylab.fill(xc2, yc2, 'b', ec="none")

        else:
            # star 1 is in front of star 2

            # plot star 2's relative orbit and position
            xc2, yc2 = circle(x_rel[n], y_rel[n], R2 * rad_scal)
            pylab.fill(xc2, yc2, 'b', ec="none")

            # plot star 1's orbit position -- set to be the origin
            xc1, yc1 = circle(0, 0, R1 * rad_scal)
            pylab.fill(xc1, yc1, 'r', ec="none")

        # plot the orbit -- in two segment
        pylab.plot(x_rel[0:cut_index1],
                   y_rel[0:cut_index1],
                   color="0.75",
                   linestyle="--",
                   alpha=0.5)
        pylab.plot(x_rel[cut_index2:ss.npts],
                   y_rel[cut_index2:ss.npts],
                   color="0.75",
                   linestyle="--",
                   alpha=0.5)

        #pylab.text(-1.5*a_star2, 1.1*a_star2, "star 1: T = %5.0f K" % (T1),
        #            color="r", fontsize=10)
        #pylab.text(-1.5*a_star2, 0.95*a_star2, "star 2: T = %5.0f K" % (T2),
        #            color="b", fontsize=10)
        #pylab.text(-1.5*a_star2, 0.8*a_star2,
        #            "R (star 1) / R (star 2) = %4.1f" % (R1/R2),
        #            color="k", fontsize=10)

        pylab.axis(
            [-1.5 * a_star2, 1.5 * a_star2, -1.25 * a_star2, 1.25 * a_star2])

        pylab.subplot(212)

        pylab.plot(ss.t[0:ss.npts] / tmax, f_system, "k")
        pylab.scatter([ss.t[n] / tmax], [f_system[n]], color="k")

        pylab.xlim(0.0, 1.0)
        pylab.ylim(0.9, 1.1)

        pylab.xlabel("t/P")
        pylab.ylabel("relative flux")

        f = pylab.gcf()
        f.set_size_inches(5.0, 6.5)

        outfile = "planet_transit_%04d.png" % iframe
        pylab.savefig(outfile)

        iframe += 1
        n += 1
Example #52
0
plt.ylabel('Drawdown [ft]', fontsize=12)
Legend2 = ['Drawdown at '+ObservationWell,]
plt.legend(Legend2, loc=0) # 4 is LR, 0 is best

# # Axis labels
# majorLocator   = plt.MultipleLocator(5)
# majorFormatter = FormatStrFormatter('%d')
# #minorLocator   = MultipleLocator(rin/40)

# ax2.xaxis.set_major_locator(majorLocator)
# ax2.xaxis.set_major_formatter(majorFormatter)

#for the minor ticks, use no labels; default NullFormatter
#ax.xaxis.set_minor_locator(minorLocator)

'''
For analyzing effects on nearby wells

# Well screen info
top1 = 43
top2 = 58
top3 = 78

# Fill area to represent well screens
p.fill([0,r[len(r)-1],r[len(r)-1],0], [top1+10,top1+10,top1,top1],
       'b', alpha = 0.2, edgecolor='k')
p.fill([0,r[len(r)-1],r[len(r)-1],0], [top2+10,top2+10,top2,top2],
       'b', alpha = 0.2, edgecolor='k')
p.fill([0,r[len(r)-1],r[len(r)-1],0], [top3+10,top3+10,top3,top3],
       'b', alpha = 0.2, edgecolor='k')
# Project non interference drawdown
Example #53
0
    import pylab
except ImportError:
    pass
else:
    pylab.figure(1, facecolor='w')
    pylab.plot(risks, returns)
    pylab.xlabel('standard deviation')
    pylab.ylabel('expected return')
    pylab.axis([0, 0.2, 0, 0.15])
    pylab.title('Risk-return trade-off curve (fig 4.12)')
    pylab.yticks([0.00, 0.05, 0.10, 0.15])

    pylab.figure(2, facecolor='w')
    c1 = [x[0] for x in xs]
    c2 = [x[0] + x[1] for x in xs]
    c3 = [x[0] + x[1] + x[2] for x in xs]
    c4 = [x[0] + x[1] + x[2] + x[3] for x in xs]
    pylab.fill(risks + [.20], c1 + [0.0], facecolor='#F0F0F0')
    pylab.fill(risks[-1::-1] + risks, c2[-1::-1] + c1, facecolor='#D0D0D0')
    pylab.fill(risks[-1::-1] + risks, c3[-1::-1] + c2, facecolor='#F0F0F0')
    pylab.fill(risks[-1::-1] + risks, c4[-1::-1] + c3, facecolor='#D0D0D0')
    pylab.axis([0.0, 0.2, 0.0, 1.0])
    pylab.xlabel('standard deviation')
    pylab.ylabel('allocation')
    pylab.text(.15, .5, 'x1')
    pylab.text(.10, .7, 'x2')
    pylab.text(.05, .7, 'x3')
    pylab.text(.01, .7, 'x4')
    pylab.title('Optimal allocations (fig 4.12)')
    pylab.show()
def simplegrid():

    #-------------------------------------------------------------------------
    # prolongation
    #-------------------------------------------------------------------------

    # grid info
    xmin = 0.0
    xmax = 1.0

    ymin = 0.0
    ymax = 1.0

    nzones = 3
    ng = 0

    dx = (xmax - xmin) / float(nzones)
    dy = (ymax - ymin) / float(nzones)

    xl = (numpy.arange(2 * ng + nzones) - ng) * dx
    xr = (numpy.arange(2 * ng + nzones) + 1 - ng) * dx

    xc = 0.5 * (xl + xr)

    yl = (numpy.arange(2 * ng + nzones) - ng) * dy
    yr = (numpy.arange(2 * ng + nzones) + 1 - ng) * dy

    yc = 0.5 * (yl + yr)

    #------------------------------------------------------------------------
    # plot a domain without ghostcells

    # x lines
    n = 0
    while (n < nzones):
        pylab.plot([xmin - 0.25 * dx, xmax + 0.25 * dx], [yl[n], yl[n]],
                   color="k",
                   lw=2)
        n += 1

    pylab.plot([xmin - 0.25 * dx, xmax + 0.25 * dx],
               [yr[nzones - 1], yr[nzones - 1]],
               color="k",
               lw=2)

    # y lines
    n = 0
    while (n < nzones):
        pylab.plot([xl[n], xl[n]], [ymin - 0.25 * dy, ymax + 0.25 * dy],
                   color="k",
                   lw=2)
        n += 1

    pylab.plot([xr[nzones - 1], xr[nzones - 1]],
               [ymin - 0.25 * dy, ymax + 0.25 * dy],
               color="k",
               lw=2)

    #------------------------------------------------------------------------
    # label
    pylab.text(xc[nzones / 2],
               yc[nzones / 2],
               r"$\phi_{i,j}^c$",
               fontsize="18",
               horizontalalignment='center',
               verticalalignment='center',
               zorder=100,
               color="b")

    pylab.text(xc[nzones / 2 + 1],
               yc[nzones / 2],
               r"$\phi_{i+1,j}^c$",
               fontsize="18",
               horizontalalignment='center',
               verticalalignment='center',
               color="b")

    pylab.text(xc[nzones / 2],
               yc[nzones / 2 + 1],
               r"$\phi_{i,j+1}^c$",
               fontsize="18",
               horizontalalignment='center',
               verticalalignment='center',
               color="b")

    pylab.text(xc[nzones / 2 - 1],
               yc[nzones / 2],
               r"$\phi_{i-1,j}^c$",
               fontsize="18",
               horizontalalignment='center',
               verticalalignment='center',
               color="b")

    pylab.text(xc[nzones / 2],
               yc[nzones / 2 - 1],
               r"$\phi_{i,j-1}^c$",
               fontsize="18",
               horizontalalignment='center',
               verticalalignment='center',
               color="b")

    # shading
    ii = nzones / 2
    jj = nzones / 2
    pylab.fill([xl[ii], xl[ii], xr[ii], xr[ii], xl[ii]],
               [yl[jj], yr[jj], yr[jj], yl[jj], yl[jj]],
               color="0.85",
               zorder=-1)

    ii = nzones / 2 + 1
    jj = nzones / 2
    pylab.fill([xl[ii], xl[ii], xr[ii], xr[ii], xl[ii]],
               [yl[jj], yr[jj], yr[jj], yl[jj], yl[jj]],
               color="0.85",
               zorder=-1)

    ii = nzones / 2 - 1
    jj = nzones / 2
    pylab.fill([xl[ii], xl[ii], xr[ii], xr[ii], xl[ii]],
               [yl[jj], yr[jj], yr[jj], yl[jj], yl[jj]],
               color="0.85",
               zorder=-1)

    ii = nzones / 2
    jj = nzones / 2 + 1
    pylab.fill([xl[ii], xl[ii], xr[ii], xr[ii], xl[ii]],
               [yl[jj], yr[jj], yr[jj], yl[jj], yl[jj]],
               color="0.85",
               zorder=-1)

    ii = nzones / 2
    jj = nzones / 2 - 1
    pylab.fill([xl[ii], xl[ii], xr[ii], xr[ii], xl[ii]],
               [yl[jj], yr[jj], yr[jj], yl[jj], yl[jj]],
               color="0.85",
               zorder=-1)

    # fine cells
    ii = nzones / 2
    jj = nzones / 2
    pylab.plot([xc[ii], xc[ii]], [yl[ii], yr[ii]], linestyle="--", color="0.3")
    pylab.plot([xl[ii], xr[ii]], [yc[ii], yc[ii]], linestyle="--", color="0.3")

    pylab.text(xc[ii] - dx / 4,
               yc[jj] - dy / 4,
               r"$\phi_{--}^{f}$",
               fontsize="18",
               horizontalalignment='center',
               verticalalignment='center',
               zorder=100,
               color="r")

    pylab.text(xc[ii] - dx / 4,
               yc[jj] + dy / 4,
               r"$\phi_{-+}^{f}$",
               fontsize="18",
               horizontalalignment='center',
               verticalalignment='center',
               zorder=100,
               color="r")

    pylab.text(xc[ii] + dx / 4,
               yc[jj] - dy / 4,
               r"$\phi_{+-}^{f}$",
               fontsize="18",
               horizontalalignment='center',
               verticalalignment='center',
               zorder=100,
               color="r")

    pylab.text(xc[ii] + dx / 4,
               yc[jj] + dy / 4,
               r"$\phi_{++}^{f}$",
               fontsize="18",
               horizontalalignment='center',
               verticalalignment='center',
               zorder=100,
               color="r")

    # grid labels
    pylab.text(xc[nzones / 2 - 1],
               yl[0] - 0.35 * dy,
               r"$i-1$",
               horizontalalignment='center',
               fontsize="16")

    pylab.text(xc[nzones / 2],
               yl[0] - 0.35 * dy,
               r"$i$",
               horizontalalignment='center',
               fontsize="16")

    pylab.text(xc[nzones / 2 + 1],
               yl[0] - 0.35 * dy,
               r"$i+1$",
               horizontalalignment='center',
               fontsize="16")

    pylab.text(xl[0] - 0.35 * dx,
               yc[nzones / 2 - 1],
               r"$j-1$",
               verticalalignment='center',
               fontsize="16")

    pylab.text(xl[0] - 0.35 * dx,
               yc[nzones / 2],
               r"$j$",
               verticalalignment='center',
               fontsize="16")

    pylab.text(xl[0] - 0.35 * dx,
               yc[nzones / 2 + 1],
               r"$j+1$",
               verticalalignment='center',
               fontsize="16")

    # axes
    pylab.xlim(xl[0] - 0.5 * dx, xr[2 * ng + nzones - 1] + 0.25 * dx)
    pylab.ylim(yl[0] - 0.5 * dy, yr[2 * ng + nzones - 1] + 0.25 * dy)
    pylab.axis("off")

    pylab.subplots_adjust(left=0.02, right=0.98, bottom=0.02, top=0.98)

    f = pylab.gcf()
    f.set_size_inches(8.0, 8.0)

    pylab.savefig("2dgrid-prolong.png")
    pylab.savefig("2dgrid-prolong.eps")
antpos = n.array(antpos) * a.const.len_ns / 100.
x,y,z = antpos[:,0], antpos[:,1], antpos[:,2]
x -= n.average(x)
y -= n.average(y)
p.plot(x,y, 'k.')
if False:
    im = a.img.Img(size=300, res=30)
    DIM = 300./30
    im.put((x,y,z), z)
    _z = a.img.recenter(im.uv, (DIM/2,DIM/2))
    print _z
    _z = n.ma.array(_z, mask=n.where(_z == 0, 1, 0))
    _x,_y = im.get_uv()
    _x = a.img.recenter(_x, (DIM/2,DIM/2))
    _y = a.img.recenter(_y, (DIM/2,DIM/2))
    p.contourf(_x,_y,_z,n.arange(-5,5,.5))
for ant,(xa,ya,za) in enumerate(zip(x,y,z)):
    hx,hy = r*za*n.cos(th)+xa, r*za*n.sin(th)+ya
    if za > 0: fmt = '#eeeeee'
    else: fmt = '#a0a0a0'
    p.fill(hx,hy, fmt)
    if not opts.nonumbers: p.text(xa,ya, str(ant))
p.grid()
#p.xlim(-100,100)
p.xlabel("East-West Antenna Position (m)")
p.ylabel("North-South Antenna Position (m)")
#p.ylim(-100,100)
#a = p.gca()
if not opts.aspect_neq: a.set_aspect('equal')
p.show()
Example #56
0
import pylab,numpy as np
from matplotlib.patches import FancyArrowPatch

fig=pylab.figure(figsize=(8,4))

pylab.fill(np.r_[0,5,5,0,0],np.r_[-1,-1,0,0,-1],'b',alpha=0.1)
pylab.plot(np.r_[0,5],np.r_[1,1],'k')
pylab.plot(np.r_[0,5],np.r_[0,0],'k')
pylab.plot(np.r_[0,5],np.r_[-1,-1],'k')

pylab.plot(np.r_[3,3],np.r_[0,1],'k--')

pylab.plot(3,0.5,'ko')
## pylab.plot(3,-0.5,'ko')
pylab.text(3.05,0.5,'$T_{a,x}$',ha='left',va='center')
## pylab.text(3.05,-0.5,'$T_{sat,r}$',ha='left',va='center')

pylab.plot(0,0.5,'ko')
pylab.plot(0,-0.5,'ko')
pylab.text(0.05,0.5,'$T_{a,i}$',ha='left',va='center')
pylab.text(0.05,-0.5,'$T_{sat,r}$',ha='left',va='center')

pylab.plot(5,0.5,'ko')
pylab.plot(5,-0.5,'ko')
pylab.text(5.05,0.5,'$T_{a,o}$',ha='left',va='center')
pylab.text(5.05,-0.5,'$T_{sat,r}$',ha='left',va='center')

pylab.plot(5,0.5,'ko')
pylab.plot(5,-0.5,'ko')
pylab.text(5.05,0.5,'$T_{a,o}$',ha='left',va='center')
pylab.text(5.05,-0.5,'$T_{sat,r}$',ha='left',va='center')
Example #57
0
    G[25, [16, 21]] = 1.0, -gamma

    # solve and return W, H, x, y, w, h 
    sol = solvers.cpl(c, F, G, h)
    return  sol['x'][0], sol['x'][1], sol['x'][2:7], sol['x'][7:12], \
        sol['x'][12:17], sol['x'][17:] 

solvers.options['show_progress'] = False

pylab.figure(facecolor='w')

pylab.subplot(221)
Amin = matrix([100., 100., 100., 100., 100.])
W, H, x, y, w, h =  floorplan(Amin)
for k in xrange(5):
    pylab.fill([x[k], x[k], x[k]+w[k], x[k]+w[k]], 
               [y[k], y[k]+h[k], y[k]+h[k], y[k]], facecolor = '#D0D0D0')
    pylab.text(x[k]+.5*w[k], y[k]+.5*h[k], "%d" %(k+1))
pylab.axis([-1.0, 26, -1.0, 26])
pylab.xticks([])
pylab.yticks([])

pylab.subplot(222)
Amin = matrix([20., 50., 80., 150., 200.])
W, H, x, y, w, h =  floorplan(Amin)
for k in xrange(5):
    pylab.fill([x[k], x[k], x[k]+w[k], x[k]+w[k]], 
               [y[k], y[k]+h[k], y[k]+h[k], y[k]], facecolor = '#D0D0D0')
    pylab.text(x[k]+.5*w[k], y[k]+.5*h[k], "%d" %(k+1))
pylab.axis([-1.0, 26, -1.0, 26])
pylab.xticks([])
pylab.yticks([])
Example #58
0
    'Alaska': 0.42
}
print shp_info
# choose a color for each state based on population density.
colors = {}
statenames = []
cmap = p.cm.hot  # use 'hot' colormap
vmin = 0
vmax = 450  # set range.
print m.states_info[0].keys()
for shapedict in m.states_info:
    statename = shapedict['NAME']
    if statename != 'District of Columbia':  # skip DC, it's not a state!
        pop = popdensity[statename]
        # calling colormap with value between 0 and 1 returns
        # rgba value.  Invert color range (hot colors are high
        # population), take sqrt root to spread out colors more.
        colors[statename] = cmap(1. - p.sqrt((pop - vmin) / (vmax - vmin)))[:3]
    statenames.append(statename)
# cycle through state names, color each one.
for nshape, seg in enumerate(m.states):
    xx, yy = zip(*seg)
    if statenames[nshape] != 'District of Columbia':  # skip DC
        color = rgb2hex(colors[statenames[nshape]])
        p.fill(xx, yy, color, edgecolor=color)
# draw meridians and parallels.
m.drawparallels(nx.arange(25, 65, 20), labels=[1, 0, 0, 0])
m.drawmeridians(nx.arange(-120, -40, 20), labels=[0, 0, 0, 1])
p.title('Filling State Polygons by Population Density')
p.show()
Example #59
0
def fill_polygon(g, o):
	a = asarray(g.exterior)
	pylab.fill(a[:, 0], a[:, 1], o, alpha=0.5)
#!/usr/bin/env python
import numpy as np
import pylab as plt

t = np.arange(0.0, 1.01, 0.01)
s = np.sin(2 * np.pi * t)

plt.subplot(2, 1, 1)
plt.plot(t,
         s * np.exp(-5 * t),
         'b',
         label=r'$sin (2\pi t) e^{-5 t}$',
         linewidth=4.)
plt.fill(t, s * np.exp(-5 * t), 'r')
plt.xlabel('time')
plt.ylabel('position')
plt.legend()
plt.grid(True)

plt.subplot(2, 1, 2)
plt.plot(t, np.sin(2. * np.pi * t), 'b', label=r'$sin (2\pi t)$', linewidth=4.)
plt.plot(t, np.cos(2. * np.pi * t), 'b', label=r'$cos (2\pi t)$', linewidth=4.)
plt.fill_between(t,
                 np.cos(2. * np.pi * t),
                 np.sin(2. * np.pi * t),
                 color='green')
plt.xlabel('time')
plt.legend()
plt.grid(True)

plt.show()