Example #1
0
    def vecPlot2(self, row, col, r_m, mWx, mWy, data1, data2, dmr, frmSize, winSize):
        pl.clf()
        pl.ion()
        pWx = []
        l = dmr - row - col
        for f in range(l):
            pWx.append(mWx[row+f, col+f,:,0])
        pWx = np.array(pWx)

        sqWx = np.sqrt(pWx * pWx)
        print sqWx
        r,c = sqWx.shape
        x = pl.arange(c+1)
        y = pl.arange(r+1)
        X, Y = pl.meshgrid(x, y)

        pl.subplot2grid((1,2),(0,0))
        pl.pcolor(X, Y, sqWx, vmin=0, vmax=1)
        pl.xlim(0,c)
        pl.ylim(0,r)
        pl.colorbar()
        pl.title("user_1 (t:"+str(row)+")")
        pl.gray()

        pWy = []
        l = dmr - row - col
        for f in range(l):
            pWy.append(mWy[row+f, col+f,:,0])
        pWy = np.array(pWy)

        sqWy = np.sqrt(pWy * pWy)
        print sqWy
        r,c = sqWy.shape
        x = pl.arange(c+1)
        y = pl.arange(r+1)
        X, Y = pl.meshgrid(x, y)

        pl.subplot2grid((1,2),(0,1))
        pl.pcolor(X, Y, sqWy, vmin=0, vmax=1)
        pl.xlim(0,c)
        pl.ylim(0,r)
        pl.colorbar()
        pl.title("user_2 (t:"+str(col)+")")
        pl.gray()

        pl.tight_layout()
        pl.draw()
Example #2
0
    def _render_bar(self, key_word_sep=" ", title=None, **kwargs):
        """Generates a pylab horizaontal barchart from the result set.

        ``matplotlib`` must be installed, and in an
        IPython Notebook, inlining must be on::

            %%matplotlib inline

        First column is x-axis, and can be text, datetime or numeric. 
        Other columns are numeric, displayed as horizontal strips.

        Parameters
        ----------
        key_word_sep: string used to separate column values
                      from each other in pie labels
        title: Plot title, defaults to name of value column

        Any additional keyword arguments will be passsed
        through to ``matplotlib.pylab.pie``.
        """
        import matplotlib.pylab as plt

        self.build_columns()
        quantity_columns = [c for c in self.columns[1:] if c.is_quantity]
        ylabel = ", ".join([c.name for c in quantity_columns])
        xlabel = self.columns[0].name

        # print("xlabel: {}".format(xlabel))
        # print("ylabel: {}".format(ylabel))

        dim = len(quantity_columns)
        w = 0.8
        dimw = w / dim

        ax = plt.subplot(111)
        x = plt.arange(len(self.columns[0]))
        xpos = -dimw * (len(quantity_columns) / 2)
        for y in quantity_columns:
            columnchart = plt.bar(x + xpos,
                                  y,
                                  width=dimw,
                                  align="center",
                                  **kwargs)
            xpos += dimw
        plt.xticks(range(len(self.columns[0])), self.columns[0], rotation=45)
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
        plt.title(title or ylabel)

        plt.show()
        return columnchart
def PlotCodonMutNTComposition(allmutations, plotfile, title):
    """Plots nucleotide composition of mutant codons and mtuated.

    For each site containing a mutated codon, looks at the nucleotide
    composition of all three sites at the original and new codon. Plots the
    overall frequency of each nucleotide at these sites.

    allmutations -> list of all mutations as tuples (wtcodon, r, mutcodon)
    plotfile -> name of the plot file we create.
    title -> string giving the plot title.
    """
    nts = ['A', 'T', 'C', 'G']
    wtntcounts = dict([(nt, 0) for nt in nts])
    mutntcounts = dict([(nt, 0) for nt in nts])
    ntot = float(3 * len(allmutations))
    for (wtcodon, r, mutcodon) in allmutations:
        for nt in wtcodon:
            wtntcounts[nt] += 1 / ntot
        for nt in mutcodon:
            mutntcounts[nt] += 1 / ntot
    pylab.figure(figsize=(3.5, 2.25))
    (lmargin, rmargin, bmargin, tmargin) = (0.16, 0.01, 0.21, 0.07)
    pylab.axes([lmargin, bmargin, 1.0 - lmargin - rmargin, 1.0 - bmargin - tmargin])
    barwidth = 0.35
    xs = [i for i in range(len(nts))]
    nwt = pylab.bar([x - barwidth for x in xs], [wtntcounts[nt] for nt in nts], width=barwidth, color='blue')
    nmut = pylab.bar([x for x in xs], [mutntcounts[nt] for nt in nts], width=barwidth, color='red')
    #pred = pylab.plot(xs, nexpected, 'rx', markersize=6, mew=3)
    pylab.gca().set_xlim([-0.5, 3.5])
    pylab.gca().set_ylim([0, max(wtntcounts.values() + mutntcounts.values()) * 1.35])
    #pylab.gca().xaxis.set_major_locator(matplotlib.ticker.MaxNLocator(4))
    pylab.gca().yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(5))
    pylab.xlabel('nucleotide')
    pylab.ylabel('codon composition')
    pylab.legend((nwt[0], nmut[0]), ('parent', 'mutant'), loc='upper center', numpoints=1, handlelength=1, ncol=2, borderaxespad=0.01, columnspacing=1.1, handletextpad=0.4)
    pylab.title(title, fontsize=12)
    pylab.xticks(pylab.arange(0, 4, 1), tuple(nts))
    pylab.savefig(plotfile)
    time.sleep(0.5)
    pylab.show()
def make_plot_observed(fname, bins=None, norm=None):

    d = pl.genfromtxt(fname, names=True, invalid_raise=False)

    # observed quantities
    Z = pl.array([chargeNumber(id) for id in d['ID'].astype(int)])  # element
    A = pl.array([massNumber(id)
                  for id in d['ID'].astype(int)])  # atomic mass number
    lE = pl.log10(d['E']) + 18  # energy in log10(E/eV))

    if bins == None:
        lEbins = pl.arange(18, 20.51, 0.01)  # logarithmic bins
        lEcens = (lEbins[1:] + lEbins[:-1]) / 2  # logarithmic bin centers
    else:
        lEbins = pl.arange(17.5, 20.2, 0.1)  # logarithmic bins

    lEcens = (lEbins[1:] + lEbins[:-1]) / 2  # logarithmic bin centers
    dE = 10**lEbins[1:] - 10**lEbins[:-1]  # bin widths

    # identify mass groups
    EE = (10.0**lEcens)**3
    J1 = EE * pl.histogram(lE, bins=lEbins)[0] / dE
    J = np.zeros_like(J1)
    Jn = np.zeros([len(J1, 58)])
    for iz in range(1, 57):
        idx = (Z == iz)
        J += pl.histogram(lE[idx], bins=lEbins)[0] / dE

    # idx1 = A == 1
    # idx2 = (A > 1) * (A < 5)
    # idx3 = (A > 4) * (A < 23)
    # idx4 = (A > 22) * (A < 39)

    # # calculate spectrum: J(E) = dN/dE, we want E^3 J(E)
    # EE = (10.0 ** lEcens) ** 3

    #lum = np.sum(J * dE)
    # J  = EE * pl.histogram(lE, bins=lEbins)[0] / dE
    # J1 = EE * pl.histogram(lE[idx1], bins=lEbins)[0] / dE
    # J2 = EE * pl.histogram(lE[idx2], bins=lEbins)[0] / dE
    # J3 = EE * pl.histogram(lE[idx3], bins=lEbins)[0] / dE
    # J4 = EE * pl.histogram(lE[idx4], bins=lEbins)[0] / dE

    # normalize the histograms
    # if norm == None:
    # 	norm = 1.0 / J[0]
    # else:
    # 	norm = norm / J[10]
    norm = 1.0 / J[0]

    J1 *= norm
    # J2 *= norm
    # J3 *= norm
    # J4 *= norm
    J *= norm

    pl.plot(lEcens, smooth(J), color='k', linewidth=3, label="Total")
    pl.plot(lEcens, smooth(J1), color='#e84118', label='A = 1')
    pl.plot(lEcens, smooth(J2), color="#7f8fa6", label='A = 2-4')
    pl.plot(lEcens, smooth(J3), color="#44bd32", label='A = 5-22')
    pl.plot(lEcens, smooth(J4), color="#00a8ff", label='A = 23-38')

    pl.legend(fontsize=20, frameon=True, loc=3)
    pl.semilogy()
    #pl.ylim(1e-5)
    pl.grid()
    pl.ylabel('$E^3 J(E)$ [a.u.]')
    pl.xlabel('$\log_{10}$(E/eV)')
Example #5
0
    def drawPlot(self, row, col, mWx, mWy, ccaMat, data1, data2, dataMaxRange, dataDimen, winSize):
        #def drawPlot(self, row, col):
        print "draw:"+str(row)+", "+str(col)

        #test
        pWx = mWx[row,col:,0,:]
        print "pWx:",pWx
        print "shape:",pWx.shape

        #データの取得
        U1 = []
        U2 = []

        for w in range(winSize):
            U1.append(data1[row+w])
            U2.append(data2[col+w])

        nU1 = CCA().stdn(U1)
        nU2 = CCA().stdn(U2)

        #pl.clf()
        pl.ion()

        Wx = mWx[row][col]
        Wy = mWy[row][col]

        X, Y = pl.meshgrid(pl.arange(dataDimen+1), pl.arange(dataDimen+1))
       
        strCorU1s = []
        strCorU2s = []
        for i in range(dataDimen):
            fU1 = np.dot(nU1.T, Wx[:,i:i+1]).T
            fU2 = np.dot(nU2.T, Wy[:,i:i+1]).T
            strU1 = np.corrcoef(fU1, nU1)
            strU2 = np.corrcoef(fU2, nU2)  
            strCorU1 = np.squeeze(np.asarray(strU1[0:1,1:]))
            strCorU2 = np.squeeze(np.asarray(strU2[0:1,1:]))
            strCorU1s.append(strCorU1)
            strCorU2s.append(strCorU2)
            
            #print np.dot(Wx[:,i:i+1].T,Wx[:,i:i+1]).mean()

        sWx = np.array(np.matrix(strCorU1s))
        sWy = np.array(np.matrix(strCorU2s))
        
        #print Wx.shape
        #print Wx
        #print sWx.shape
        #print sWx

        pl.subplot2grid((3,2),(0,0),colspan=2)
        pl.xlim(0,dataDimen)
        pl.ylim(0,1)
        pl.xticks(fontsize=10)
        pl.yticks(fontsize=10)
        pl.plot(ccaMat[row][col])
        pl.title("eigen value (user 1:"+str(row)+", user 2:"+str(col)+")",fontsize=11)

        pl.subplot2grid((3,2),(1,0))
        pl.pcolor(X, Y, sWx)
        pl.gca().set_aspect('equal')
        pl.colorbar()
        pl.gray()
        pl.xticks(fontsize=10)
        pl.yticks(fontsize=10)
        pl.title("user 1:"+str(row),fontsize=11)

        pl.subplot2grid((3,2),(1,1))
        pl.pcolor(X, Y, sWy)
        pl.gca().set_aspect('equal')
        pl.colorbar()
        pl.gray()
        pl.xticks(fontsize=10)
        pl.yticks(fontsize=10)
        pl.title("user 2:"+str(col),fontsize=11)

        x = np.linspace(0, winSize-1, winSize)

        #forで回して第三位の正準相関までとる?
        pl.subplot2grid((3,2),(2,0),colspan=2)
        ls = ["-","--","-."]
        rhos = ""
        order = 3
        for i in range(order):
            fU1 = np.dot(nU1.T, Wx[:,i:i+1]).T
            fU2 = np.dot(nU2.T, Wy[:,i:i+1]).T

            fU1 = np.squeeze(np.asarray(fU1))
            fU2 = np.squeeze(np.asarray(fU2))

            rho = round(ccaMat[row][col][i],5)

            pl.plot(x, fU1, label="user1:"+str(rho), linestyle=ls[i])
            pl.plot(x, fU2, label="user2:"+str(rho), linestyle=ls[i])
            rhos += str(rho)+", "

        leg = pl.legend(prop={'size':9})
        leg.get_frame().set_alpha(0.7)
        pl.xticks(fontsize=10)
        pl.yticks(fontsize=10)
        pl.title("canonical variate (eig val:"+rhos.rstrip(", ")+")",fontsize=11)

        pl.tight_layout()
        pl.draw()
Example #6
0
    def vecPlot(self, row, col, r_m, mWx, mWy, data1, data2, frmSize, winSize):
        pl.clf()
        pl.ion()

        #pWy = mWy[row][col]
        #まずはx方向のWx
        pWx = mWx[row,col:(frmSize-winSize+1)+row,:,0]

        #print np.mean(pWx*pWx, axis=0)
        sqWx = np.sqrt(pWx * pWx)/1.1
        print sqWx
        r,c = sqWx.shape
        x = pl.arange(c+1)
        y = pl.arange(r+1)
        X, Y = pl.meshgrid(x, y)

        pl.subplot2grid((2,2),(0,0))
        pl.pcolor(X, Y, sqWx, vmin=0, vmax=1)
        pl.xlim(0,c)
        pl.ylim(0,r)
        pl.colorbar()
        pl.title("user_1 (t:"+str(row)+")")
        pl.gray()

        
        pWy = mWy[row,col:(frmSize-winSize+1)+row,:,0]
        #print "pWy sum:",np.sum(pWy[0,:],axis=1)
        #print np.sum(pWy*pWy,axis=1)
        #print np.mean(pWy*pWy, axis=0)
        sqWy = np.sqrt(pWy * pWy)
        r,c = sqWx.shape
        x = pl.arange(c+1)
        y = pl.arange(r+1)
        X, Y = pl.meshgrid(x, y)

        pl.subplot2grid((2,2),(0,1))
        pl.pcolor(X, Y, sqWy,vmin=0, vmax=1)    
        pl.xlim(0,c)
        pl.ylim(0,r)
        pl.colorbar()
        pl.title("user_2 (t:"+str(col)+")")
        pl.gray()

        """
        pl.subplot2grid((2,2),(1,0),colspan=2)
        pr, pc = pWx.shape
        for i in range(pc):
            pl.plot(pWx[:,i], color="r")
        """
        
        
        xl = np.arange(c)        
        pl.subplot2grid((2,2),(1,0))
        #subx1 = np.delete(sqWx,0,0)
        #subx2 = np.delete(sqWx,r-1,0)
        #print "sum sub:",sum(subx2-subx1)
        #pl.bar(xl, np.fabs(np.mean(subx2-subx1,axis=0)))
        pl.bar(xl, np.mean(sqWx, axis=0))
        pl.xlim(0,c)
        pl.ylim(0,1)

        pl.subplot2grid((2,2),(1,1))
        #subx1 = np.delete(sqWy,0,0)
        #subx2 = np.delete(sqWy,r-1,0)
        #pl.bar(xl, np.fabs(np.mean(subx2-subx1,axis=0)))
        pl.bar(xl, np.mean(sqWy, axis=0))
        pl.xlim(0,c)
        pl.ylim(0,1)

        """
        pl.subplot2grid((2,2),(1,0),colspan=2)
        U1 = []
        U2 = []
        od = 0
        for w in range(winSize):
            U1.append(data1[row+w][od])
            U2.append(data2[col+w][od])
        pl.plot(U1, color="r")
        pl.plot(U2, color="b")        
        """
        """
        #正準相関変量の表示
        U1 = []
        U2 = []
        for w in range(winSize):
            U1.append(data1[row+w])
            U2.append(data2[col+w])
        U1 = np.array(U1)
        U2 = np.array(U2)
        U1 = U1 - U1.mean(axis=0)
        U2 = U2 - U2.mean(axis=0)

        print "u1 s:",U1.shape
        print "wx s:",mWx[row,col,0,:].shape
    
        ls = ["-","--","-."]
        rhos = ""
        order = 3
        xl = np.linspace(0, winSize-1, winSize)
        for i in range(order):

            fU1 = np.dot(U1, mWx[row,col,i,:]).T
            fU2 = np.dot(U2, mWy[row,col,i,:]).T

            fU1 = np.squeeze(np.asarray(fU1))
            fU2 = np.squeeze(np.asarray(fU2))

            rho = round(r_m[row][col][i],5)

            pl.plot(xl, fU1, label="user1:"+str(rho), linestyle=ls[i])
            pl.plot(xl, fU2, label="user2:"+str(rho), linestyle=ls[i])
            rhos += str(rho)+", "

        leg = pl.legend(prop={'size':9})
        leg.get_frame().set_alpha(0.7)
        pl.title("canonical variate (eig val:"+rhos.rstrip(", ")+")",fontsize=11)
        """
        pl.xticks(fontsize=10)
        pl.yticks(fontsize=10)

        pl.tight_layout()

        pl.draw()