Пример #1
0
def _hinton(W, error=None, vmax=None, square=True):
    """
    Draws a Hinton diagram for visualizing a weight matrix. 

    Temporarily disables matplotlib interactive mode if it is on, 
    otherwise this takes forever.

    Originally copied from
    http://wiki.scipy.org/Cookbook/Matplotlib/HintonDiagrams
    """
    reenable = False
    if plt.isinteractive():
        plt.ioff()
        reenable = True
        
    #P.clf()
    W = misc.atleast_nd(W, 2)
    (height, width) = W.shape
    if not vmax:
        #vmax = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2))
        if error is not None:
            vmax = np.max(np.abs(W) + error)
        else:
            vmax = np.max(np.abs(W))

    plt.fill(0.5+np.array([0,width,width,0]),
             0.5+np.array([0,0,height,height]),
             'gray')
    plt.axis('off')
    if square:
        plt.axis('equal')
    plt.gca().invert_yaxis()
    for x in range(width):
        for y in range(height):
            _x = x+1
            _y = y+1
            w = W[y,x]
            _w = np.abs(w)
            if w > 0:
                _c = 'white'
            else:
                _c = 'black'
            if error is not None:
                e = error[y,x]
                if e < 0:
                    print(e, _w, vmax)
                    raise Exception("BUG? Negative error")
                if _w + e > vmax:
                    print(e, _w, vmax)
                    raise Exception("BUG? Value+error greater than max")
                _rectangle(_x,
                           _y, 
                           min(1, np.sqrt((_w+e)/vmax)),
                           min(1, np.sqrt((_w+e)/vmax)),
                           edgecolor=_c,
                           fill=False)
            _blob(_x, _y, min(1, _w/vmax), _c)
                
    if reenable:
        plt.ion()
Пример #2
0
def plot_Nhden(elem,N,hcol,hden,bounds=False):
    for i in to_plot[elem]:
        plt.clf()
        x = np.array(hden,dtype=np.float)
        y = np.array(N[i])
        #x,y,hcol = trim(x,y,hcol)
        y = hcol[0] - y
        xlims=[0.75*np.amin(x), 1.25*np.amax(x)]
        ylims=[0.75*np.amin(y), 1.25*np.amax(y)]
        try:
            if bounds: 
                l = minNHI - observed[elem][i]["column"][2] 
                if observed[elem][i]["column"][0]==-30.:
                    u=maxNHI
                else:
                    u = maxNHI - observed[elem][i]["column"][0]
                plt.fill([-30.,30., 30., -30.], [l,l,u,u], '0.50', alpha=0.2, edgecolor='b')

                #plt.fill_between(np.arange(xlims[0],xlims[1]),lower,upper,color='0.50')
        except KeyError:
            pass
        plt.plot(x, y, color_map[i],label=ion_state(i,elem))
        plt.ylabel(r"log $N_{HI}/N_{%s}$"%(str(elem)+str(roman[i])))
        plt.xlabel("log $n_{H}$")
        plt.minorticks_on()

        makedir('hden')

        f=os.path.join(paths["plot_path"],"hden", elem+roman[i]+"N_Nhden.png")

        plt.xlim([-3.,0.])
        #plt.ylim(ylims)
        plt.savefig(f)
        plt.show()
        plt.close()
Пример #3
0
def hinton(W, maxweight=None, fig=None):
    """
    Draws a Hinton diagram for visualizing a weight matrix. 
    Temporarily disables matplotlib interactive mode if it is on, 
    otherwise this takes forever.
    """
    if fig is None:
        fig = plt.gcf()
    reenable = False
    
    height, width = W.shape
    if not maxweight:
        maxweight = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2))
    ax = fig.add_subplot(111)    
    plt.fill(np.array([0, width, width, 0]), 
             np.array([0, 0, height, height]),
             'gray')
    
    ax.axis('off')
    ax.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),
                      'green')
            elif w < 0:
                _blob(_x - 0.5,
                      height - _y + 0.5, 
                      min(1, -w/maxweight), 
                      'red')
Пример #4
0
def standard_process():
    """
    standard process from scikit learn
    """
    X = np.atleast_2d([1., 3., 5., 6., 7., 8.]).T
    y = f(X).ravel()
    x = np.atleast_2d(np.linspace(0, 10, 1000)).T
    gp = gaussian_process.GaussianProcess(theta0=1e-2, thetaL=1e-4, thetaU=1e-1)
    gp.fit(X, y)
    y_pred, MSE = gp.predict(x, eval_MSE=True)
    sigma = np.sqrt(MSE)

    # Plot the function, the prediction and the 95% confidence interval based on
    # the MSE
    fig = plt.figure()
    plt.plot(x, f(x), 'r:', label=u'$f(x) = x\,\sin(x)$')
    plt.plot(X, y, 'r.', markersize=10, label=u'Observations')
    plt.plot(x, y_pred, 'b-', label=u'Prediction')
    plt.fill(np.concatenate([x, x[::-1]]),
            np.concatenate([y_pred - 1.9600 * sigma,
                           (y_pred + 1.9600 * sigma)[::-1]]),
            alpha=.5, fc='b', ec='None', label='95% confidence interval')
    plt.xlabel('$x$')
    plt.ylabel('$f(x)$')
    plt.ylim(-10, 20)
    plt.legend(loc='upper left')
    plt.show()
Пример #5
0
def plot_triangle(x, y, color=None, draw_lines=True, fill=False):
    """plot an rgb triangle in xy

    Args:
        x,y (numpy.array): [r, g, b] coords

    kwargs:
        color (str): if none, 1st point--> red, 2nd --> green, 3rd -> blue

        drawLines (bool): draw outline

        fill (bool): fill triangle

    """
    if fill:
        plt.fill(x, y, color='grey', alpha='0.5')
    if draw_lines:
        indexVal = np.hstack([np.arange(x.size), 0])
        plt.plot(x[indexVal], y[indexVal], '-k')

    if color:
        plt.plot(x[0], y[0], 'o', x[1], y[1], 'o', x[2], y[2], 'o',
                 color=color)
    else:
        plt.plot(x[0], y[0], 'or', x[1], y[1], 'og', x[2], y[2], 'ob')
Пример #6
0
def plot_2_lines(y_pred,y_reco,name0,chain0,path0='/home/stanford/rbaltman/users/bchen45/data/MCL_data/ig_specific/variable_region_plots/'):
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib
    import subprocess
    import os
    #y_axis scaling
    ratio0 = 1.3
    #main
    matplotlib.use('Agg')
    #example name0 = MCL001_H_chain
    if not os.path.isdir(path0+chain0):
        cmd_line = 'mkdir '+path0+chain0
        cmd0 = subprocess.Popen(cmd_line,shell=True)      
        cmd0.wait()
    len0 = len(y_pred) #len y1 = y2
    x = np.linspace(0, len0+1, len0+2)
    #print(x)
    y_pred = np.array([0]+y_pred+[0])
    #print(y_pred)
    y_reco = np.array([0]+y_reco+[0])
    max0 = ratio0*max(max(y_pred),max(y_reco))
    #print(y_reco)
    ax = plt.gca()
    alpha0 = 0.3
    pred0, = plt.fill(x,y_pred,'b',alpha=alpha0,label='MARIA Predicted')
    reco0, = plt.fill(x,y_reco,'r',alpha=alpha0,label='MHCII Peptide Recovered')
    plt.legend(handles=[pred0,reco0,])
    #plt.fill(x,y_pred,'b*',alphax,y_reco,'r*',alpha=0.2)
    ax.set_xlabel(name0+' Amino Acid Sequence')
    ax.set_ylabel('Peptides recovered/Predicted scores')
    ax.set_title(name0+' Peptide Recovered vs. MARIA Prediction Scores')
    ax.set_ylim([0,max0])
    plt.savefig(path0+chain0+'/'+name0+'_pred_vs_recovered.png', bbox_inches='tight')
    plt.close()
def plot_data_and_line(w1,w2):
    w1,w2 = float(w1),float(w2)
    if w2 != 0 :
        y1,y2 = (-w1*(xl1))/w2, (-w1*(xl2))/w2
        vx1,vy1 = [xl1,xl2,xl2,xl1,xl1], [y1,y2,yl2,yl2,y1]
        vx2,vy2 = [xl1,xl2,xl2,xl1,xl1], [y1,y2,yl1,yl1,y1]
    elif w1 != 0:
        vx1,vy1 = [xl2,0,0,xl2,xl2], [yl1,yl1,yl2,yl2,yl1]
        vx2,vy2 = [xl1,0,0,xl1,xl1], [yl1,yl1,yl2,yl2,yl1]
    else:
        print "ERROR, Invalid w1 and w2."
        return;
    if  w2 > 0 or ( w2 == 0 and w1 > 0):
        c1,c2 = 'b','r'
    else:
        c1,c2 = 'r','b'
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.scatter(X1[Y > 0], X2[Y > 0], s = 80, c = 'b', marker = "o")
    plt.scatter(X1[Y<= 0], X2[Y<= 0], s = 80, c = 'r', marker = "^")
    plt.fill(vx1, vy1, c1, alpha = 0.25)
    plt.fill(vx2, vy2, c2, alpha = 0.25)
    ax.set_title(("w1 = %s, w2 = %s")%( w1, w2))
    ax.set_xlim(xl1, xl2)
    ax.set_ylim(yl1, yl2)
    fig.set_size_inches(6, 6)
    plt.show()    
Пример #8
0
 def point_load():
     # point load shear
     x = np.linspace(0,L,100)
     y = np.ones(len(x))*P/2
     y[x>Ploc] = y[x>Ploc]-P
     x[0]=0
     x[-1]=0
     
     plt.subplot(3,1,2)
     plt.ylabel('Shear, V')
     plt.title('Shear Diagram')
     plt.fill(x, y, 'b', alpha=0.25)
     plt.grid(True)
     plt.xlim([-1, L+1])
     
     # point load bending
     x = np.linspace(-L/2,L/2,100)
     y = -(x**2)+(np.max(x**2))
     x = np.linspace(0,L,100)
     plt.subplot(3,1,3)
     plt.title('Bending Diagram')
     plt.ylabel('Moment, M')
     plt.fill(x, y, 'b', alpha=0.25)
     plt.grid(True)
     plt.xlim([-1, L+1])    
     
     # add point load
     plt.subplot(3,1,1)
     plt.annotate('P=%i'%P, ha = 'center', va = 'bottom',
                  xytext = (Ploc, 15), xy = (Ploc,7.5),
                 arrowprops = { 'facecolor' : 'black', 'shrink' : 0.05 })    
     plt.title('Free Body Diagram')
     plt.axis('off') # removes axis and labels       
Пример #9
0
 def dist_load():
     
             # add distributed load
     plt.subplot(3,1,1)
     for k in np.linspace(0,L,20):
         ax1.arrow(k, 11+L/10, 0, -3, head_width=L*0.01, head_length=L*0.1, fc='k', ec='k')
     plt.title('Free Body Diagram')
     plt.axis('off') # removes axis and labels
     #ax1.set_yticklabels('') 
     
     # dist load shear
     x = [0,0,L,L]
     y = [0,5,-5,0]
     plt.subplot(3,1,2)
     plt.ylabel('Shear, V')
     plt.title('Shear Diagram')
     plt.fill(x, y, 'b', alpha=0.25)
     plt.grid(True)
     plt.xlim([-1, L+1])
     
     # dist load bending
     x = np.linspace(-L/2,L/2,100)
     y = -(x**2)+(np.max(x**2))
     x = np.linspace(0,L,100)
     plt.subplot(3,1,3)
     plt.title('Bending Diagram')
     plt.ylabel('Moment, M')
     plt.fill(x, y, 'b', alpha=0.25)
     plt.grid(True)
     plt.xlim([-1, L+1])
Пример #10
0
def plot_interval_f(fun, x, pow2=0, num_points=101):
    """
    Plots the interval extension of a function `fun` over the interval `x`,
    which is divided into num=1, 2, 4, ..., 2**pow2 uniform subintervals.
    The original function is plotted at num_points points
    """
    num_intervals = [2 ** p for p in range(pow2 + 1)]

    # plt.figure()
    # plt.subplot(1, 1, 1)

    for num in num_intervals:
        fact_alfa = num * 1.0 / num_intervals[-1]  # for plotting

        subdivided_intervals = split_interval(x, num)
        total_range = range_interval_f(fun, subdivided_intervals)
        print "Total range (N={}) = {}".format(num, total_range)

        # Draw each subinterval and its range:
        for x1 in subdivided_intervals:
            low = float(x1.lo)
            high = float(x1.hi)
            Ffun = fun(x1)

            # draw a block of the correct size:
            xa1 = np.array([low, low, high, high])
            ya1 = np.array([float(Ffun.lo), float(Ffun.hi), float(Ffun.hi), float(Ffun.lo)])
            plt.fill(xa1, ya1, "b", alpha=fact_alfa)

    # plot the graph of the function:
    low = float(x.lo)
    high = float(x.hi)
    xx = np.linspace(low, high, num_points)
    yy = [fun(x) for x in xx]
    plt.plot(xx, yy, "red")
Пример #11
0
def wiggle (traces, skipt=1,scale=1.,lwidth=.1,offsets=None,redvel=0., manthifts=None, tshift=0.,sampr=1.,clip=10., dx=1., color='black',fill=True,line=True, ax=None):

  ns = traces.shape[1]
  ntr = traces.shape[0]
  t = np.arange(ns)*sampr
  timereduce = lambda offsets, redvel, shift: [float(offset) / redvel + shift for offset in offsets]

  if (offsets is not None):
    shifts = timereduce(offsets, redvel, tshift)
  elif (manthifts is not None):
    shifts = manthifts
  else:
    shifts = np.zeros((ntr,))

  for i in range(0, ntr, skipt):
    trace = traces[i].copy()
    trace[0] = 0
    trace[-1] = 0

    if ax == None:
      if (line):
        plt.plot(i*dx + clipsign(trace / scale, clip), t - shifts[i], color=color, linewidth=lwidth)
      if (fill):
        for j in range(ns):
          if (trace[j] < 0):
            trace[j] = 0
        plt.fill(i*dx + clipsign(trace / scale, clip), t - shifts[i], color=color, linewidth=0)
    else:
      if (line):
        ax.plot(i*dx + clipsign(trace / scale, clip), t - shifts[i], color=color, linewidth=lwidth)
      if (fill):
        for j in range(ns):
          if (trace[j] < 0):
            trace[j] = 0
        ax.fill(i*dx + clipsign(trace / scale, clip), t - shifts[i], color=color, linewidth=0)
Пример #12
0
def main():
    axes = lsst.afw.geom.ellipses.Axes(4, 3, 1)
    ellipse = lsst.afw.geom.ellipses.Ellipse(
        axes, lsst.geom.Point2D(0.25338, 0.76032))
    region = lsst.afw.geom.ellipses.PixelRegion(ellipse)
    for bbox in [ellipse.computeBBox(), lsst.geom.Box2D(region.getBBox())]:
        corners = bbox.getCorners()
        pyplot.fill([p.getX() for p in corners], [p.getY()
                                                  for p in corners], alpha=0.2)
    envelope = region.getBBox()
    envelope.grow(2)
    ellipse.plot(alpha=0.2)
    ellX = []
    ellY = []
    allX, allY = numpy.meshgrid(
        numpy.arange(envelope.getBeginX(), envelope.getEndX()),
        numpy.arange(envelope.getBeginY(), envelope.getEndY())
    )
    gt = ellipse.getGridTransform()
    mgt = gt.getMatrix()
    transX = mgt[0, 0] * allX + mgt[0, 1] * allY + mgt[0, 2]
    transY = mgt[1, 0] * allX + mgt[1, 1] * allY + mgt[1, 2]
    allR = (transX**2 + transY**2)**0.5
    pyplot.plot(ellX, ellY, 'ro', markeredgewidth=0, alpha=0.5)
    pyplot.plot(allX[allR < 1], allY[allR < 1], '+')
    pyplot.plot(allX[allR > 1], allY[allR > 1], 'x')
Пример #13
0
def hinton(W, max_weight=None):
    """ Draws a Hinton diagram for visualizing a weight matrix. 
    """
    if max_weight is None:
        max_weight = 2 ** np.ceil(np.log2(np.max(np.abs(W))))

    # Temporarily disable matplotlib interactive mode if it is on,
    # otherwise this takes forever.
    isinteractive = plt.isinteractive()
    if isinteractive:
        plt.ioff()

    height, width = W.shape
    plt.clf()
    plt.fill(np.array([0, width, width, 0]), np.array([0, 0, height, height]), "gray")

    plt.axis("off")
    plt.axis("equal")
    for (y, x), w in np.ndenumerate(W):
        if w != 0:
            color = "white" if w > 0 else "black"
            area = min(1, np.abs(w) / max_weight)
            _blob(x + 0.5, height - y - 0.5, area, color)

    if isinteractive:
        plt.ion()
Пример #14
0
    def plot_kde_overlap(self, terms, color1='#0067a2', color2='#e8a945', overlap_color='#dddddd', **kwargs):

        term1 = terms[0]
        term2 = terms[1]

        t1 = self.stem(term1)
        t2 = self.stem(term2)

        bc = self.score_braycurtis(t1, t2, **kwargs)

        kde1 = self.kde(t1, **kwargs)
        kde2 = self.kde(t2, **kwargs)
        plt.plot(kde1, color=color1, label=term1)
        plt.plot(kde2, color=color2, label=term2)

        overlap = np.minimum(kde1, kde2)
        plt.fill(overlap, color=overlap_color)
        plt.title(term1+', '+term2+' - '+str(round(bc, 4)))

        plt.xlabel('Word Offset')
        plt.ylabel('Number of Occurrences')
        plt.legend(loc='upper right')

        fig = plt.gcf()
        fig.set_size_inches(10, 4)
        fig.tight_layout()

        return plt
Пример #15
0
def radar_plot():
    """
    radar plot
    """
    # 生成测试数据
    labels = np.array(["A组", "B组", "C组", "D组", "E组", "F组"])
    data = np.array([68, 83, 90, 77, 89, 73])
    theta = np.linspace(0, 2*np.pi, len(data), endpoint=False)

    # 数据预处理
    data = np.concatenate((data, [data[0]]))
    theta = np.concatenate((theta, [theta[0]]))

    # 画图方式
    plt.subplot(111, polar=True)
    plt.title("雷达图", fontproperties=myfont)

    # 设置"theta grid"/"radar grid"
    plt.thetagrids(theta*(180/np.pi), labels=labels, fontproperties=myfont)
    plt.rgrids(np.arange(20, 100, 20), labels=np.arange(20, 100, 20), angle=0)
    plt.ylim(0, 100)

    # 画雷达图,并填充雷达图内部区域
    plt.plot(theta, data, "bo-", linewidth=2)
    plt.fill(theta, data, color="red", alpha=0.25)

    # 图形显示
    plt.show()
    return
Пример #16
0
def pretty_rho3(meanr, rho, sig, sqrtn):
    import matplotlib.patches as mp
    t1 = 0.5
    t2 = 300.
    y_sv = 1.1e-2**2
    y_y5 = 2.2e-3**2

    sv_req = plt.fill( [t1, t1, t2, t2], [0., y_sv, y_sv, 0.],
                        color = '#FFFF82')
    y5_req = plt.fill( [t1, t1, t2, t2], [0., y_y5, y_y5, 0.],
                        color = '#BAFFA4')
    plt.plot(meanr, rho, color='blue')
    plt.plot(meanr, -rho, color='blue', ls=':')
    plt.errorbar(meanr[rho>0], rho[rho>0], yerr=sig[rho>0]/sqrtn, color='blue', ls='')
    plt.errorbar(meanr[rho<0], -rho[rho<0], yerr=sig[rho<0]/sqrtn, color='blue', ls='')
    rho1_line = plt.errorbar(-meanr, rho, yerr=sig, color='blue')
    sv_req = mp.Patch(color='#FFFF82')
    y5_req = mp.Patch(color='#BAFFA4')
    plt.legend([rho1_line, sv_req, y5_req], 
               [r'$\rho_1(\theta)$', 'SV Requirements', 'Y5 Requirements'])
    plt.xlim( [t1,t2] )
    plt.ylim( [1.e-6, 3.e-4] )
    plt.xlabel(r'$\theta$ (arcmin)')
    plt.ylabel(r'$\rho_3$')
    plt.xscale('log')
    plt.yscale('log', nonposy='clip')
Пример #17
0
    def test_voronoi(self):
        # make up data points
        np.random.seed(1234)
        points = np.random.rand(15, 2)

        # compute Voronoi tesselation
        vor = Voronoi(points)

        # plot
        regions, vertices = self.voronoi_finite_polygons_2d(vor)
        print "--"
        print regions
        print "--"
        print vertices

        # colorize
        for region in regions:
            polygon = vertices[region]
            plt.fill(*zip(*polygon), alpha=0.4)

        plt.plot(points[:, 0], points[:, 1], "ko")
        plt.xlim(vor.min_bound[0] - 0.1, vor.max_bound[0] + 0.1)
        plt.ylim(vor.min_bound[1] - 0.1, vor.max_bound[1] + 0.1)

        plt.show()
Пример #18
0
def funk_graph_boot_naive_beta(beta, seuil ,n,estimateur,type_name, plot_save=False):
    # graph de convergence pour le beta 
    # beta : float, seuil : float, n : integer, plot_save : Boolean
    l=[]
    x_r = range(1,n)
    for esc in x_r:
        echantillon = funk_pareto(beta,esc,seuil,plot_boolean=False)
        l.append(funk_bootstrap_naive_beta(echantillon,seuil,esc,estimateur,rep=True))    

    # graphique
    y = np.repeat(beta,len(l))
    echa = [funk_sig_beta_emp(funk_pareto(beta,x,seuil),seuil) for x in range(len(l))]

    test1 = ([l[x] - 1.96*echa[x]*(1/np.sqrt(x)) for x in range(len(l))]) # il faudra mettre les var de la loie normale
    test2 = ([l[x] + 1.96*echa[x]*(1/np.sqrt(x)) for x in range(len(l))])
    plt.figure()
    plt.title(r'Estimation du $\beta$ par methode bootstrap naive par '+type_name+ 
              '\n'+r' $\beta$='+str(beta)+', seuil = '+str(seuil),fontsize=16)
    plt.plot(x_r, l, 'r', label=r' Estimation des $\theta_{(n,B)}$')
    plt.fill(np.concatenate([x_r, x_r[::-1]]),             np.concatenate([test1,test2[::-1]]),             alpha=.5, fc='b', ec='None', label='95% confidence interval')
    plt.xlabel('Taille de l\'echantillon')
    plt.legend(loc='upper left')
    if(plot_save==True):
        plt.savefig("plot\\conv_beta_boot"+type_name+"_n="+str(n)+".png",bbox_inches="tight")
    return([l,test1,test2])
Пример #19
0
def funk_theta_graph_conv(beta,seuil,a_i,n,perce,estimateur,typename,plot_save=False):
    # pour faire les courbes de convergences vers theta
    # beta: float, seuil:float, a_i : float, perce : float, 
    # estimateur : fonction, typename : string, plot_save: boolean
    l_test=[]
    l1=[]
    l2=[]
    l_r=[]
    thetta = (seuil/a_i)**beta
    for esc in range(1,n):
        echantillon = funk_pareto(beta,esc,seuil,plot_boolean=False)
        [test,test1,test2] = funk_IC_theta(echantillon,seuil,beta,a_i,perce)
        #l_r.append(funk_theta_moment(echantillon,seuil,a_i))
        l_r.append(funk_theta_mle(echantillon,seuil,a_i))
        l_test.append(test)
        l1.append(test1)
        l2.append(test2)
    plt.figure()
    plt.title(r'Aprroximation du $\theta$ avec methode empirique',fontsize=16)
    plt.plot(range(1,100),l_r,'r',label=r'$\theta$ estime')
    plt.fill(np.concatenate([range(1,100), range(1,100)[::-1]]),                     np.concatenate([[thetta - l_test[x] for x in range(len(l_r))],#l_r[x]
                                    [thetta + l_test[x] for x in range(len(l_r))][::-1]]), \
                    alpha=.5, fc='b', ec='None', label=str(perce*100)+'% confidence interval') 
    plt.xlabel('Taille de l\'echantillon')
    plt.legend(loc='lower right')
    if(plot_save==True):
        plt.savefig('plot\conv_thet_IC_'+typename+'.png',bbox_inches="tight")
    return([l_r,l1,l2,l_test])
Пример #20
0
def load_world():
	shpRecords = shpUtils.loadShapefile('world_borders/world_borders.shp')['features']
	colors = load_color_map()
	plt.figure(figsize=(16, 9))

	last = ''
	for i in range(0,len(shpRecords)):
		if shpRecords[i]['info']['CNTRY_NAME'] != last:
			print shpRecords[i]['info']['CNTRY_NAME']
			last = shpRecords[i]['info']['CNTRY_NAME']

		# x and y are empty lists to be populated with the coords of each geometry.
		x = []
		y = []
		#print shpRecords[i]
		for j in range(0,len(shpRecords[i]['shape']['parts'][0]['points'])):
			tempx = float(shpRecords[i]['shape']['parts'][0]['points'][j][0])
			tempy = float(shpRecords[i]['shape']['parts'][0]['points'][j][1])
			x.append(tempx)
			y.append(tempy) # Populate the lists  

		# Creates a polygon in matplotlib for each geometry in the shapefile
		if shpRecords[i]['info']['CNTRY_NAME'] in colors:
			if shpRecords[i]['info']['CNTRY_NAME'] == 'Congo' or shpRecords[i]['info']['CNTRY_NAME'] == 'Zaire':
				plt.fill(x,y, facecolor=colors['Democratic Republic of the Congo'])
			plt.fill(x,y, facecolor=colors[shpRecords[i]['info']['CNTRY_NAME']])

	plt.axis('equal')
	plt.savefig('world_calls.png', dpi=100, format='png')
	plt.show()
Пример #21
0
def plotting(DIR, z_name, opos):
    colours = ['#313695', '#4575b4', '#74add1',\
               '#abd9e9', '#fdae61', '#f46d43', '#d73027', '#a50026',\
               '#313695', '#4575b4', '#74add1',\
               '#abd9e9', '#fdae61', '#f46d43', '#d73027', '#a50026',\
               '#313695', '#4575b4', '#74add1',\
               '#abd9e9', '#fdae61', '#f46d43', '#d73027', '#a50026']


    xlo, xhi, ylo, yhi, zlo, zhi = coords(DIR, z_name)
    vor = Voronoi(opos)
    fig = voronoi_plot_2d(vor, show_vertices=False, point_size=0.1)

    # add colours
    for region in vor.regions:
        if not -1 in region:
            polygon = [vor.vertices[i] for i in region]
            plt.fill(*zip(*polygon), c=colours[2*len(region)+1])
            #plt.fill
    plt.xlim(0, xhi)
    plt.ylim(ylo, yhi)
    plt.xlabel('$x$ (\AA)')
    plt.ylabel('$y$ (\AA)')
    plt.savefig('PLOTS_C/{}/voronoi_2d_{}.pdf'.format(DIR,z_name),
                bbox_inches='tight')
    #plt.show()

    return 
Пример #22
0
def histogram_gdal_direct(bag_file, patch_name,verbose):
    # This is the one 
    'Plot the depth histogram.  Use the tif until gdal 1.7.0 comes out'

    patch = osgeo.gdal.Open(bag_file)
    band = patch.GetRasterBand(1)
    bandmin,bandmax = band.ComputeRasterMinMax()
    hist = band.GetDefaultHistogram()

    #print hist
    #print '----------------------------------------------------------------------'
    #print hist[3]
    hist_vals = hist[3][:-1]
    while hist_vals[-1] == 0:
        hist_vals.pop()

    xticks = ['%02.1f' % depth for depth in  np.arange(hist[0],hist[1],(hist[1]-hist[0])/5)]
    xticks.append('%.1f' % hist[1])
    if verbose:
        print (xticks)  # Why is the 0.0 tick not showing?
    plt.xticks([val * len(hist_vals)/5 for val in range(len(xticks))],xticks) # Yuck!
    plt.fill(range(len(hist_vals)),hist_vals)
    plt.grid(True)
    plt.savefig(patch_name+'-hist.png') #,dpi=50)
    with file(patch_name+'.hist','w') as o:
        o.write('\n'.join([str(v) for v in hist_vals]))
def hist_with_peak(x, bins=None, range=None, ax=None, orientation='vertical',
                   histtype=None, **kwargs):
    if ax is None:
        ax = plt.gca()
    hist, bin_edges = np.histogram(x, bins=bins, range=range)
    hist_n = hist * 1.0/hist.max()
    width = bin_edges[1] - bin_edges[0]
    x = np.ravel(zip(bin_edges[:-1], bin_edges[:-1]+width))
    y = np.ravel(zip(hist_n, hist_n))
    if histtype == 'step':
        if orientation == 'vertical':
            plt.plot(x, y, **kwargs)
        elif orientation == 'horizontal':
            plt.plot(y, x, **kwargs)
        else:
            raise ValueError
    elif histtype == 'stepfilled':
        if orientation == 'vertical':
            plt.fill(x, y, **kwargs)
        elif orientation == 'horizontal':
            plt.fill(y, x, **kwargs)
        else:
            raise ValueError
    else:
        raise ValueError
Пример #24
0
	def GPVisualize1D(self, locations, measurements, predict_range = (0, 1), num_samples = 1000):
		"""
		Visualize posterior in graphical form
		NOTE: very ineffecient since we are using the weight space view to vizualize this
		"""	

		# Grid points
		x = np.atleast_2d(np.linspace(predict_range[0], predict_range[1], num_samples, endpoint=False)).T

		# Compute predictions - very inefficient because we are using the weight space view
		predicted_mean = [0.0] * num_samples
		predicted_variance = [0.0] * num_samples
		for i in xrange(num_samples):
			predicted_mean[i] = self.GPMean(locations, measurements, x[i])[0]
			predicted_variance[i] = self.GPVariance2(locations, x[i])[0]

		# Plot posterior mean and variances
		pl.plot(x, self.GPRegressionTestEnvironment(x), 'r:', label=u'$f(x)$')
		pl.plot(locations, measurements, 'r.', markersize=10, label=u'Observations')
		pl.plot(x, predicted_mean, 'b-', label=u'Prediction')
		pl.fill(np.concatenate([x, x[::-1]]),
        np.concatenate([predicted_mean - 1.9600 * np.sqrt(predicted_variance),
                       (predicted_mean + 1.9600 * np.sqrt(predicted_variance))[::-1]]),
        				alpha=.5, fc='b', ec='None', label='95% confidence interval')
		pl.xlabel('$x$')
		pl.ylabel('$f(x)$')
		pl.legend(loc='upper left')

		pl.show()
Пример #25
0
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 plt.isinteractive():
        plt.ioff()
    plt.clf()
    height, width = W.shape
    if not maxWeight:
        maxWeight = 2**np.ceil(np.log(np.max(np.abs(W)))/np.log(2))

    plt.fill(np.array([0, width, width, 0]), np.array([0, 0, height, height]),
             'gray')
    plt.axis('off')
    plt.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:
        plt.ion()
    plt.show()
Пример #26
0
def convexview(linearcombination):
    # draw K
    plt.plot([1.0, 2.0, 20.0, 3.0, 1.0],[2.0, 4.0, 0.0, 1.0, 2.0],'b',lw=2.0)
    plt.fill([1.0, 2.0, 20.0, 3.0, 1.0],[2.0, 4.0, 0.0, 1.0, 2.0],
             facecolor='b', alpha=0.2, edgecolor='none')
    plt.text(3.5,1.2,r'$K$',fontsize=28,color='b')
    # draw axes
    plt.plot([0.5, 0.5],[-0.5, 4.5],'k',lw=1.0)
    plt.plot([0.0, 4.0],[0.5, 0.5],'k',lw=1.0)
    # plot u, v
    u = np.array([1.6,1.7])
    v = np.array([3.0,3.0])
    plt.plot(u[0],u[1],'.',markersize=14,color='k')
    plt.text(u[0]-0.3,u[1]-0.3,r'$u$',fontsize=24,color='k')
    plt.plot(v[0],v[1],'.',markersize=14,color='k')
    plt.text(v[0]+0.1,v[1]+0.1,r'$v$',fontsize=24,color='k')
    # show either interpretation
    eps = 0.6
    z = (1.0 - eps) * u + eps * v
    plt.plot(z[0],z[1],'.',markersize=14,color='k')
    if linearcombination:
        # lin-comb : (1 - eps) u + eps v
        plt.plot([u[0],v[0]], [u[1],v[1]],'k',lw=2.0)
        plt.text(z[0],z[1]-0.3,r'$(1-\varepsilon) u + \varepsilon v$',fontsize=24,color='k')
    else:
        # intoK : u + eps (v - u)
        ax = plt.axes()
        w = eps * (v - u)
        ax.arrow(u[0],u[1],w[0],w[1],
                 head_width=0.1, head_length=0.2, length_includes_head=True, fc='k', ec='k')
        plt.text(z[0],z[1]-0.3,r'$u + \varepsilon (v - u)$',fontsize=24,color='k')
    plt.axis([-1.0,4.0,0.0,5.0],'k',lw=2.0)
    plt.axis('off')
Пример #27
0
def main():
    x = linspace(0, 1, 200)
    y = sin(4 * pi * x) * exp(-5 * x)

    fill(x, y, 'r')
    grid(True)
    show()
Пример #28
0
def noiseless():
  X = np.atleast_2d([1.,3.,5.,6.,7.,8.,]).T
  # observations
  y = f(X).ravel() # reshape to 1-D
  # mesh the input space to cover all points to predict f(x) and the MSE
  x = np.atleast_2d(np.linspace(0,10,1000)).T # and flatten
  # instantiate gauss process
  gp = GaussianProcess(corr='cubic', theta0=1e-2, thetaL=1e-4,
                       thetaU=1e-1, random_start=100)
  # fit to data using maximum likelihood estimation of params
  gp.fit(X,y)
  # make predictions on meshed x-axis, also return MSE
  y_pred, MSE = gp.predict(x, eval_MSE=True)
  sigma = np.sqrt(MSE)
  
  # plot
  fig = plt.figure()
  plt.plot(x, f(x), 'r:', label=u'$f(x) = x\,\sin(x)$')
  plt.plot(X, y, 'r.', markersize=10, label=u'Observations')
  plt.plot(x, y_pred, 'b-', label=u'Prediction')
  # fill the space between the +/-MSE
  plt.fill(np.concatenate([x, x[::-1]]), # reverse order of x
           np.concatenate([y_pred - 1.9600 * sigma,
                          (y_pred + 1.9600 * sigma)[::-1]]),
           alpha=0.5, fc='b', ec='None', label='95% confidence interval')
           # shade, fill color, edge color
  plt.title('Noiseless case')
  plt.xlabel('$x$')
  plt.ylabel('$f(x)$')
  plt.ylim(-10, 20)
  plt.legend(loc='upper left')
  return
def __main__():
    '''test code'''
    # make up data points
    #np.random.seed(1234)
    points = np.random.rand(3, 2)

    # compute Voronoi tesselation
    vor = Voronoi(points)

    # plot
    regions, vertices = voronoi_finite_polygons_2d(vor,radius=100000)
    print("--")
    print(regions)
    print("--")
    print(vertices)

    # colorize
    for region in regions:
        polygon = vertices[region]
        plt.fill(*zip(*polygon), alpha=0.4)

    plt.plot(points[:,0], points[:,1], 'ko')
    plt.axis('equal')
    plt.xlim(vor.min_bound[0] - 0.1, vor.max_bound[0] + 0.1)
    plt.ylim(vor.min_bound[1] - 0.1, vor.max_bound[1] + 0.1)

    #plt.savefig('voro.png')
    plt.show()
Пример #30
0
	def display(self):
		length = self.length
		width = self.width
		base_x = self.x - .5*length
		base_y = self.y - .5*width
		xs = [base_x, base_x + length, base_x+length, base_x, base_x]
		ys = [base_y, base_y, base_y+width, base_y+width, base_y]
		plt.plot(xs, ys, 'k')
		if not self.flyable:
			plt.fill(xs, ys, 'r')
		for letter in self.exitnodelist:
			if letter == 'C':
				x = base_x + .5*length
				y = base_y +.5*width
			if letter == 'N':
				x = base_x + .5*length
				y = base_y + width
			if letter == 'S':
				x = base_x + .5*length
				y = base_y
			if letter == 'E':
				x = base_x + length
				y = base_y + .5*width
			if letter == 'W':
				x = base_x
				y = base_y + .5*width
			plt.plot([x, base_x+.5*length],[y, base_y +.5*width], 'g')
			plt.plot([x, base_x+.5*length],[y, base_y +.5*width], 'go')
Пример #31
0
# loop thru years
i = 0
for minmag in minmags:
    fig, ax = plt.subplots(1, figsize=(14, 8))

    width = 0.35

    # first plot filled box between 1986 & 1992
    if minmag == 5.0:
        fy = 7
    else:
        fy = 13
    fx1 = 1986 - width
    fx2 = 1992 + width
    plt.fill([fx1, fx2, fx2, fx1, fx1], [0, 0, fy, fy, 0],
             '0.8',
             edgecolor='0.8')
    plt.text(1989,
             8.1,
             '  Australian $\mathregular{M_L}$\n' + 'equations developed',
             rotation=90.,
             ha='center',
             va='bottom',
             fontsize=13)

    for pm in pltmean:
        i += 1

        plt_years = arange(1960, 2019)

        n_origML = []
Пример #32
0
D = elphmod.dispersion.sample(ph.D, q)

ph2 = copy.copy(ph)
elphmod.ph.q2r(ph2, D, q, nq, apply_asr_simple=True)

plt.figure()

for subplot, D in enumerate([ph.D, ph2.D]):
    plt.subplot(121 + subplot)

    w2, e, order = elphmod.dispersion.dispersion(D,
                                                 q_path,
                                                 vectors=True,
                                                 order=True,
                                                 broadcast=False)

    if comm.rank == 0:
        w = elphmod.ph.sgnsqrt(w2) * elphmod.misc.Ry * 1e3

        pol = elphmod.ph.polarization(e, q_path)

        for i in range(w.shape[1]):
            fatbands = elphmod.plot.compline(x, w[:, i], pol[:, i])

            for j, fatband in enumerate(fatbands):
                plt.fill(*fatband, color=colors[j], linewidth=0.0)

if comm.rank == 0:
    plt.show()
Пример #33
0
def process(file, name, trueFile):
    scores = []
    trueScores = []
    sampleRate = 3
    c = 0
    X_samps = []

    for line in file:
        c = c + sampleRate
        if float(line) not in scores:
            scores.append(float(line))
            X_samps.append(c)

    scores = (np.array(scores) * sampleRate).T

    for line in trueFile:
        trueScores.append(float(line))

    fig = plt.figure()
    #plt.plot(scores, markersize=10)

    #X = np.atleast_2d([x for x in range(0, len(scores))]).T

    scores2 = scores
    #scores2 = scores[::sampleRate]
    scores2 = np.array(scores2).reshape(len(scores2), 1)
    #scores2 = list(itertools.chain.from_iterable(itertools.repeat(q, x) for q in scores2))

    trueScores = np.array(trueScores).reshape(len(trueScores), 1)
    X = np.atleast_2d(np.linspace(0, len(scores2), len(scores))).T

    # for i in range(len(scores2), len(scores)):
    # scores2.append(scores2[len(scores2) - 1])

    #plt.plot(scores2, '--')
    x = np.atleast_2d([x for x in range(0, len(scores2))]).T
    X = np.atleast_2d(np.linspace(0, len(scores2), len(scores))).T

    #X = np.atleast_2d([x for x in range(0, len(scores2))]).T
    #X = np.atleast_2d(X).T

    x_val_true = findIn(int(round(max(trueScores)[0] * 0.7)),
                        trueScores) / sampleRate

    dy = 0.5 + 1.0 * np.random.random(np.array(scores2).shape)

    gp = GP()
    gp.create(x, scores2)
    y_pred, sigma = gp.predict(X)
    _X = np.atleast_2d([x for x in range(0, len(scores))]).T

    #x_val_gp = findIn(int(round(max(scores) * 0.7)), scores2)

    #plt.plot(scores, markersize=10)

    #plt.errorbar(X.ravel(), scores2, dy, fmt='r.', label=u'Observations')
    """
    resultScoreFile = open('true_document_rates/' + name + ".csv", "w")
    resultScoreFile.write("% of Docs Looked at" + "," + "% of Docs Returned" + "," + "Number of Documents" + "," + "Total Number of Documents" + "\t" + "Sample Rate:" + str(sampleRate) + "\n")
    percentages = [x for x in range(1, 100)]


    for per in percentages:
        ind = (len(X) / 100) * per
        score = ((scores[int(ind)] / scores[-1]) * 100)
        resultScoreFile.write(str(per) + "," + str(score) + "," + str(int(ind)) + "," + str(len(scores)) + "\n")


    resultScoreFile.close()
    
    """

    p0 = (0.3, 5)  # starting search coefs

    opt, pcov = curve_fit(model_func, X_samps, scores2, p0)
    #a, k = opt
    #y2 = model_func(x, a, k)

    # plt.plot(X_samps, y2, label='Fit. func: f(x) = %.3f e^{-%.3f x}' % (a,k))

    p1 = plt.plot(X_samps, scores2, c='C1', label=u'True')

    # y_pred = np.array([ '%.2f' % elem for elem in y_pred ])
    # y_pred_u = {}

    # for i, item in enumerate(y_pred):
    #  if item not in y_pred_u:
    #   y_pred_u[item] = i

    # _X = np.array(list(y_pred_u.values()))
    # y_pred = np.array(list(y_pred_u.keys()))

    p2 = plt.plot(X_samps, y_pred, c='b', label='Prediction GP')

    #p3 =plt.plot([x for x in range(0, len(trueScores[::sampleRate]))], trueScores[::sampleRate], c='C2', label=u'All Values')
    p3 = plt.plot([x for x in range(0, len(trueScores))],
                  trueScores,
                  c='C2',
                  label=u'All Values')

    plt.fill(np.concatenate([X_samps, X_samps[::-1]]),
             np.concatenate(
                 [y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]),
             alpha=.1,
             fc='g',
             ec='None',
             label='95% confidence interval')

    plt.xlabel('Number of Documents')
    plt.ylabel('Return Rate')
    #plt.xlim(0, len(scores))
    #  plt.title(str())
    plt.title("Sample Rate: " + str(sampleRate) + " 70% Recall: " +
              str(x_val_true))

    plt.legend(loc='upper right')
    plt.show()
    plt.plot(X, y, 'r+', markersize=20, lw=2.0, label='observations')
    plt.errorbar(X.ravel(),
                 y,
                 dy,
                 fmt='r.',
                 markersize=10,
                 label='Observations')
    plt.plot(Xt,
             y_pred,
             color='g',
             linestyle='--',
             lw=1.5,
             label='GP prediction')
    plt.fill(np.concatenate([Xt, Xt[::-1]]),
             np.concatenate(
                 [y_pred - 1.96 * sigma, (y_pred + 1.96 * sigma)[::-1]]),
             alpha=0.5,
             label='95% conf interval')
    plt.title('GP regression')
    plt.xlabel('X1')
    plt.ylabel('X2')
    plt.grid(True)
    plt.legend()
    plt.show()

    #fit a GP to market data
    #load data
    start = datetime(2015, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2016, 1, 1, 0, 0, 0, 0, pytz.utc)
    spy = data.DataReader("SPY", 'google', start, end)
Пример #35
0
import sys
sys.path.append('../scraper')
import location_sampler

states_file = 'states.xml'

borders = np.asarray(location_sampler.get_borders(states_file))
labels = location_sampler.get_labels(states_file)

nLabels = len(borders)

state_center = np.zeros([nLabels, 2])

for i in range(0, nLabels):
    plt.fill(borders[i][:, 0], borders[i][:, 1], 'r-')
    border_A = map(float, borders[i][:, 0])
    border_B = map(float, borders[i][:, 1])
    #pdb.set_trace()

    state_center[i, 1] = np.mean(border_A)
    state_center[i, 0] = np.mean(border_B)
    plt.plot(state_center[i, 1], state_center[i, 0], 'b.')

np.save("state_center.npy", state_center)
plt.show()
plt.hold(True)

juneau_ak = (58.3019, 134.4197)
honolulu_hi = (21.3069, 157.8583)
print(great_circle(juneau_ak, honolulu_hi).kilometers)
Пример #36
0
matplotlib.rcParams['font.family']='Arial Unicode MS'
matplotlib.rcParams['font.sans-serif']=['Arial Unicode MS']

radar_labels = np.array(['爆发力','技巧熟练度','气势',\
                         '稳定性','速度'])
nAttr = 5
data = np.array([[0.8,0.9,0.9,0.75],
                 [0.85,0.87,0.9,0.9],
                 [0.9,0.6,1.0,0.6],
                 [0.8,0.7,0.7,0.9],
                 [0.6,0.9,0.9,0.92]]
                )
data_labels = ('马龙','张继科','马琳',\
               '王励勤')
angles = np.linspace(0, 2*np.pi, nAttr, endpoint = False)
data = np.concatenate((data, [data[0]]))
angles = np.concatenate((angles, [angles[0]]))
fig = plt.figure(facecolor = 'white')
plt.subplot(111, polar = True)
plt.plot(angles, data, 'o-', linewidth = 1.5, alpha = 0.9)
plt.fill(angles, data, alpha = 0.2)
plt.thetagrids(angles*180/np.pi, radar_labels)
plt.figtext(0.05, 0.97, '中国国家队乒乓球运动员参数雷达图',ha =
            'left', size = 15)
legend = plt.legend(data_labels, loc = (0.9,0.92), labelspacing= 0.1)
#plt.setp(legend.get_texts(), fontsize = 'small')
#plt.grid(True)
plt.savefig('9.5PingPong_holland_radar.jpg')
plt.show()
def generate_cover(title, subtitle, file_name):
    sha = hashlib.sha3_512()
    sha.update((title + subtitle).encode("utf8"))
    rem = int.from_bytes(sha.digest(), "little")
    rg = np.random.default_rng(rem)
    r = np.sqrt(1 - 0.5**2)
    x = [0, 0, r, 2 * r, 2 * r, r, 0]
    y = [1, 0, -0.5, 0, 1, 1.5, 1]
    x_data = np.array(x)
    y_data = np.array(y)
    fig = plt.figure(figsize=(66, 36))
    x_orig = x_data.copy()

    width = 37
    height = 25
    for j in range(height):
        x_data = x_orig.copy()
        shift = (j % 2) == 0
        x_data += shift * r
        for i in range(width):
            plt.fill(x_data, y_data, color=color[rg.integers(0, len(color))])
            x_data += 2 * r
        y_data -= 1 + 0.5

    fig.savefig(f"{file_name}-back.png",
                pad_inches=0,
                bbox_inches="tight",
                dpi=108)
    ax = fig.axes[0]
    ylim = ax.get_ylim()
    h = ylim[1] - ylim[0]
    img = Image.open(f"{file_name}-back.png")
    vadj = int(img.size[1] / h // 1)
    px = img.size[0] // (width + 1)
    box = [px // 2, vadj, img.size[0] - px // 2, img.size[1] - vadj]
    crop = img.crop(box)
    sz = crop.size
    if sz[0] / sz[1] > 16 / 9:
        new_width = int(np.ceil(sz[0] * (16 / 9) / (sz[0] / sz[1])))
        loss = sz[0] - new_width
        box = [loss // 2, 0, sz[0] - loss // 2, crop.size[1]]
        crop = crop.crop(box)
    crop.save(f"{file_name}-back.png")

    plt.fill(
        [0, (width + r / 2) * 2 * r, (width + r / 2) * 2 * r, 0],
        [-3 + 0.5 - 1.5, -3 + 0.5 - 1.5, -8 - 2 - 1.5, -8 - 2 - 1.5],
        color="#ffffff",
    )

    plt.subplots_adjust(0, 0, 1, 1, 0, 0)
    for ax in fig.axes:
        ax.set_axis_off()
        ax.axis("off")
        ax.margins(0, 0)
        ax.xaxis.set_major_locator(plt.NullLocator())
        ax.yaxis.set_major_locator(plt.NullLocator())
    ax.text(
        5 * r,
        -6 - 1.5,
        title.replace("`", ""),
        fontsize=3 * 60,
        color=color[1],
        fontweight="normal",
        fontname="Roboto Condensed",
    )
    if subtitle:
        ax.text(
            5 * r,
            -8.5 - 1.5,
            subtitle.replace("`", ""),
            fontsize=3 * 40,
            color=color[3],
            fontname="Roboto Condensed",
            fontweight="light",
        )

    fig.savefig(f"{file_name}-cover.png",
                pad_inches=0,
                bbox_inches="tight",
                dpi=108)

    ylim = ax.get_ylim()
    h = ylim[1] - ylim[0]
    img = Image.open(f"{file_name}-cover.png")
    vadj = int(img.size[1] / h // 1)
    px = img.size[0] // (width + 1)
    box = [px // 2, vadj, img.size[0] - px // 2, img.size[1] - vadj]
    crop = img.crop(box)
    sz = crop.size
    if sz[0] / sz[1] > 16 / 9:
        new_width = int(np.ceil(sz[0] * (16 / 9) / (sz[0] / sz[1])))
        loss = sz[0] - new_width
        box = [loss // 2, 0, sz[0] - loss // 2, crop.size[1]]
        crop = crop.crop(box)
    crop.save(f"{file_name}-cover.png")
Пример #38
0
def wiggle(traces,
           skipt=1,
           scale=1.,
           lwidth=.1,
           offsets=None,
           redvel=0.,
           manthifts=None,
           tshift=0.,
           sampr=1.,
           clip=10.,
           dx=1.,
           color='black',
           fill=True,
           line=True,
           ax=None):

    ns = traces.shape[1]
    ntr = traces.shape[0]
    t = np.arange(ns) * sampr
    timereduce = lambda offsets, redvel, shift: [
        float(offset) / redvel + shift for offset in offsets
    ]

    if (offsets is not None):
        shifts = timereduce(offsets, redvel, tshift)
    elif (manthifts is not None):
        shifts = manthifts
    else:
        shifts = np.zeros((ntr, ))

    for i in range(0, ntr, skipt):
        trace = traces[i].copy()
        trace[0] = 0
        trace[-1] = 0

        if ax == None:
            if (line):
                plt.plot(i * dx + clipsign(trace / scale, clip),
                         t - shifts[i],
                         color=color,
                         linewidth=lwidth)
            if (fill):
                for j in range(ns):
                    if (trace[j] < 0):
                        trace[j] = 0
                plt.fill(i * dx + clipsign(trace / scale, clip),
                         t - shifts[i],
                         color=color,
                         linewidth=0)
        else:
            if (line):
                ax.plot(i * dx + clipsign(trace / scale, clip),
                        t - shifts[i],
                        color=color,
                        linewidth=lwidth)
            if (fill):
                for j in range(ns):
                    if (trace[j] < 0):
                        trace[j] = 0
                ax.fill(i * dx + clipsign(trace / scale, clip),
                        t - shifts[i],
                        color=color,
                        linewidth=0)
Пример #39
0
for i in range(xx.size):
    if (srad < np.sqrt(xx[i]**2 + yy[i]**2) < rmax * 0.97 * np.sqrt(3) / 2.):
        #    if (10.7 * srad < np.sqrt(xx[i]**2 + yy[i]**2) < rmax*0.97*np.sqrt(3)/2.):
        xs = np.append(xs, xx[i])
        ys = np.append(ys, yy[i])

# plot segments
# -------------
r0 = srad / sqrt(3)
th = 2 * np.pi * np.arange(6) / 6. + np.pi / 6.

for i in range(xs.size):
    hx = xs[i] + r0 * np.cos(th)
    hy = ys[i] + r0 * np.sin(th)
    plt.fill(hx, hy, fc='none', linewidth=1)

plt.plot(xs, ys, 'r.')
# plot spider arms
# ----------------
#r0 = rmax
#x0, x1, y0, y1 = -r0, r0, 0, 0
#plt.plot([x0, x1], [y0, y1], color='gray', linewidth=5)
#x0, y0 = r0 * np.cos(np.pi/3), r0 * np.sin(np.pi/3)
#x1, y1 = -x0, -y0
#plt.plot([x0, x1], [y0, y1], color='gray', linewidth=5)
#x0, y0 = r0 * np.cos(2*np.pi/3), r0 * np.sin(2*np.pi/3)
#x1, y1 = -x0, -y0
#plt.plot([x0, x1], [y0, y1], color='gray', linewidth=5)

# plot sample points
Пример #40
0
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 27 02:05:03 2015

@author: antalcides
"""
import matplotlib.pyplot as plt
n = 16
m = 6
plt.figure(figsize=(n * 0.2, m * 0.2))
plt.gca().axison = False
x = 8
y = 4
plt.fill((x, x + 1, x + 1, x), (y, y, y + 1, y + 1), 'r', linewidth=0)
for i in range(0, n + 1):
    ii = (i, i)
    jj = (0, m)
    plt.plot(ii, jj, '0.4', linewidth=0.2)
for j in range(0, m + 1):
    ii = (0, n)
    jj = (j, j)
    plt.plot(ii, jj, '0.4', linewidth=0.2)
plt.savefig('myplot.pdf', bbox_inches='tight')
Пример #41
0
def plot_regions(model,
                 X,
                 y,
                 num_ticks=100,
                 cmap='rainbow',
                 fig_size=None,
                 legend=True,
                 close=True,
                 display=True,
                 path=None,
                 keras=False):

    # Convert X to numpy array
    X = np.array(X)
    y = np.array(y)

    # Check to see if there are exactly 2 features
    if X.shape[1] != 2:
        raise Exception('Training set must contain exactly ' + 'two features.')

    # Find min and max points for grid axes
    minx, maxx = min(X[:, 0]), max(X[:, 0])
    marginx = (maxx - minx) / 20
    x0, x1 = minx - marginx, maxx + marginx

    miny, maxy = min(X[:, 1]), max(X[:, 1])
    marginy = (maxy - miny) / 20
    y0, y1 = miny - marginy, maxy + marginy

    # Create grid tick marks
    xticks = np.linspace(x0, x1, num_ticks)
    yticks = np.linspace(y0, y1, num_ticks)

    # Create array of grid points
    # tile stacks copies of xticks end creating a size num_ticks^2 array
    # repeat repeats each elt of yticks to create a size num_ticks^2 array
    # They are combined into an array of shape (2, num_ticks^2)
    # transpose creates array of pts with shape (num_ticks^2, 2).
    grid_pts = np.transpose(
        [np.tile(xticks, len(yticks)),
         np.repeat(yticks, len(xticks))])

    # Feed grid points to model to generate 1D array of classes
    if (keras == True):
        class_pts = model.predict_classes(grid_pts)
        class_pts = class_pts.reshape((len(class_pts), ))
    else:
        class_pts = model.predict(grid_pts)

    # Get list of classes. This could, in theory, contain text labels.
    classes = np.unique(y)
    k = len(classes)

    # create new list with numerical classes
    class_pts_2 = np.zeros(class_pts.shape)
    for i in range(len(classes)):
        sel = class_pts == classes[i]
        class_pts_2[sel] = i

    # reshape classification array into 2D array corresponding to grid
    class_grid = class_pts_2.reshape(len(xticks), len(yticks))

    # Set a color map
    my_cmap = plt.get_cmap(cmap)

    # Close any open figures and set plot size.

    if (close):
        plt.close()
    if (not fig_size is None):
        plt.figure(figsize=fig_size)

    # Add color mesh
    plt.pcolormesh(xticks,
                   yticks,
                   class_grid,
                   cmap=my_cmap,
                   zorder=1,
                   vmin=0,
                   vmax=k - 1)

    # Add transparency layer to lighten the colors
    plt.fill([x0, x0, x1, x1], [y0, y1, y1, y0], 'white', alpha=0.5, zorder=2)

    # Select discrete cuts for color map
    cuts = np.arange(k) / (k - 1)

    # Add scatter plot for each class, with seperate colors and labels
    for i in range(k):
        sel = y == classes[i]

        my_c = mplc.rgb2hex(my_cmap(cuts[i]))
        plt.scatter(X[sel, 0],
                    X[sel, 1],
                    c=my_c,
                    edgecolor='k',
                    zorder=3,
                    label=classes[i])

    if (legend):
        plt.legend()

    if (not path is None):
        plt.savefig(path, format='png')

    if (display):
        plt.show()
Пример #42
0
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt 

x = np.linspace(0, 5*np.pi, 1000)
y1 = np.sin(x)
y2 = np.sin(2*x)

# plt.plot(x, y1)
# plt.plot(x, y2)

# fill range between x axis and curve
plt.fill(x, y1, 'b', alpha=0.3)
plt.fill(x, y2, 'r', alpha=0.3)

plt.show()
Пример #43
0
def draw_roles(p,z,roles,background=False,marker=".",size=1):
    c = [ROLE_COLORS[x] for x in roles]
    plt.scatter(p,z,color=c,marker=marker,s=size)
    
    if background:
        ylim = plt.ylim()
        plt.hlines(2.5,0,1)
        plt.vlines(0.05,ylim[0],2.5)
        plt.vlines(0.625,ylim[0],2.5)
        plt.vlines(0.8,ylim[0],2.5)

        plt.vlines(0.3,2.5,ylim[1])
        plt.vlines(0.75,2.5,ylim[1])
        plt.fill([0,0.3,0.3,0],[ylim[1],ylim[1],2.5,2.5],color=ROLE_COLORS["R5"],alpha=.2)
        plt.fill([0.75,0.3,0.3,0.75],[ylim[1],ylim[1],2.5,2.5],color=ROLE_COLORS["R6"],alpha=.2)
        plt.fill([0.75,1,1,.75],[ylim[1],ylim[1],2.5,2.5],color=ROLE_COLORS["R7"],alpha=.2)

        plt.fill([0,.05,.05,0],[ylim[0],ylim[0],2.5,2.5],color=ROLE_COLORS["R1"],alpha=.2)
        plt.fill([.625,.05,.05,.625],[ylim[0],ylim[0],2.5,2.5],color=ROLE_COLORS["R2"],alpha=.2)
        plt.fill([.625,.8,.8,.625],[ylim[0],ylim[0],2.5,2.5],color=ROLE_COLORS["R3"],alpha=.2)
        plt.fill([1,.8,.8,1],[ylim[0],ylim[0],2.5,2.5],color=ROLE_COLORS["R4"],alpha=.2)

        plt.ylim(ylim)
        plt.xlim((-0.01,1))
        plt.xlabel("Participation coefficient")
        plt.ylabel("z-score of within-module degree")
Пример #44
0
	a=random.uniform(0,1000)
	b=random.uniform(0,1000)
	w=random.uniform(0,100)
    h=random.uniform(0,100)
	f=box(a,b,a+w,b+h)
	print(f.area);

if f.contains(pnt2):
	print("Covered");
else:
	print("Not Covered");


plt.figure()
x,y=c1.exterior.coords.xy;
plt.fill(x,y,edgecolor='black', linewidth=2.1)
x,y=f.exterior.coords.xy;
plt.fill(x,y,edgecolor='black', linewidth=2.1)
plt.plot(pnt2.x,pnt2.y,'r',marker = 'o');
#plt.plot(x,y)
plt.show()


"""poly = Polygon([(2.2, 4.2), (7.2, -25.1), (9.26, -2.456)]) 
x,y=poly.exterior.coords.xy;
plt.fill(x,y,edgecolor='black', linewidth=2.1)
"""

'''p1 = Point(10,10);
c1= p1.buffer(20);
x,y=c1.exterior.coords.xy;
Пример #45
0
}, {
    'name': 'r_state',
    'bits': 2
}, {
    'name': 'r_closed',
    'bits': 1
}]

path_location = os.path.dirname(os.path.realpath(__file__))
dreamer_file = os.path.join(path_location, 'two_player', 'ctrl.json')
# dreamer_file = '/home/formal/cyberphysical_systems/hw5/two_player/ctrl.json'
dreamer_sim = Controller(dreamer_lookup, dreamer_file)
node_init = '0'
var_list = dreamer_sim.simulate(node_init, 40)

plt.fill([0, 1, 1, 0], [0, 0, 1, 1], 'b', alpha=0.2, edgecolor='r')
plt.fill([1, 2, 2, 1], [0, 0, 1, 1], 'y', alpha=0.2, edgecolor='r')
plt.fill([2, 3, 3, 2], [0, 0, 1, 1], 'b', alpha=0.2, edgecolor='r')
plt.fill([3, 4, 4, 3], [0, 0, 1, 1], 'y', alpha=0.2, edgecolor='r')
plt.grid()

l = len(var_list)

anim = animation.FuncAnimation(fig,
                               animate,
                               init_func=init(),
                               frames=l,
                               interval=1000,
                               blit=True,
                               repeat=False)
Пример #46
0
def plot_multipoles(data,
                    main_harmonic_order=2,
                    r0=17.5 / 1000,
                    plot_label='',
                    harmonics=None,
                    directory=None,
                    filename=None,
                    max_multipole=None,
                    ymin=1e-6,
                    colors=None,
                    alpha_blending=0.6,
                    legend=None,
                    reference_data_idx=0,
                    display_plot=True):
    """ plots mutipole data comparisons """
    ''' processes input parameters '''
    if colors == None:
        colors = colors_redline
    if filename == None:
        filename = 'multipoles.ps'
    if max_multipole is None:
        max_multipole = max(data[reference_data_idx].harmonics)
    if harmonics is None:
        harmonics = []
        for i in data[reference_data_idx].harmonics:
            if i <= max_multipole:
                harmonics.append(i)
    ''' defines main multipole '''
    nr_bars = len(data)
    #main_idx = data[reference_data_idx].harmonics.index(main_multipole_order)
    #main_multipole = abs(data[reference_data_idx].LNn_avg[main_idx]*(r0**(data[reference_data_idx].harmonics[main_idx]-1)))
    ''' main loop for normal component '''
    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(1, 1, 1)
    ax.set_yscale('log')
    dx = 1  #0.4/nr_bars
    xticks = []
    for j in range(nr_bars):
        main_idx = data[j].harmonics.index(main_harmonic_order)
        main_multipole = abs(data[j].LNn_avg[main_idx] *
                             (r0**(data[j].harmonics[main_idx] - 1)))
        #main_multipole_error = abs(data[j].LNn_std[main_idx]*(r0**(data[j].harmonics[main_idx]-1)))
        x, y, n = [], [], 1
        for i in range(len(harmonics)):

            idx = data[j].harmonics.index(harmonics[i])
            alpha = r0**(data[j].harmonics[idx] -
                         1) / (r0**(data[j].harmonics[main_idx] - 1))
            error = alpha * math.sqrt(
                (data[j].LNn_std[idx] / data[j].LNn_avg[main_idx])**2 +
                (data[j].LNn_avg[idx] * data[j].LNn_std[main_idx] /
                 data[j].LNn_avg[main_idx])**2)
            multipole_0 = alpha * abs(
                data[j].LNn_avg[idx] / data[j].LNn_avg[main_idx])
            multipole_p = multipole_0 + error
            multipole_n = multipole_0 - error

            if multipole_n < 0:
                multipole_n = ymin
            x0 = n * (nr_bars + 2) + j
            if j == nr_bars / 2:
                xticks.append(x0)
            x.append(x0 - 0.5 * dx), y.append(ymin)
            x.append(x0 - 0.5 * dx), y.append(multipole_0)
            x.append(x0 + 0.5 * dx), y.append(multipole_0)
            x.append(x0 + 0.5 * dx), y.append(ymin)
            if (multipole_n != 0) or (multipole_p != 0):
                plt.plot([x0, x0], [multipole_n, multipole_p],
                         color=(0, 0, 0))  #colors[j])
                plt.plot([x0 - 0.25 * dx, x0 + 0.25 * dx],
                         [multipole_n, multipole_n],
                         color=(0, 0, 0))  #colors[j])
                plt.plot([x0 - 0.25 * dx, x0 + 0.25 * dx],
                         [multipole_p, multipole_p],
                         color=(0, 0, 0))  #colors[j])
            n += 1
        plt.fill(x,
                 y,
                 color=RotatingCoilMeasurement.alpha_blending(
                     colors[j % len(colors)], alpha_blending))
    ''' creates plots '''
    ax.grid(True)
    ax.xaxis.set_ticks(xticks)
    ax.xaxis.set_ticklabels(['{0:d}'.format(i) for i in harmonics])
    plt.ylim(ymin=ymin)
    plt.xlabel('harmonic order')
    plt.ylabel('relative normal multipole strengths (r$_0$ = ' +
               str(r0 * 1000) + ' mm)')
    if legend is not None:
        plt.legend(legend)
    plt.title(plot_label + ': normal components')
    if directory is not None:
        fname = os.path.join(directory, filename + '_normal.ps')
    else:
        fname = filename + '_normal.ps'
    plt.savefig(fname)
    if display_plot:
        plt.show()
    plt.close()

    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(1, 1, 1)
    ax.set_yscale('log')
    dx = 1  #0.4/nr_bars
    xticks = []

    for j in range(nr_bars):
        x, y, n = [], [], 1
        for i in range(len(harmonics)):
            idx = data[j].harmonics.index(harmonics[i])
            multipole_0 = abs(data[j].LSn_avg[idx]) * (r0**(
                data[j].harmonics[idx] - 1)) / main_multipole
            multipole_p = (abs(data[j].LSn_avg[idx]) +
                           data[j].LSn_std[idx]) * (r0**(
                               data[j].harmonics[idx] - 1)) / main_multipole
            multipole_n = (abs(data[j].LSn_avg[idx]) -
                           data[j].LSn_std[idx]) * (r0**(
                               data[j].harmonics[idx] - 1)) / main_multipole
            if multipole_n < 0:
                multipole_n = ymin
            x0 = n * (nr_bars + 2) + j
            if j == nr_bars / 2:
                xticks.append(x0)
            x.append(x0 - 0.5 * dx), y.append(ymin)
            x.append(x0 - 0.5 * dx), y.append(multipole_0)
            x.append(x0 + 0.5 * dx), y.append(multipole_0)
            x.append(x0 + 0.5 * dx), y.append(ymin)
            if (multipole_n != 0) or (multipole_p != 0):
                plt.plot([x0, x0], [multipole_n, multipole_p],
                         color=(0, 0, 0))  #colors[j])
                plt.plot([x0 - 0.25 * dx, x0 + 0.25 * dx],
                         [multipole_n, multipole_n],
                         color=(0, 0, 0))  #colors[j])
                plt.plot([x0 - 0.25 * dx, x0 + 0.25 * dx],
                         [multipole_p, multipole_p],
                         color=(0, 0, 0))  #colors[j])
            n += 1
        plt.fill(x,
                 y,
                 color=RotatingCoilMeasurement.alpha_blending(
                     colors[j % len(colors)], alpha_blending))

    ax.grid(True)
    ax.xaxis.set_ticks(xticks)
    ax.xaxis.set_ticklabels(['{0:d}'.format(i) for i in harmonics])
    plt.xlabel('harmonic order')
    plt.ylabel('relative skew multipole strengths (r$_0$ = ' + str(r0 * 1000) +
               ' mm)')
    if legend is not None:
        plt.legend(legend)
    plt.title(plot_label + ': skew components')
    if directory is not None:
        fname = os.path.join(directory, filename + '_skew.ps')
    else:
        fname = filename + '_skew.ps'
    plt.savefig(fname)
    if display_plot:
        plt.show()
    plt.close()
Пример #47
0
 def display_obstacle(self):
     
     obstacle_x, obstacle_y = self.obstacle.exterior.xy  #this method is defined in class Polygon
     plt.fill(obstacle_x, obstacle_y)
Пример #48
0
                'weight': 'bold',
            })
        # Set the font used for MathJax - more on thiprint(images)
        rc('mathtext', **{'default': 'regular'})
        plt.rc('font', family='serif')

        plt.figure()
        ax = plt.axes(xlim=(0, 12), ylim=(0, 9))
        plt.plot(CV, fes, zorder=5)
        plt.plot(CV, fes_biased, zorder=5)

        # Plot N circles to represent N walkers
        for j in range(N):
            # prevent crossing of each other
            plt.plot(rx[j], ry[j], color='black', zorder=10 + j)
            plt.fill(rx[j], ry[j], color='yellow', zorder=10 + j)
            if N > 1:
                plt.text(cx[j],
                         cy[j],
                         '%s' % str(j + 1),
                         zorder=10 + j,
                         fontsize='8')

        plt.fill_between(CV, 0, fes, color='steelblue')
        plt.fill_between(CV, fes, fes_biased, color='palegreen')
        plt.xlabel('Centers of mass separation distance (nm)',
                   fontsize='12',
                   fontweight='bold')
        plt.ylabel('Free energy ($k_{B} T$)', fontsize='12', fontweight='bold')

        if N == 1:
Пример #49
0
    def plot(self):
        fig = plt.figure(figsize=(15, 5))

        plt.subplot(2, 3, 1).set_title("Koch Line (iterations = 0)")
        points = self.koch(a=np.array([0, 0]),
                           b=np.array([1, 0]),
                           iterations=0)
        ptsx = []
        ptsy = []
        for i in range(len(points)):
            ptsx.append(points[i][0])
            ptsy.append(points[i][1])
        plt.plot(ptsx, ptsy, '-')
        plt.axis('equal')
        plt.axis('off')

        plt.subplot(2, 3, 2).set_title("Koch Line (iterations = 1)")
        points = self.koch(a=np.array([0, 0]),
                           b=np.array([1, 0]),
                           iterations=1)
        ptsx = []
        ptsy = []
        for i in range(len(points)):
            ptsx.append(points[i][0])
            ptsy.append(points[i][1])
        plt.plot(ptsx, ptsy, '-')
        plt.axis('equal')
        plt.axis('off')

        plt.subplot(2, 3, 3).set_title("Koch Line (iterations = 2)")
        points = self.koch(a=np.array([0, 0]),
                           b=np.array([1, 0]),
                           iterations=2)
        ptsx = []
        ptsy = []
        for i in range(len(points)):
            ptsx.append(points[i][0])
            ptsy.append(points[i][1])
        plt.plot(ptsx, ptsy, '-')
        plt.axis('equal')
        plt.axis('off')

        plt.subplot(2, 3, 4).set_title("Koch Line (iterations = 3)")
        points = self.koch(a=np.array([0, 0]),
                           b=np.array([1, 0]),
                           iterations=3)
        ptsx = []
        ptsy = []
        for i in range(len(points)):
            ptsx.append(points[i][0])
            ptsy.append(points[i][1])
        plt.plot(ptsx, ptsy, '-')
        plt.axis('equal')
        plt.axis('off')

        plt.subplot(2, 3, 5).set_title("Koch Line (iterations = 4)")
        points = self.koch(a=np.array([0, 0]),
                           b=np.array([1, 0]),
                           iterations=4)
        ptsx = []
        ptsy = []
        for i in range(len(points)):
            ptsx.append(points[i][0])
            ptsy.append(points[i][1])
        plt.plot(ptsx, ptsy, '-')
        plt.axis('equal')
        plt.axis('off')

        plt.subplot(2, 3, 6).set_title("Koch Line (iterations = 5)")
        points = self.koch(a=np.array([0, 0]),
                           b=np.array([1, 0]),
                           iterations=5)
        ptsx = []
        ptsy = []
        for i in range(len(points)):
            ptsx.append(points[i][0])
            ptsy.append(points[i][1])
        plt.plot(ptsx, ptsy, '-')
        plt.axis('equal')
        plt.axis('off')

        h = np.sqrt(3) / 2.
        a = np.array([0, 0])
        b = np.array([1, 0])
        c = np.array([0.5, h])

        iterations = 7

        points1 = self.koch(a=np.array([0, 0]),
                            b=np.array([1, 0]),
                            iterations=iterations)
        points2 = self.koch(a=np.array([1, 0]),
                            b=np.array([0.5, -h]),
                            iterations=iterations)
        points3 = self.koch(a=np.array([0.5, -h]),
                            b=np.array([0, 0]),
                            iterations=iterations)

        points = []
        for i in range(len(points1)):
            points.append(np.array(points1[i]))
        for i in range(len(points2)):
            points.append(np.array(points2[i]))
        for i in range(len(points3)):
            points.append(np.array(points3[i]))

        ptsx = []
        ptsy = []
        for i in range(len(points)):
            ptsx.append(points[i][0])
            ptsy.append(points[i][1])

        plt.figure(figsize=(25, 25))

        plt.title("Koch Triangle (iterations = 7)")
        plt.plot(ptsx, ptsy, '-')
        plt.fill(ptsx, ptsy, color='lightcyan', alpha=0.7)
        plt.axis('equal')
        plt.axis('off')
        plt.show()
Пример #50
0
        flat = list(
            itertools.chain(
                *[point for point in adj if point is not "removed"]))

        # this works only if order is not a concern...........
        #flat_no_duplicates = list(set(map(tuple, flat)))
        #print(flat)
        flat_no_duplicates = [
            e for i, e in enumerate(flat) if e not in flat[:i]
        ]

        polygons[i] = flat_no_duplicates
        #print(flat)

    return polygons


if __name__ == '__main__':
    polygons_fixed = fix_polygons(polygons[:])
    #polygons_fixed = list(filter(None, polygons_fixed))
    #print(polygons_fixed)
    #print(polygons_fixed)
    for i in range(len(polygons)):
        plt.fill(*zip(*polygons[i]), "r")
        #try: # polygon may get removed in fixed which would result in index error since we are looping unfixed
        plt.fill(*zip(*polygons_fixed[i]), "b")
        # except:
        #     pass
    plt.xlim([0, 1]), plt.ylim([0, 1])
    plt.show()
Пример #51
0
def kepflatten(infile,
               outfile=None,
               datacol='PDCSAP_FLUX',
               errcol='PDCSAP_FLUX_ERR',
               nsig=3.,
               stepsize=0.5,
               winsize=5.0,
               npoly=3,
               niter=1,
               ranges='0,0',
               plot=False,
               overwrite=False,
               verbose=False,
               logfile='kepflatten.log'):
    """
    kepflatten -- Remove low frequency variability from time-series, preserve
    transits and flares

    kepflatten detrends data for low-frequency photometric structure by
    dividing by the mean of best-fit sliding polynomials over a sequential
    series of small time ranges across the data. For example, a typical
    timestamp is fit three times of ``stepsize=1.0`` and ``winsize=3.0``. The
    adopted fit to the timestamp will be the mean of the three values. Outliers
    are iteratively-clipped from the fit, therefore structure in e.g.
    short-lived transits or flares are better preserved compared to e.g.
    bandpass filtering methods (``kepfilter``). Optionally, input data, best
    fits, fit outliers and output data are rendered to a plot window. In many
    respects kepflatten performs the opposite task to kepoutlier which removes
    statistical outliers while preserving low-frequency structure in light
    curves.

    Parameters
    ----------
    infile : str
        The name of a MAST standard format FITS file containing a Kepler light
        curve within the first data extension.
    outfile : str
        The name of the output FITS file. outfile will be a direct copy of
        infile but with NaN timestamps removed and two new columns in the 1st
        extension - DETSAP_FLUX (a flattened or detrended for low-frequency
        variations version of the data) and DETSAP_FLUX_ERR (the associated
        1-:math:`\sigma` error).
    datacol : str
        The column name containing data stored within extension 1 of infile.
        Typically this name is SAP_FLUX (Simple Aperture Photometry fluxes),
        PDCSAP_FLUX (Pre-search Data Conditioning fluxes) or CBVSAP_FLUX
        (SAP_FLUX corrected for systematic artifacts by the PyKE tool
        kepcotrend).
    errcol : str
        The column name containing photometric 1-:math:`\sigma` errors
        stored within extension 1 of infile. Typically this name is
        SAP_FLUX_ERR (Simple Aperture Photometry fluxes), PDCSAP_FLUX_ERR
        (Pre-search Data Conditioning fluxes). The error column coupled to
        CBVSAP_FLUX data is SAP_FLUX_ERR. kepflatten normalizes datacol and
        errcol consistently using a series of best fit polynomials.
    nsig : float
        The sigma clipping threshold in units of standard deviation. Data
        deviating from a best fit function by more than the threshold will
        ignored during subsequent fit iterations.
    stepsize : float
        The data within datacol is unlikely to be well represented by a single
        polynomial function. stepsize splits the data up into a series of time
        blocks, each is fit independently by a separate function. The user can
        provide an informed choice of stepsize after inspecting the data with
        the kepdraw tool. Units are days.
    winsize : float
        The size of the window to be fit during each step. Units are days.
        winsize must be greater or equal to stepsize. winsize >> stepsize is
        recommended.
    npoly : integer
        The order of each piecemeal polynomial function.
    niter : integer
        If outliers outside of nsig are found in a particular data section,
        that data will be removed temporarily and the time series fit again.
        This will be iterated niter times before freezing upon the best current
        fit.
    ranges : str
        The user can choose specific time ranges of data on which to work. This
        could, for example, avoid removing known stellar flares from a dataset.
        Time ranges are supplied as comma-separated pairs of Barycentric Julian
        Dates (BJDs). Multiple ranges are separated by a semi-colon. An example
        containing two time ranges is:

        ``2455012.48517,2455014.50072;2455022.63487,2455025.08231``.

        If the user wants to correct the entire time series then providing
        ``ranges='0,0'`` will tell the task to operate on the whole time
        series.
    plot : bool
        Plot the data, fit, outliers and result?
    overwrite : bool
        Overwrite the output file?
    verbose : bool
        Print informative messages and warnings to the shell and logfile?
    logfile : str
        Name of the logfile containing error and warning messages.

    Examples
    --------
    .. code-block:: bash

        $ kepflatten kplr012557548-2011177032512_llc.fits
        --nsig 3 --stepsize 1.0 --winsize 3.0 --npoly 3 --niter 10 --plot
        --overwrite --verbose

    .. image:: ../_static/images/api/kepflatten.png
        :align: center
    """

    if outfile is None:
        outfile = infile.split('.')[0] + "-{}.fits".format(__all__[0])
    # log the call
    hashline = '--------------------------------------------------------------'
    kepmsg.log(logfile, hashline, verbose)
    call = ('KEPFLATTEN -- ' + ' infile={}'.format(infile) +
            ' outfile={}'.format(outfile) + ' datacol={}'.format(datacol) +
            ' errcol={}'.format(errcol) + ' nsig={}'.format(nsig) +
            ' stepsize={}'.format(stepsize) + ' winsize={}'.format(winsize) +
            ' npoly={}'.format(npoly) + ' niter={}'.format(niter) +
            ' ranges={}'.format(ranges) + ' plot={}'.format(plot) +
            ' overwrite={}'.format(overwrite) + ' verbose={}'.format(verbose) +
            ' logfile={}'.format(logfile))
    kepmsg.log(logfile, call + '\n', verbose)

    # start time
    kepmsg.clock('KEPFLATTEN started at', logfile, verbose)

    # test winsize > stepsize
    if winsize < stepsize:
        errmsg = 'ERROR -- KEPFLATTEN: winsize must be greater than stepsize'
        kepmsg.err(logfile, errmsg, verbose)

    # overwrite output file
    if overwrite:
        kepio.overwrite(outfile, logfile, verbose)
    if kepio.fileexists(outfile):
        errmsg = ('ERROR -- KEPFLATTEN: {} exists. Use overwrite=True'.format(
            outfile))
        kepmsg.err(logfile, errmsg, verbose)

    # open input file
    instr = pyfits.open(infile, 'readonly')
    tstart, tstop, bjdref, cadence = kepio.timekeys(instr, infile, logfile,
                                                    verbose)
    try:
        work = instr[0].header['FILEVER']
        cadenom = 1.0
    except:
        cadenom = cadence

    # fudge non-compliant FITS keywords with no values
    instr = kepkey.emptykeys(instr, infile, logfile, verbose)
    # read table structure
    table = kepio.readfitstab(infile, instr[1], logfile, verbose)
    # filter input data table
    try:
        datac = table.field(datacol)
    except:
        errmsg = ('ERROR -- KEPFLATTEN: cannot find or read data column {}'.
                  format(datacol))
        kepmsg.err(logfile, message, verbose)
    try:
        err = table.field(errcol)
    except:
        errmsg = ('WARNING -- KEPFLATTEN: cannot find or read error column {}'.
                  format(errcol))
        kepmsg.warn(logfile, errmsg, verbose)
        errcol = 'None'
    if errcol.lower() == 'none' or errcol == 'PSF_FLUX_ERR':
        err = datac * cadence
        err = np.sqrt(np.abs(err)) / cadence
        work1 = np.array([table.field('time'), datac, err])
    else:
        work1 = np.array([table.field('time'), datac, err])
    work1 = np.rot90(work1, 3)
    work1 = work1[~np.isnan(work1).any(1)]

    # read table columns
    intime = work1[:, 2] + bjdref
    indata = work1[:, 1]
    inerr = work1[:, 0]
    if len(intime) == 0:
        message = 'ERROR -- KEPFLATTEN: one of the input arrays is all NaN'
        kepmsg.err(logfile, message, verbose)

    # time ranges for region to be corrected
    t1, t2 = kepio.timeranges(ranges, logfile, verbose)
    cadencelis = kepstat.filterOnRange(intime, t1, t2)
    # find limits of each time step
    tstep1, tstep2 = [], []
    work = intime[0]
    while work <= intime[-1]:
        tstep1.append(work)
        tstep2.append(
            np.array([work + winsize, intime[-1]], dtype='float64').min())
        work += stepsize

    # find cadence limits of each time step
    cstep1, cstep2 = [], []
    for n in range(len(tstep1)):
        for i in range(len(intime) - 1):
            if intime[i] <= tstep1[n] and intime[i + 1] > tstep1[n]:
                for j in range(i, len(intime) - 1):
                    if intime[j] < tstep2[n] and intime[j + 1] >= tstep2[n]:
                        cstep1.append(i)
                        cstep2.append(j + 1)

    # comment keyword in output file
    kepkey.history(call, instr[0], outfile, logfile, verbose)
    # clean up x-axis unit
    intime0 = tstart // 100 * 100.0
    ptime = intime - intime0
    xlab = 'BJD $-$ {}'.format(intime0)

    # clean up y-axis units
    pout = copy(indata)
    nrm = len(str(int(pout.max()))) - 1
    pout = pout / 10**nrm
    ylab = '10$^{}$'.format(nrm) + 'e$^-$ s$^{-1}$'

    # data limits
    xmin = ptime.min()
    xmax = ptime.max()
    ymin = pout.min()
    ymax = pout.max()
    xr = xmax - xmin
    yr = ymax - ymin
    ptime = np.insert(ptime, [0], [ptime[0]])
    ptime = np.append(ptime, [ptime[-1]])
    pout = np.insert(pout, [0], [0.0])
    pout = np.append(pout, 0.0)

    if plot:
        plt.figure()
        plt.clf()
        # plot data
        ax = plt.axes([0.06, 0.54, 0.93, 0.43])
        # force tick labels to be absolute rather than relative
        plt.gca().xaxis.set_major_formatter(
            plt.ScalarFormatter(useOffset=False))
        plt.gca().yaxis.set_major_formatter(
            plt.ScalarFormatter(useOffset=False))
        # rotate y labels by 90 deg
        labels = ax.get_yticklabels()
        plt.setp(plt.gca(), xticklabels=[])
        plt.plot(ptime[1:-1],
                 pout[1:-1],
                 color='#363636',
                 linestyle='-',
                 linewidth=1.0)
        plt.fill(ptime, pout, color='#a8a7a7', linewidth=0.0, alpha=0.2)
        plt.ylabel(ylab, {'color': 'k'})
        plt.grid()

    # loop over each time step, fit data, determine rms
    fitarray = np.zeros((len(indata), len(cstep1)), dtype='float32')
    sigarray = np.zeros((len(indata), len(cstep1)), dtype='float32')
    fitarray[:, :] = np.nan
    sigarray[:, :] = np.nan
    masterfit = indata * 0.0
    mastersigma = np.zeros(len(masterfit))
    functype = getattr(kepfunc, 'poly' + str(npoly))
    for i in tqdm(range(len(cstep1))):
        timeSeries = intime[cstep1[i]:cstep2[i] + 1] - intime[cstep1[i]]
        dataSeries = indata[cstep1[i]:cstep2[i] + 1]
        fitTimeSeries = np.array([], dtype='float32')
        fitDataSeries = np.array([], dtype='float32')
        pinit = [dataSeries.mean()]
        if npoly > 0:
            for j in range(npoly):
                pinit.append(0.0)
        pinit = np.array(pinit, dtype='float32')
        try:
            if len(fitarray[cstep1[i]:cstep2[i] + 1, i]) > len(pinit):
                coeffs, errors, covar, iiter, sigma, chi2, dof, fit, plotx, ploty = \
                    kepfit.lsqclip(functype, pinit, timeSeries, dataSeries,
                                   None, nsig, nsig, niter, logfile, verbose)
                fitarray[cstep1[i]:cstep2[i] + 1, i] = 0.0
                sigarray[cstep1[i]:cstep2[i] + 1, i] = sigma
                for j in range(len(coeffs)):
                    fitarray[cstep1[i]:cstep2[i] + 1,
                             i] += coeffs[j] * timeSeries**j
        except:
            message = ('WARNING -- KEPFLATTEN: could not fit range ' +
                       str(intime[cstep1[i]]) + '-' + str(intime[cstep2[i]]))
            kepmsg.warn(logfile, message, verbose)

    # find mean fit for each timestamp
    for i in range(len(indata)):
        masterfit[i] = np.nanmean(fitarray[i, :])
        mastersigma[i] = np.nanmean(sigarray[i, :])
    masterfit[-1] = masterfit[-4]  #fudge
    masterfit[-2] = masterfit[-4]  #fudge
    masterfit[-3] = masterfit[-4]  #fudge
    if plot:
        plt.plot(intime - intime0, masterfit / 10**nrm, 'b')

    # reject outliers
    rejtime, rejdata = [], []
    naxis2 = 0
    for i in range(len(masterfit)):
        if (abs(indata[i] - masterfit[i]) > nsig * mastersigma[i]
                and i in cadencelis):
            rejtime.append(intime[i])
            rejdata.append(indata[i])
    rejtime = np.array(rejtime, dtype='float64')
    rejdata = np.array(rejdata, dtype='float32')
    if plot:
        plt.plot(rejtime - intime0, rejdata / 10**nrm, 'ro', markersize=2)
    # new data for output file
    outdata = indata / masterfit
    outerr = inerr / masterfit
    pout = copy(outdata)
    ylab = 'Normalized Flux'
    # plot ranges
    if plot:
        plt.xlim(xmin - xr * 0.01, xmax + xr * 0.01)
        if ymin >= 0.0:
            plt.ylim(ymin - yr * 0.01, ymax + yr * 0.01)
        else:
            plt.ylim(1.0e-10, ymax + yr * 0.01)
        # plot residual data
        ax = plt.axes([0.06, 0.09, 0.93, 0.43])
        plt.gca().xaxis.set_major_formatter(
            plt.ScalarFormatter(useOffset=False))
        plt.gca().yaxis.set_major_formatter(
            plt.ScalarFormatter(useOffset=False))
        # rotate y labels by 90 deg
        labels = ax.get_yticklabels()

        ymin = pout.min()
        ymax = pout.max()
        yr = ymax - ymin
        pout = np.insert(pout, [0], [0.0])
        pout = np.append(pout, 0.0)
        plt.plot(ptime[1:-1],
                 pout[1:-1],
                 color='#363636',
                 linestyle='-',
                 linewidth=1.0)
        plt.fill(ptime, pout, color='#a8a7a7', linewidth=0.0, alpha=0.2)
        plt.xlabel(xlab, {'color': 'k'})
        plt.ylabel(ylab, {'color': 'k'})
        plt.grid()
        # plot ranges
        plt.xlim(xmin - xr * 0.01, xmax + xr * 0.01)
        if ymin >= 0.0:
            plt.ylim(ymin - yr * 0.01, ymax + yr * 0.01)
        else:
            plt.ylim(1.0e-10, ymax + yr * 0.01)
        # render plot
        plt.savefig(re.sub('.fits', '.png', outfile))
        plt.show()
    # add NaNs back into data
    n = 0
    work1 = np.array([], dtype='float32')
    work2 = np.array([], dtype='float32')
    instr = pyfits.open(infile, 'readonly')
    table = kepio.readfitstab(infile, instr[1], logfile, verbose)
    tn = table.field('time')
    dn = table.field(datacol)
    for i in range(len(table.field(0))):
        if np.isfinite(tn[i]) and np.isfinite(dn[i]) and np.isfinite(err[i]):
            try:
                work1 = np.append(work1, outdata[n])
                work2 = np.append(work2, outerr[n])
                n += 1
            except:
                pass
        else:
            work1 = np.append(work1, np.nan)
            work2 = np.append(work2, np.nan)

    # history keyword in output file
    kepkey.history(call, instr[0], outfile, logfile, verbose)

    # write output file
    try:
        print("Writing output file {}...".format(outfile))
        col1 = pyfits.Column(name='DETSAP_FLUX', format='E13.7', array=work1)
        col2 = pyfits.Column(name='DETSAP_FLUX_ERR',
                             format='E13.7',
                             array=work2)
        cols = instr[1].data.columns + col1 + col2
        instr[1] = pyfits.BinTableHDU.from_columns(cols,
                                                   header=instr[1].header)
        instr.writeto(outfile)
    except ValueError:
        try:
            instr[1].data.field('DETSAP_FLUX')[:] = work1
            instr[1].data.field('DETSAP_FLUX_ERR')[:] = work2
            instr.writeto(outfile)
        except:
            message = ('ERROR -- KEPFLATTEN: cannot add DETSAP_FLUX data to '
                       'FITS file')
            kepmsg.err(logfile, message, verbose)

    # close input file
    instr.close()
    ## end time
    kepmsg.clock('KEPFLATTEN completed at', logfile, verbose)
Пример #52
0
y_args = logaritmetic_spira_coridnates(y, r)

draw(x_args, y_args)

x_args = aritmetic_spiral_codinates(x, r)
y_args = aritmetic_spiral_codinates(y, r)

draw(x_args, y_args)

draw(r, [y(i) for i in r])

theta = np.arange(0, 8 * np.pi, 0.1)
a = 1
b = .2

for dt in np.arange(0, 2 * np.pi, np.pi / 2.0):

    x = a * np.cos(theta + dt) * np.exp(b * theta)
    y = a * np.sin(theta + dt) * np.exp(b * theta)

    dt = dt + np.pi / 4.0

    x2 = a * np.cos(theta + dt) * np.exp(b * theta)
    y2 = a * np.sin(theta + dt) * np.exp(b * theta)

    xf = np.concatenate((x, x2[::-1]))
    yf = np.concatenate((y, y2[::-1]))

    p1 = plt.fill(xf, yf)

plt.show()
Пример #53
0
 def fill_one_square(self, position, color):
     x, y = self.get_xy_coordinate(position)
     plt.fill(x,y, color)
Пример #54
0
    def vicsek(self, a, b, c, d, iterations, offset=np.array([0, 0])):
        ab = (a + b) / 3.
        ba = 2 * (a + b) / 3.
        bc = (2 * b + c) / 3.
        cb = (b + 2 * c) / 3.
        dc = (c + 2 * d) / 3.
        cd = (2 * c + d) / 3.
        ad = (d + a) / 3.
        da = 2 * (d + a) / 3.

        abd = 2 * a / 3. + (b + d) / 3.
        bac = a + (2 * b + d) / 3.
        cbd = 4 * a / 3. + 2 * (b + d) / 3.
        dac = a + (b + 2 * d) / 3.

        if iterations == 0:
            plt.fill([
                ab[0] + offset[0], ba[0] + offset[0], bac[0] + offset[0],
                bc[0] + offset[0], cb[0] + offset[0], cbd[0] + offset[0],
                cd[0] + offset[0], dc[0] + offset[0], dac[0] + offset[0],
                da[0] + offset[0], ad[0] + offset[0], abd[0] + offset[0]
            ], [
                ab[1] + offset[1], ba[1] + offset[1], bac[1] + offset[1],
                bc[1] + offset[1], cb[1] + offset[1], cbd[1] + offset[1],
                cd[1] + offset[1], dc[1] + offset[1], dac[1] + offset[1],
                da[1] + offset[1], ad[1] + offset[1], abd[1] + offset[1]
            ], 'saddlebrown')
            #plt.hold(True)
        else:
            abd_m = np.array([0, 0])
            bac_m = bac - abd
            cbd_m = cbd - abd
            dac_m = dac - abd
            offset1 = offset + abd
            self.vicsek(abd_m, bac_m, cbd_m, dac_m, iterations - 1, offset1)

            ab_m = np.array([0, 0])
            ba_m = ba - ab
            bac_m = bac - ab
            abd_m = abd - ab
            offset2 = offset + ab
            self.vicsek(ab_m, ba_m, bac_m, abd_m, iterations - 1, offset2)

            bac_m = np.array([0, 0])
            bc_m = bc - bac
            cb_m = cb - bac
            cbd_m = cbd - bac
            offset4 = offset + bac
            self.vicsek(bac_m, bc_m, cb_m, cbd_m, iterations - 1, offset4)

            dac_m = np.array([0, 0])
            cbd_m = cbd - dac
            cd_m = cd - dac
            dc_m = dc - dac
            offset6 = offset + dac
            self.vicsek(dac_m, cbd_m, cd_m, dc_m, iterations - 1, offset6)

            ad_m = np.array([0, 0])
            abd_m = abd - ad
            dac_m = dac - ad
            da_m = da - ad
            offset8 = offset + ad
            self.vicsek(ad_m, abd_m, dac_m, da_m, iterations - 1, offset8)
Пример #55
0
m2.drawmapboundary(fill_color='0.8')
m2.fillcontinents(color='w', lake_color='0.8')  #, zorder=0)
m2.drawcoastlines()
m2.drawcountries()
m2.drawstates()

# fill main area
xv = mean([llcrnrlon, urcrnrlon])
yv = mean([llcrnrlat, urcrnrlat])

xv = [llcrnrlon, urcrnrlon, urcrnrlon, llcrnrlon, llcrnrlon]
yv = [llcrnrlat, llcrnrlat, urcrnrlat, urcrnrlat, llcrnrlat]
x, y = m2(xv, yv)
#plt.plot(x, y, 'rs',ms=6)
plt.fill(x, y, facecolor='none', edgecolor='r', linewidth=2)

##########################################################################################
# label states
##########################################################################################
'''
state = ['WA', 'NT', 'SA', 'QLD', 'NSW', 'VIC', 'TAS']
slat = [-26, -21.0, -29.5, -23.0, -32.5, -37.1, -42.]
slon = [122, 133.5, 135.0, 144.5, 146.5, 143.6, 147.0]
for i, st in enumerate(state):
    x, y = m(slon[i], slat[i])
    plt.text(x, y, st, size=11, horizontalalignment='center', verticalalignment='center', weight='normal')
'''
##########################################################################################
# add colourbar
##########################################################################################
                color='0.99',
                linewidth=0.0)

##########################################################################################
# get land & lake polygons for masking
##########################################################################################

polys = get_map_polygons(m)

mask_outside_polygons(polys, 'lightskyblue', plt)

# get lake ploygons and mask
polygons = []
for polygon in m.lakepolygons:
    poly = polygon.get_coords()
    plt.fill(poly[:, 0], poly[:, 1], 'lightskyblue')
    polygons.append(poly)

###############################################################################
# make 50-km grid the ugly way
###############################################################################

cell_size = 30.
min_nresp = 2

grd_lons = []
grd_lats = []
grd_geom = []
grd_mmi = []
grd_count = []
lon_grd = minlon
Пример #57
0
    # with shaded regions of potential
    #plot_isw_state(L = 2)
    #plt.ylabel("$\psi(x)$", fontsize = 15)
    #plt.xlabel("$x$", fontsize = 15)
    #plt.axis([-.5, 2.5, 0, 2])
    #plt.fill([-.5, 0, 0, -.5], [0, 0, 2, 2], 'b', [2.0, 2.5, 2.5, 2.0], [0, 0, 2, 2], 'b', alpha=0.2)
    #plt.text(.6, 1.7, "$L = 2$", fontsize = 14)

    # Single spin arrows, centered on psi
    # plt.arrow(.5, 1.4-.05, 0, .18) # Spin up arrow
    # plt.arrow(.5, 1.4+.13, 0, -.18) # Spin down arrow

    # Double spin arrows
    #plt.arrow(1-.03, 1.0-.05, 0, .18) # Spin up arrow
    #plt.arrow(1+.03, 1.0+.13, 0, -.18) # Spin down arrow

    # Plotting ISW probability distribution with L = 1
    # on x = [-.5, 1.5] and y = [0, 2.5]
    # with shaded regions of potential
    plot_isw_prob()
    plt.ylabel("$P(x)$", fontsize=18)
    plt.xlabel("$x$", fontsize=18)
    plt.axis([-.5, 1.5, 0, 2.5])
    plt.fill([-.5, 0, 0, -.5], [0, 0, 2.5, 2.5],
             'b', [1.0, 1.5, 1.5, 1.0], [0, 0, 2.5, 2.5],
             'b',
             alpha=0.2)
    plt.text(.75, 1.7, "$L = 1$", fontsize=18)

    plt.show()
Пример #58
0
y_pred, MSE = gp.predict(x, eval_MSE=True)
sigma = np.sqrt(MSE)

x_true = np.array(map(f, timePts))
# Plot the function, the prediction and the 95% confidence interval based on
# the MSE
fig = pl.figure()
dXdT_true = np.array(map(df, timePts))
print "dXdT_true", dXdT_true
pl.plot(x_true, dXdT_true, 'g', label=u'$df(x)$', linewidth=5.0)
pl.errorbar(X.ravel(), y, dy, fmt='r.', markersize=10, label=u'Observations')
pl.plot(x, y_pred, 'b-', label=u'Prediction')
pl.fill(np.concatenate([x, x[::-1]]),
        np.concatenate(
            [y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]),
        alpha=.5,
        fc='b',
        ec='None',
        label='95% confidence interval')
pl.xlabel('$x$')
pl.ylabel('$dx/dt$')
pl.ylim(-0.5, 4)
pl.legend(bbox_to_anchor=(0, 1), loc='upper left', ncol=2)

savefig('figures/test/diffEqPlot.png')


def integrateTraj(xs, dXdT_pred):
    dXdT_pred = np.matrix(dXdT_pred)
    xs = np.matrix(xs)
    indices = np.array(range(len(xs)))
def evaluate_A(predA,system_params, print_results=True,show_plots=False, proportion_of_max=0.9):
    ''' 
    evaluate_A(predA,system_params, print_results,show_plots):
        compute results for adjacency matrix estimation
    Inputs:
    predA: predicted adjacency matrix (no threshold)

    system_params: dictionary with: 
                'w': scalar or (n,1)
                'A': (n,n)
                'K': scalar 
                'Gamma': vectorized function
    print_results: boolean to determine if results should be displayed
    show_plots: boolean to determine if result should be plotted
    
    Outputs:
    A_res: series with labeled results
    
    '''
    #print("predA:",predA,type(predA))
    FS=16 # fontsize
    correctA=system_params['A']
    pos_label=1.0 # determines which label is considered a positive.
    fpr, tpr, thresholds = roc_curve(remove_diagonal(correctA,1),
                                         remove_diagonal(predA,1),
                                         pos_label=pos_label,
                                         drop_intermediate=False)
    roc_auc = auc(fpr, tpr)
    #print("roc_auc:",roc_auc,type(roc_auc))
    warnings.filterwarnings('ignore')
    f1_scores=np.array([f1_score(remove_diagonal(correctA,1),1*(remove_diagonal(predA,1)>thr)) for thr in thresholds])
    warnings.filterwarnings('default')
    optimal_f1=np.max(f1_scores)
    optimal_threshold=thresholds[np.argmax(f1_scores)]
    inds=list(np.where(f1_scores>= proportion_of_max*optimal_f1)[0])
    threshold_range=[np.min(thresholds[inds]),np.max(thresholds[inds])]
    if show_plots:
        plt.figure()
        plt.plot(thresholds,f1_scores,color='black')
        plt.xlim(0,1)
        plt.ylim(0,1)
        plt.xlabel('threshold',fontsize=FS)
        plt.ylabel('F1 score',fontsize=FS)
        plt.fill(np.append(thresholds[inds],[threshold_range[0],threshold_range[1]]),
                 np.append(f1_scores[inds],[0.0,0.0]),color='red',alpha=0.2)
        plt.text(0.5,0.5,'>%.1f %% of peak f1 score' %(100*proportion_of_max),fontsize=FS,ha='center')
    n_errors=np.sum(np.sum(abs((predA>optimal_threshold).astype(int)-correctA)))/2    
    num_osc=correctA.shape[0]
    if print_results:
        print('')
        print('Evaluating adjacency matrix:')   
        print('')
        print('Errors: %d out of %d' % (n_errors,(num_osc*(num_osc-1)/2)))
        print('Error rate: %.5f%%' % (n_errors/(num_osc*(num_osc-1.0)/2.0)*100.0))
        print('Area under ROC curve: %.5f' % (roc_auc))
        print('Best f1 score: %.5f' %(optimal_f1))
        print('Threshold for best f1 score: %.5f' %(optimal_threshold))
        print('Threshold range for >%.1f%% of best f1 score: [%.5f,%.5f]' % (100*proportion_of_max,threshold_range[0],threshold_range[1]))
        print('')
    
    A_res=pd.Series()
    
    A_res['Number of errors']=n_errors
    A_res['Error rate']=n_errors/(num_osc*(num_osc-1)/2)*100
    A_res['Area under ROC curve']=roc_auc
    A_res['Best f1 score']=optimal_f1
    A_res['Threshold for best f1 score']=optimal_threshold
    A_res['Threshold range for >%.1f%% of best f1 score'% (100*proportion_of_max)]=threshold_range
    

    return A_res
Пример #60
0
    def visualize(self,
                  scene,
                  trajector,
                  head_on,
                  sampled_landmark=None,
                  sampled_relation=None,
                  description='',
                  step=0.02):

        relation = sampled_relation
        print relation
        if hasattr(relation, 'measurement'):
            print relation.measurement, relation.measurement.best_distance_class, relation.measurement.best_degree_class

        # plt.figure( figsize=(6,8) )
        #plt.subplot(1,2,1)
        scene_bb = scene.get_bounding_box()
        scene_bb = scene_bb.inflate(
            Vec2(scene_bb.width * 0.5, scene_bb.height * 0.5))

        if relation:
            probabilities, points = self.get_probabilities_box(
                scene_bb, relation, head_on, sampled_landmark, step)
            # xs, ys = points[:,0], points[:,1]

            xs = arange(scene_bb.min_point.x, scene_bb.max_point.x, step)
            ys = arange(scene_bb.min_point.y, scene_bb.max_point.y, step)

            # probabilities = zeros(  ( len(ys),len(xs) )  )
            # for i,x in enumerate(xs):
            #     for j,y in enumerate(ys):
            #         rel = relation( head_on, sampled_landmark, Landmark('', PointRepresentation(Vec2(x,y)), None, None) )
            #         if hasattr(rel, 'measurement'):
            #             rel.measurement.best_degree_class = sampled_relation.measurement.best_degree_class
            #             rel.measurement.best_distance_class = sampled_relation.measurement.best_distance_class
            #         probabilities[j,i] = rel.is_applicable()
            #         # print rel.distance, probabilities[j,i]

            set_printoptions(threshold='nan')
            #print probabilities

            x = array([list(xs - step * 0.5)] * len(ys))
            y = array([list(ys - step * 0.5)] * len(xs)).T

            probabilities = probabilities.reshape((len(xs), len(ys))).T

            # print probabilities

            #print self.get_entropy(probabilities)
            plt.pcolor(x,
                       y,
                       probabilities,
                       cmap='jet',
                       edgecolors='none',
                       alpha=0.7)
            plt.colorbar()

        for lmk in scene.landmarks.values():
            if isinstance(lmk.representation, GroupLineRepresentation):
                xs = [
                    lmk.representation.line.start.x,
                    lmk.representation.line.end.x
                ]
                ys = [
                    lmk.representation.line.start.y,
                    lmk.representation.line.end.y
                ]
                plt.fill(xs, ys, facecolor='none', linewidth=2)
            elif isinstance(lmk.representation, RectangleRepresentation):
                rect = lmk.representation.rect
                xs = [
                    rect.min_point.x, rect.min_point.x, rect.max_point.x,
                    rect.max_point.x
                ]
                ys = [
                    rect.min_point.y, rect.max_point.y, rect.max_point.y,
                    rect.min_point.y
                ]
                plt.fill(xs, ys, facecolor='none', linewidth=2)
                plt.text(rect.min_point.x + 0.01, rect.max_point.y + 0.02,
                         lmk.name)

        plt.plot(self.location.x, self.location.y, 'bx', markeredgewidth=2)

        traj_rep = trajector.representation
        if isinstance(traj_rep, GroupLineRepresentation):
            xs = [traj_rep.line.start.x, traj_rep.line.end.x]
            ys = [traj_rep.line.start.y, traj_rep.line.end.y]
            plt.fill(xs, ys, facecolor='none', linewidth=2)
        elif isinstance(traj_rep, RectangleRepresentation):
            rect = traj_rep.rect
            xs = [
                rect.min_point.x, rect.min_point.x, rect.max_point.x,
                rect.max_point.x
            ]
            ys = [
                rect.min_point.y, rect.max_point.y, rect.max_point.y,
                rect.min_point.y
            ]
            plt.fill(xs, ys, facecolor='none', linewidth=2)
        elif isinstance(traj_rep, PointRepresentation):
            plt.plot(traj_rep.location.x,
                     traj_rep.location.y,
                     'bo',
                     markeredgewidth=2)

        plt.text(traj_rep.middle.x + 0.01, traj_rep.middle.y + 0.02,
                 'trajector')
        '''
        plt.plot(poi.x,poi.y,'rx',markeredgewidth=2)
        plt.text(poi.x+0.01,
                 poi.y+0.02,'POI')
        '''

        plt.plot(head_on.x, head_on.y, 'ro', markeredgewidth=2)
        plt.text(head_on.x + 0.02, head_on.y + 0.01, 'perspective')

        if sampled_landmark:
            lwidth = 3
            lcolor = (0, 1, 0)
            if isinstance(sampled_landmark.representation,
                          PointRepresentation):
                plt.plot(sampled_landmark.representation.location.x,
                         sampled_landmark.representation.location.y,
                         '.',
                         markeredgewidth=lwidth,
                         color=lcolor)
            elif isinstance(sampled_landmark.representation,
                            LineRepresentation):
                xs = [
                    sampled_landmark.representation.line.start.x,
                    sampled_landmark.representation.line.end.x
                ]
                ys = [
                    sampled_landmark.representation.line.start.y,
                    sampled_landmark.representation.line.end.y
                ]
                plt.fill(xs,
                         ys,
                         facecolor='none',
                         edgecolor=lcolor,
                         linewidth=lwidth)
            elif isinstance(sampled_landmark.representation,
                            RectangleRepresentation):
                rect = sampled_landmark.representation.rect
                xs = [
                    rect.min_point.x, rect.min_point.x, rect.max_point.x,
                    rect.max_point.x
                ]
                ys = [
                    rect.min_point.y, rect.max_point.y, rect.max_point.y,
                    rect.min_point.y
                ]
                plt.fill(xs,
                         ys,
                         facecolor='none',
                         edgecolor=lcolor,
                         linewidth=lwidth)

        # rel_scores = []
        # for relation in relations:
        #     rel_scores.append( relation.probability(poi, sampled_landmark) )
        # rel_scores = array(rel_scores)
        # rel_probabilities = rel_scores/sum(rel_scores)
        # index = rel_probabilities.cumsum().searchsorted( random.sample(1) )[0]
        # sampled_relation = relations[index]

        # toprint = str(poi)+' ; '+sampled_relation.get_description() + " " + sampled_landmark.get_description()
        # print toprint
        plt.axis('scaled')

        plt.axis([
            scene_bb.min_point.x, scene_bb.max_point.x, scene_bb.min_point.y,
            scene_bb.max_point.y
        ])
        title = "Probability of location given description:\n" + description
        # plt.suptitle('\n'.join(wrap(title,50)))
        plt.suptitle(title)

        # plt.subplot(2,2,2)
        # plt.axis([0,1.5,-0.1,1.1])

        # xs = arange(0,3,0.01)
        # ys = {}
        # for relation in relations:
        #     name = relation.__class__.__name__
        #     plt.plot( xs, relation.distance_probability(xs) )
        # plt.axvline(x=distance,linewidth=2)
        # print distance

        plt.show()