Example #1
2
def wiki_code():
    N = 51
    # Create a sparse matrix in the "list of lists" format. 
    # This provides a flexible syntax for creating sparse matrices.
    A = scpy.sparse.lil_matrix((N, N))
    # Finite difference matrices will always have some 
    # regular structure involving diagonals and off diagonals.
    # The lil_matrix object has a function to help you with this.
    A.setdiag(np.ones(N))              # The diagonal
    A.setdiag(-2*np.ones(N-1),k=1)       # The fist upward off-diagonal.
    A.setdiag(2*np.ones(N-1), k=-1)
    # etc. observe that I leave it to you to insert correct values along the diagonals...

    # To fix the boundaries, you'll have to reset some rows.
    # The numpy indexing you expect to work will work.
    #A[0,:] = np.zeros(N) # zero out the first row
    #A[0,0] = 1.0       # set diagonal in that row to 1.0


    # For performance, other sparse matrix formats are preferred.
    # Convert to "Compressed Row Format" CR
    A = A.tocsr()

    # Helpful for diagnostics

    print A.todense()

    # and 

    plt.spy(A.todense())
    plt.show()
def makespyplot( matrix, name, imgtype=None ):
  if not scipy.sparse.isspmatrix( matrix ):
      matrix = matrix.toscipy()

  with plot.PyPlot( name, ndigits=0, imgtype=imgtype ) as plt:
    plt.spy( matrix, markersize=0.8, color='black')
    plt.title( name+', nnz = '+str(matrix.nnz) )
Example #3
0
def save_matrix_fig(matrix, path, filename):
	fig = plt.figure()
	plt.spy(matrix)
	#plt.title(filename)
	plt.savefig(path + filename + '.png', dpi=600)
	plt.close(fig)
	return
Example #4
0
def plot_matrix_fig(matrix, filename):
	fig = plt.figure()
	plt.spy(matrix)
	plt.title(filename)
	#plt.savefig('/home/igorpesic/Desktop/filename.png', dpi=600)
	plt.show()
	return
Example #5
0
def plot(f, mesh=None, fig=None, **kwargs):
    """Plot functions/expression in 1D and spy matrices."""
    # Decide if function or expression
    try:
        V = f.function_space
        # Not really Scattered
        x = V.mesh.vertex_coordinates
        # Scattered in the same way
        y = f.vertex_values()
        isort = np.argsort(x[:, 0])
        x = x[isort]
        y = y[isort]
    # Expression or matrix
    except AttributeError:
        try:
            F = f.toarray()
            fig = plt.figure()
            plt.spy(F, precision=1e-10)
            return fig
        # Expression
        except AttributeError:
            # Evaluate at mesh vertices
            assert mesh is not None
            x = np.sort(mesh.vertex_coordinates)
            y = f.eval(x)

    if fig is None:
        fig = plt.figure()
    ax = fig.gca()
    ax.plot(x, y, **kwargs)

    return fig
def plotFeatMatr(toPlot,featureObjects,featureMat,saveDir,label,badIdx):
    nFeats = featureMat.shape[1]
    nnzPerFeature = toPlot.getnnz(0)
    # get the indices to sort this ish.
    # how many should we use?...
    # get the top N most common
    mostCommon = np.argsort(nnzPerFeature)[-nFeats//7:]
    # get their labels
    featLabels = [f.label() for f in featureObjects]
    # get a version imshow can handle
    matImage = toPlot.todense()
    # fix the aspect ratio
    aspectSkew = len(badIdx)/nFeats
    aspectStr = 1./aspectSkew
    # plot everything
    ax = plt.subplot(1,1,1)
    cax = plt.imshow(matImage,cmap=plt.cm.hot_r,aspect=aspectStr,
                     interpolation="nearest")
    plt.spy(toPlot,marker='s',markersize=1.0,color='b',
            aspect=aspectStr,precision='present')
    cbar = plt.colorbar(cax, ticks=[0, 1], orientation='vertical')
    # horizontal colorbar
    cbar.ax.set_yticklabels(['Min Feat', 'Max Feat'],
                            fontsize=g_label)
    ax.set_xticks(range(nFeats))
    ax.set_xticklabels(featLabels,rotation='vertical')
    plt.xlabel("Feature Number",fontsize=g_label)
    plt.ylabel("Individual",fontsize=g_label)
    return aspectStr
Example #7
0
def sparsity(matrix, min_value=0):
    """
    https://redmine.epfl.ch/projects/python_cookbook/wiki/Matrix_sparsity_patterns
    """
    mat = matrix.matrix
    plt.spy(mat, precision=min_value, marker=',')
    plt.show()
Example #8
0
def test_tsqr(create_func):
    mat, data = create_func()
    n = mat.shape[1]

    q, r = csnmf.tsqr.qr(data)

    print q.shape
    q = np.array(q)

    r = np.array(r)
    print r.shape

    print np.linalg.norm(mat - np.dot(q, r))

    assert np.allclose(mat, np.dot(q, r))
    assert np.allclose(np.eye(n, n), np.dot(q.T, q))
    assert np.all(r == np.triu(r))

    plt.figure()
    plt.subplot(2, 4, 1)
    plt.imshow(mat, interpolation='nearest')
    plt.title('Original matrix')
    plt.subplot(2, 4, 2)
    plt.imshow(q, interpolation='nearest')
    plt.title('$\mathbf{Q}$')
    plt.subplot(2, 4, 3)
    plt.imshow(np.dot(q.T, q), interpolation='nearest')
    plt.title('$\mathbf{Q}^T \mathbf{Q}$')
    plt.subplot(2, 4, 4)
    plt.imshow(r, interpolation='nearest')
    plt.title('$\mathbf{R}$')

    plt.subplot(2, 4, 8)
    plt.spy(r)
    plt.title('Nonzeros in $\mathbf{R}$')
Example #9
0
def check_ass_penaro(bcsd=None, bcssfuns=None, V=None, plot=False):
    mesh = V.mesh()

    bcone = bcsd[1]
    contshfunone = bcssfuns[1]
    Gammaone = bcone()

    bparts = dolfin.MeshFunction('size_t', mesh, mesh.topology().dim() - 1)
    Gammaone.mark(bparts, 0)

    u = dolfin.TrialFunction(V)
    v = dolfin.TestFunction(V)

    # Robin boundary form
    arob = dolfin.inner(u, v) * dolfin.ds(0)
    brob = dolfin.inner(v, contshfunone) * dolfin.ds(0)

    amatrob = dolfin.assemble(arob, exterior_facet_domains=bparts)
    bmatrob = dolfin.assemble(brob, exterior_facet_domains=bparts)

    amatrob = dts.mat_dolfin2sparse(amatrob)
    amatrob.eliminate_zeros()
    print 'Number of nonzeros in amatrob:', amatrob.nnz
    bmatrob = bmatrob.array()  # [ININDS]

    if plot:
        plt.figure(2)
        plt.spy(amatrob)

    if plot:
        plt.figure(1)
        for x in contshfunone.xs:
            plt.plot(x[0], x[1], 'bo')

    plt.show()
Example #10
0
    def getError(self):
        if plotIt:
            plt.spy(self.getAve(self.M))
            plt.show()

        num = self.getAve(self.M) * self.getHere(self.M)
        err = np.linalg.norm((self.getThere(self.M)-num), np.inf)
        return err
Example #11
0
def plotSpy(M, eps, myTitle):
    plt.figure()
    frame1 = plt.gca()
    frame1.get_xaxis().set_ticks([])
    frame1.get_yaxis().set_ticks([])
    #  plt.title(myTitle+",eps="+str(eps))
    plt.spy(M, precision=eps, marker=".", markersize=3)
    plt.savefig(myTitle + "eps" + str(eps) + ".eps")
Example #12
0
def plot_sparse(mat, filename):
    plt.spy(mat, markersize=1)
    plt.tight_layout()
    #plt.rc('xtick',labelsize=16)
    #plt.rc('ytick',labelsize=16)
    plt.savefig.format = "pdf"
    plt.savefig(filename)
    plt.clf()
Example #13
0
def plotMatrix(A):
    ''' Spy plot of matrix A.
    Arguments:
        A: (numpy.array, numpy.matrix, sparse.matrix)
    '''
    plt.spy(A, markersize=5)    
    plt.show()
    return
Example #14
0
def makeCouplingAtomPlot(n, tag):
    import parseXYZ
    from mpl_toolkits.mplot3d import Axes3D

    mmdir = "/Volumes/s/matrices/matrixmarket/"
    mmfile = mmdir + tag + "_A.mm"
    xyzdir = "/Volumes/s/keceli/Dropbox/work/SEMO/xyz/"
    xyzfile = xyzdir + tag + ".xyz"
    mat = getAtomMatrix(mmfile)
    nnz = mat.nnz
    distW = np.array([0.0] * nnz)
    xyz = parseXYZ.getXYZ(xyzfile)
    matD = getDistMat(xyz, 5.6)
    makeNnzHist(mat, xyz)
    xyzW = np.asarray(xyz[1:4])
    myrow = np.asarray(mat.row)
    mycol = np.asarray(mat.col)
    listofAtoms1 = myrow[mycol == n]
    listofAtoms2 = mycol[myrow == n]
    listofAtoms = np.unique(np.concatenate((listofAtoms1, listofAtoms2)))
    print "focused atom number and its coordinates:", n + 1, xyzW[:, n]
    print "number of atoms interacting with this atom:", len(listofAtoms)
    print "list of interacting atoms:", listofAtoms + 1
    print "jmol command:", str(["C" + str(listofAtoms[i] + 1) for i in range(len(listofAtoms))]).replace(
        "[", ""
    ).replace("]", "").replace("'", "")
    print "coordinates of interacting atoms", xyzW[:, listofAtoms]
    fig = plt.figure()
    plt.spy(mat, markersize=1)
    fig = plt.figure()
    plt.spy(matD, markersize=1)
    fig = plt.figure()
    plt.plot(listofAtoms, linestyle="None", marker="s")
    fig = plt.figure()
    ax = fig.add_subplot(111, projection="3d")
    plt.plot(xyzW[0, :], xyzW[1, :], xyzW[2, :], linestyle="None", marker=".", color="black", markersize=2)
    plt.plot(
        xyzW[0, listofAtoms],
        xyzW[1, listofAtoms],
        xyzW[2, listofAtoms],
        linestyle="None",
        marker="o",
        color="red",
        markersize=3,
    )
    plt.plot([xyzW[0, n]], [xyzW[1, n]], [xyzW[2, n]], linestyle="None", marker="s", color="blue", markersize=4)
    plt.grid(which="major", axis="all")
    plt.gca().set_aspect("equal", adjustable="box")
    #    ax.auto_scale_xyz()
    # plt.axis('equal')
    ax.set_xlim([-5, 25])
    ax.set_ylim([-5, 25])
    ax.set_zlim([0, 45])
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.set_zlabel("z")
    return
Example #15
0
def plotSparsity(data, xmin=0, ymin=0, xmax=0, ymax=0):
    
    if xmax == 0:
        xmax = data.shape[0]
    if ymax == 0:
        ymax = data.shape[1]
        
    plt.spy(data[xmin:xmax, ymin:ymax])
    plt.show()
Example #16
0
def main():
	n = 9
	arr = np.zeros((n,n))

	arr[:,0:3] = 1
	arr[n-1, :]  = 1
	arr[(4,7,1),(5,7,8)] = 1

	plt.spy(arr)
	savefig('arr_plot.png')
	plt.show()
Example #17
0
def plotSpy(M, eps):
    plt.figure()
    frame1 = plt.gca()
    frame1.get_xaxis().set_ticks([])
    frame1.get_xaxis().set_ticklabels([])
    frame1.get_yaxis().set_ticks([])
    frame1.get_yaxis().set_ticklabels([])
    plt.subplot(111)
    #  plt.title(myTitle+",eps="+str(eps))
    plt.spy(M, precision=eps, marker=".", markersize=1)
    plt.show
Example #18
0
def plot_matrix(Mat,dir_name=None,title=None):
	"""Plots and saves a dense matrix"""
	if dir_name is None:
		dir_name='./'
	if title is None:
		title = 'Matrix'
	plt.figure(figsize=(10,10))
	plt.spy(np.abs(Mat))
	plt.grid()
	plt.title(title)
	plt.savefig(dir_name+title+'.png')
Example #19
0
def contact_to_distance(M):
    N = np.zeros(M.shape)
    N[M!=0] = 1/M[M!=0]
    s = sparse.csgraph.floyd_warshall(N)
    plt.figure()
    plt.spy(s, precision=0, markersize=0.00000000000005)
    plot_image = plt.imshow(s, vmin=0,vmax=np.percentile(s,99),interpolation='nearest')
    plot_image.set_cmap("jet")
    plt.show(block=BLOCK)
    print s
    return s
def test_form_k():
    from pygeoiga.nurb.cad import make_3_layer_patches

    geometry = make_3_layer_patches(refine=True)
    geometry, gDoF = patch_topology(geometry)
    geometry = bezier_extraction_mp(geometry)

    K_glob = np.zeros((gDoF, gDoF))
    K_glob = form_k_bezier_mp(geometry, K_glob)

    plt.spy(K_glob)
    plt.show()
Example #21
0
def SpyDG(N=8, order=1):
    mesh1D = Mesh1D(N)
    fes = Discontinuous(H1(mesh1D, order=order))  #, dirichlet=)
    u, v = fes.TnT()
    a = BilinearForm(fes)
    a += SymbolicBFI(grad(u) * grad(v))
    a.Assemble()
    rows, cols, vals = a.mat.COO()
    A = sp.csr_matrix((vals, (rows, cols)))
    plt.figure(figsize=(7, 7))
    plt.spy(A)
    plt.show()
Example #22
0
def plotspy(title, xval, eventnumber):  #xval is which matrix u want to plot
    print(title)
    plt.spy(xval, origin='lower', aspect=3.3, markersize=5, color='black')
    ax = plt.axes()
    ax.invert_yaxis()
    ax.xaxis.tick_bottom()
    ax.set_xticks(np.arange(0, 32, 5))
    ax.set_yticks(np.arange(0, 11, 2))
    plt.xlabel("Strips")  #y_test value
    plt.ylabel("Layer")  #y_pred value
    plt.savefig('x_stripevent_without_incl_eff_{}.png'.format(eventnumber))
    plt.show()
Example #23
0
def PlotCSR(I, J, Vals, title):
    # print("In python module: {}".format(__file__))
    # print("I: ", I)
    # print("J: ", J)
    # print("Vals: ", Vals)
    size = I.shape[0] - 1
    csr = csr_matrix((Vals, J, I), shape=(size, size))
    plt.figure()
    plt.spy(csr, precision=1E-10)
    plt.title(title)
    plt.savefig('./' + title + '.png')
    plt.show()
Example #24
0
 def view_dataset(self, title, data, markersize=0.001):
     """plot data matrix
     
     Arguments:
         title {str} -- title of plot
         data {np.array} -- dataset to plot
     
     Keyword Arguments:
         markersize {float} -- size of datapoints (default: {0.001})
     """
     plt.spy(data, markersize=markersize)
     plt.title(title)
     plt.show()
    def PlotSparsity(self, solver):
        """
        Call in with your T.Solver as argument.
        """
        solver['H'].evaluate()
        H = solver['H'].output()

        solver['dg'].evaluate()
        dg = solver['dg'].output()
        
        plt.figure(1)
        plt.spy(np.concatenate([H,dg.T],axis=1))
        plt.show()
Example #26
0
 def plot_Phis_sparsity(self, Phis, fig=0):
     Phis = [phis[0].data.cpu().numpy() for phis in Phis]
     plt.figure(fig)
     plt.clf()
     for i, phi in enumerate(Phis):
         plt.subplot(1, len(Phis), i + 1)
         # plot first element of the batch
         plt.spy(phi, precision=0.001, marker='o', markersize=2)
         plt.xticks([])
         plt.yticks([])
         plt.title('k={}'.format(i))
     path = os.path.join(self.path, 'Phis.png')
     plt.savefig(path)
Example #27
0
def main():
    """
    Plot the sparsity pattern of arrays
    """
    # set image size
    plt.figure(figsize=(2.56, 2.56))
    x = numpy.random.randn(20, 20)
    x[5] = 0.
    x[:, 12] = 0.

    plt.spy(x, precision=0.1, markersize=5)

    plt.savefig(IMGPATH)
Example #28
0
def trucquanthuathot():
    import scipy.sparse as sparse
    import scipy.stats as stats
    import numpy as np
    import matplotlib.pyplot as plt
    np.random.seed(42)
    # create sparse matrix with density 0.25
    S = sparse.random(5, 5, density=0.25)
    A = S.toarray()
    plt.spy(S)
    S1 = sparse.random(5, 5, density=0.25, data_rvs=np.ones) 
    A1=S1.toarray()
    plt.spy(S1)
Example #29
0
def spy_inds(ind_iterable, img_dims):
    """
    Plots the pixels in ind_iterable

    :param ind_iterable:
    :param img_dims:
    :return:
    """
    mtrx = np.zeros(img_dims)
    for ind in ind_iterable:
        mtrx[ind[0], ind[1]] = 1
    plt.spy(mtrx)
    plt.show()
Example #30
0
 def plot_Phis_sparsity(self, Phis, fig=0):
     Phis = [phis[0].data.cpu().numpy() for phis in Phis]
     plt.figure(fig)
     plt.clf()
     for i, phi in enumerate(Phis):
         plt.subplot(1, len(Phis), i + 1)
         # plot first element of the batch
         plt.spy(phi, precision=0.001, marker='o', markersize=2)
         plt.xticks([])
         plt.yticks([])
         plt.title('k={}'.format(i))
     path = os.path.join(self.path, 'Phis.png')
     plt.savefig(path)
def Visualisation_Matrix(Model, Matrix_Docs_Terms, percentage):

    reorganisation_indice_rows = np.argsort(Model.row_labels_)
    reorganisation_indice_cols = np.argsort(Model.column_labels_)

    Matrix = Matrix_Docs_Terms[reorganisation_indice_rows, :]
    Matrix = Matrix[:, reorganisation_indice_cols]

    plt.spy(Matrix, markersize=0.5, color="red", aspect='auto')
    fig = plt.gcf()
    fig.set_size_inches(6, 6)
    plt.title("Percentage des valeurs manquantes est {}".format(percentage))
    plt.show()
Example #32
0
def main():
    g = Graph(5)
    g.addEdge(0, 1)
    g.addEdge(0, 2)
    g.addEdge(1, 2)
    g.addEdge(2, 0)
    g.addEdge(2, 3)

    for i in range(0, g.size):
        print(g.adjMatrix[i])
        print()
    draw.spy(g.adjMatrix, markersize=50)
    draw.show()
Example #33
0
    def build_user_rating_df(self):
        user_ids = []
        frames = []

        for user_id, d in self.user_id_dict.items():
            user_ids.append(user_id)
            frames.append(pd.DataFrame.from_dict(d, orient='index'))

        df = pd.concat(frames, keys=user_ids)

        df2 = df.unstack(level=-1)
        df3 = df2[0]

        #pd DF of the users (user id as index) with their associated ratings by route_id
        df3.index.name = 'user_id'
        self.df_users = df3

        #convert to numpy array for possible visualization
        user_rating_mat = self.df_users.to_numpy().copy()
        user_rating_mat[np.isnan(user_rating_mat)] = 0.0

        if self.verbatim:
            fig = plt.figure(figsize=(22, 22))
            plt.spy(user_rating_mat, markersize=0.5)
            plt.xlabel('Route ID', fontsize=24)
            plt.ylabel('User ID', fontsize=24)
            plt.title('User-Rating Matrix', fontsize=24)
            plt.rcParams['xtick.labelsize'] = 20
            plt.rcParams['ytick.labelsize'] = 20
            fig.savefig('sparsity.png')  # Use fig. here
            plt.show()

        #get users who have rated at least n=15 routes
        ind_users_at_least20 = []

        dim = user_rating_mat.shape
        for u in range(dim[0]):
            n = len(user_rating_mat[u, :].nonzero()[0])
            if n >= 15:
                ind_users_at_least20.append(u)

        #print(df_users.index[ind_users_at_least20])

        df_users_at_least20 = self.df_users.loc[
            self.df_users.index[ind_users_at_least20]]

        df20 = df_users_at_least20.stack()
        df20 = df20.reset_index()
        df20.columns = ['user_id', 'route_id', 'rating']
        #Pandas DF that has user_id, route_id, and rating; i.e., all the users and their ratings
        self.df20 = df20
def main():
    rng = np.random.RandomState(42)

    # Generate some 2D coefficients with sine waves with random frequency and phase
    n_samples, n_features, n_tasks = 100, 30, 40
    n_relevant_features = 5
    coef = np.zeros((n_tasks, n_features))
    times = np.linspace(0, 2 * np.pi, n_tasks)
    for k in range(n_relevant_features):
        coef[:, k] = np.sin((1. + rng.randn(1)) * times + 3 * rng.randn(1))

    X = rng.randn(n_samples, n_features)
    Y = np.dot(X, coef.T) + rng.randn(n_samples, n_tasks)

    coef_lasso_ = np.array([Lasso(alpha=0.5).fit(X, y).coef_ for y in Y.T])
    coef_multi_task_lasso_ = MultiTaskLasso(alpha=1.).fit(X, Y).coef_

    # #############################################################################
    # Plot support and time series
    fig = plt.figure(figsize=(8, 5))
    plt.subplot(1, 2, 1)
    plt.spy(coef_lasso_)
    plt.xlabel('Feature')
    plt.ylabel('Time (or Task)')
    plt.text(10, 5, 'Lasso')
    plt.subplot(1, 2, 2)
    plt.spy(coef_multi_task_lasso_)
    plt.xlabel('Feature')
    plt.ylabel('Time (or Task)')
    plt.text(10, 5, 'MultiTaskLasso')
    fig.suptitle('Coefficient non-zero location')

    feature_to_plot = 0
    plt.figure()
    lw = 2
    plt.plot(coef[:, feature_to_plot],
             color='seagreen',
             linewidth=lw,
             label='Ground truth')
    plt.plot(coef_lasso_[:, feature_to_plot],
             color='cornflowerblue',
             linewidth=lw,
             label='Lasso')
    plt.plot(coef_multi_task_lasso_[:, feature_to_plot],
             color='gold',
             linewidth=lw,
             label='MultiTaskLasso')
    plt.legend(loc='upper center')
    plt.axis('tight')
    plt.ylim([-1.1, 1.1])
    plt.show()
Example #35
0
def repetitionMatrix(_input, title="", kind=False, cmap="Reds"):

    _input = _input.lower()
    _input = re.sub("[\(\)\-,;:\"\.\?\!\_\[\]]", " ", _input)
    _input = re.sub("[\n']", " ", _input)

    x = word_tokenize(_input)
    y = x

    word_freq = dict()
    set_of_x = set(x)
    for word in set_of_x:
        val = x.count(word)
        word_freq.update({word: val})

    all_words = []

    for i in x:
        for j in y:
            if i == j:
                all_words.append(word_freq.get(i))
            else:
                all_words.append(0)

    divider = int(len(all_words) / len(x))

    arrays = []

    for element in range(0, len(all_words), divider):
        arrays.append(np.array(all_words[element - divider:element]))

    colmap = cm.get_cmap(cmap)
    arrays = np.vstack(arrays[1:])
    sparsematrix = sparse.csr_matrix(arrays)

    if kind == "sns":
        # Plot using seaborn
        sns.heatmap(arrays,
                    cbar=False,
                    square=True,
                    xticklabels=50,
                    yticklabels=50,
                    cmap="binary").set_title(title)
    elif kind == "sparse":
        plt.spy(sparsematrix, markersize=3, cmap="binary")

    else:
        #                plt.scatter(arrays[:,:], arrays[:,:], marker="s")
        plt.imshow(arrays, cmap="binary", interpolation="none")

    plt.title(title)
Example #36
0
def contact_to_distance(M):
    N = np.zeros(M.shape)
    N[M != 0] = 1 / M[M != 0]
    s = sparse.csgraph.floyd_warshall(N)
    plt.figure()
    plt.spy(s, precision=0, markersize=0.00000000000005)
    plot_image = plt.imshow(s,
                            vmin=0,
                            vmax=np.percentile(s, 99),
                            interpolation='nearest')
    plot_image.set_cmap("jet")
    plt.show(block=BLOCK)
    print s
    return s
Example #37
0
def grafmat(k):
    """Plot stiffness matrix sparsity

    Parameters
    ----------
    k : ndarray (int)
      Stiffness matrix of the system.

    """
    plt.figure("Stiffness matrix")
    plt.spy(k)
    plt.title("Stiffness matrix")
    plt.ylabel(r"$i$ index", size=10)
    plt.xlabel(r"$j$ index", size=10)
Example #38
0
def plot_graph_steps(graphs):
    """
    Plots successively the adjency matrix and the networkx spring representation.
    """
    for g in graphs:
        if sp.sparse.issparse(g):
            g = g.todense()
        
        plt.subplot(121)
        plt.title('adjency matrix')
        plt.spy(g)
        plt.subplot(122)
        nx.draw(nx.from_numpy_array(g))
        plt.show()
Example #39
0
def distance_to_gram(M):
    print M.shape
    n, m = M.shape
    bary = np.sum(np.triu(M,1))/(n**2)
    d = np.sum(M**2,0)/n - bary
    G = np.array([[(d[i]+d[j]-M[i][j]**2)/2 for i in range(n)] for j in range(m)])
    plt.figure()
    plt.spy(G, precision=0, markersize=0.000000000000005)
    
    plot_image = plt.imshow(G, vmin=0,vmax=np.abs(np.percentile(G,99)),interpolation='nearest')
    plot_image.set_cmap("jet")
    plt.show(block=BLOCK)
    print G
    return G
Example #40
0
def grafmat(k):
    """Plot stiffness matrix sparsity

    Parameters
    ----------
    k : ndarray (int)
      Stiffness matrix of the system.

    """
    plt.figure("Stiffness matrix")
    plt.spy(k)
    plt.title("Stiffness matrix")
    plt.ylabel(r"$i$ index", size=10)
    plt.xlabel(r"$j$ index", size=10)
Example #41
0
    def getError(self):
        if plotIt:
            plt.spy(self.getAve(self.M))
            plt.show()

        num = self.getAve(self.M) * self.getHere(self.M)
        err = np.linalg.norm((self.getThere(self.M) - num), np.inf)

        if plotIt:
            self.M.plotImage(self.getThere(self.M) - num)
            plt.show()
            plt.tight_layout

        return err
Example #42
0
def forw_function(n, s):
    id1 = np.linspace(1, n, n)
    w = np.zeros([n, n])
    for j in range(n):
        w[:, j] = np.exp(
            pow(id1 - (j + 1), 2) * (2 * pow(np.pi, 2)) / (pow(s, 2)))
    diagonals = np.linspace(0, pow(n, 2) - n, n)
    t_w = np.transpose(w)
    diag = sp.diags(t_w.diagonal(0), diagonals.astype(int),
                    (n, pow(n, 2))).toarray()
    b = np.full((n, pow(n, 2)), diag)
    plt.spy(b)
    plt.show()
    return b
Example #43
0
    def getError(self):
        if plotIt:
            plt.spy(self.getAve(self.M))
            plt.show()

        num = self.getAve(self.M) * self.getHere(self.M)
        err = np.linalg.norm((self.getThere(self.M)-num), np.inf)

        if plotIt:
            self.M.plotImage(self.getThere(self.M)-num)
            plt.show()
            plt.tight_layout

        return err
Example #44
0
def test_dataloader(train_loader, plot=True, plot_features=True):
    """Summary
    
    Args:
        train_loader (TYPE): Description
        plot (bool, optional): Description
    """
    t_start = time.time()
    batch_size = train_loader.batch_size
    if plot_features:
        fix, axs = plt.subplots(2, 4)
    for batch_idx, (data, target, feature_dict) in enumerate(train_loader):
        real_batch_size = data.shape[0]
        feature_vec = feature_dict['feature_vector']
        city_names = feature_dict['city_names']
        print(city_names)

        if batch_idx % 10 == 0:
            t_end = time.time()
            print('{} [{}/{} ({:.0f}%)]\t {:.0f}seconds \t{} - {} - {} - {}'.
                  format(train_loader.dataset.split_type,
                         batch_idx * len(data), len(train_loader.dataset),
                         100. * batch_idx / len(train_loader), t_end - t_start,
                         data.shape, target.shape, feature_vec.shape,
                         len(city_names)))

            t_start = time.time()
        if plot:
            try:
                plt.spy(data[0, 0, 0, :, :])
                plt.title("Example Image")
                plt.pause(0.1)
            except IndexError:
                plt.spy(data[0, 0, :, :])
                plt.title("Example Image")
                plt.pause(0.1)

        if plot_features:
            i = 0
            j_start = batch_idx * batch_size
            j_end = j_start + real_batch_size
            for ax in axs:
                for a in ax:
                    a.plot(np.arange(j_start, j_end), feature_vec[:, i])
                    i = i + 1

            plt.pause(0.1)
        if batch_idx > 2:
            break
Example #45
0
def results_show(mod_tot):
    for mod in mod_tot:
        n = int(sqrt(len(mod)))
        chessboard = np.zeros((n, n))
        for i in range(len(mod)):
            if mod[i] is True:
                chessboard[int(i / n)][i % n] = 1
        plt.spy(chessboard)
        for i in range(n + 1):
            for t in range(n * 25):
                plt.plot(i - 0.5, t / 25 - 0.5, '*', color='black')
        for i in range(n + 1):
            for t in range(n * 25):
                plt.plot(t / 25 - 0.5, i - 0.5, '*', color='black')
        plt.show()
def extract_ridges(mat):
	shap = np.shape(mat)
	tmp = np.zeros(shap)
	print np.shape(tmp)
	for i in xrange(1,shap[0]-1):
		for j in xrange(1,shap[0]-1):
			if ((mat[i][j-1] < mat[i][j]) and  (mat[i][j+1]<mat[i][j])):
				tmp[i][j] = 1
			if ((mat[i-1][j] < mat[i][j]) and  (mat[i+1][j]<mat[i][j])):
				tmp[i][j] = 1
	tmp2 = scipy.ndimage.filters.gaussian_filter(tmp,2)
	plt.spy(tmp)
	plt.show()
	plt.imshow(tmp2)
	plt.show()
Example #47
0
def makeTest(M):
    import rcm
    import sparse

    Mcsr = M.tocsr()
    plt.figure()
    plt.spy(Mcsr)
    p = rcm._reverse_cuthill_mckee(Mcsr.indices, Mcsr.indptr, M.shape[0])
    Mrcm = sparse.sp_permute(Mcsr, p, p)
    print "Bandwidth before", sparse.sp_bandwidth(Mcsr)
    print "Bandwidth after", sparse.sp_bandwidth(Mrcm)
    plt.figure()
    plt.spy(Mrcm)
    plt.show()
    return
Example #48
0
 def generate_edge_label_network_adjacency(self):
     assert self.edge_labels_list is not None and self.edge_labels_list
     n = len(self.edge_labels_list)
     G = np.zeros(shape=(n, n))
     for i in range(n):
         for j in range(n):
             curr_edge_label_pair = tuple([self.edge_labels_list[i], self.edge_labels_list[j]])
             if curr_edge_label_pair in self.child_i_vec_matrix_map:
                 assert curr_edge_label_pair in self.child_j_vec_matrix_map
                 G[i, j] = 1
                 G[j, i] = 1
     self.G = G
     plt.spy(G)
     plt.savefig('./G.pdf', dpi=300, format='pdf')
     plt.close()
Example #49
0
def sparse_matrix(wi, leng, den):
    """Creates a sparse matrix.

    It uses random number to place the values (non-null values).

    :param wi: the width of the matrix
    :type wi: integer
    :param leng: the length of the matrix
    :type leng: integer
    :param den: density of non-null number in the matrix
    :type den: float
    :return: The representation of a sparse matrix
    :rtype: matplotlib plot
    """
    sp_mat = sparse.random(wi, leng, den)
    plt.spy(sp_mat, markersize=1, mfc='purple', marker='p', mec='red')
Example #50
0
def spy_matrix(matrix, title):
    # Plot non-zero matrix entries

    zmin = np.min(matrix)
    zmax = np.max(matrix)

    plt.figure()

    plt.spy(matrix, precision=0.01)

    plt.xlabel("State j")
    plt.ylabel("State i")
    plt.title("%s" % title)

    plt.savefig("%s" % title)
    plt.close()
def spyClusters(adj,clusterId):
    nClusters = np.max(clusterId)+1
    clusterSizes = np.histogram(clusterId, bins=nClusters)[0]
    
    # Plot permuted adjacency matrix
    sortId = np.argsort(clusterId)
    plt.figure()
    plt.spy(adj[sortId[:,np.newaxis],sortId])
    
    # Plot lines showing boundaries between blocks
    cumulativeClusterSizes = np.cumsum(clusterSizes)
    for size in cumulativeClusterSizes[:-1]:
        plt.axhline(size, color='black', linewidth=1)
        plt.axvline(size, color='black', linewidth=1)
    
    plt.show()
Example #52
0
    def test_inpoly(self):
        x = np.linspace(0., 100, 101)
        y = np.linspace(100, 0., 101)
        pgcoords = [(30, 0), (80, 50), (10, 80)]

        # individual inpoly function
        plt.spy(self.inpoly(x, y, pgcoords))
        plt.show()

        z = np.array([1, 0])
        gr = self.Grid(x, y, z)

        # grid_method inpoly
        plt.spy(gr.inpoly(pgcoords))
        plt.show()
        return True
Example #53
0
def main():

    arrZeros = np.zeros((9, 9))
    for i in range(0, len(arrZeros)):
        for j in range(0, 3):
            arrZeros[i][j] = 1

    for i in range(0, len(arrZeros[0])):
        arrZeros[len(arrZeros) - 1][i] = 1

    arrZeros[(4, 7, 1), (
        5, 7, 8
    )] = 1  #Sets arrZeros[x's, y's] to the value of the RHS. x's and y's have been entered as tuples
    print(arrZeros)
    plt.spy(arrZeros)
    plt.show()
Example #54
0
def showContactMap(enm, *args, **kwargs):
    """Show Kirchhoff matrix using :func:`~matplotlib.pyplot.spy`.
    
    .. plot::
       :context:
       :include-source:
        
       p38_gnm = GNM('p38')
       p38_gnm.buildKirchhoff( p38_structure )
       plt.figure(figsize=(4,4))
       showContactMap( p38_gnm )

    .. plot::
       :context:
       :nofigs:
        
       plt.close('all')"""
    
    import matplotlib.pyplot as plt
    if not isinstance(enm, GNMBase):
        raise TypeError('model argument must be an ENM instance')
    kirchhoff = enm.getKirchhoff()
    if kirchhoff is None:
        LOGGER.warning('kirchhoff matrix is not set')
        return None
    show = plt.spy(kirchhoff, *args, **kwargs)
    plt.title('{0:s} contact map'.format(enm.getTitle())) 
    plt.xlabel('Residue index')
    plt.ylabel('Residue index')
    return show
Example #55
0
def spy_matrix(matrix, title):
    # Plot non-zero matrix entries

    zmin = np.min(matrix)
    zmax = np.max(matrix)

    plt.figure()

    plt.spy(matrix, precision=0.01)

    plt.xlabel("State j")
    plt.ylabel("State i")
    plt.title("%s" % title)

    plt.savefig("%s" % title)
    plt.close()
Example #56
0
def synth_graph(M, N):
    nE = 2 * N
    nS = M * N
    iE = np.array([1, 2, 4, 6, 8, 7, 5, 3]) - 1
    jE = np.array([2, 4, 6, 8, 7, 5, 3, 1]) - 1
    vE = 2 * np.ones(8)
    Ap = sp.sparse.csc_matrix(
        (vE, (iE, jE)),
        shape=(nE, nE)).toarray()  # Matrix in compressed column format
    Ap = Ap + Ap.transpose()
    Apr = [Ap] * nS  # Repeat patrol states nS times

    # Make a block diagonal matrix
    A = la.block_diag(*Apr)
    iS = np.array([
        1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,
        9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 13, 14, 14,
        14, 15, 15, 15, 16, 16, 2, 3, 6, 7, 10, 11, 14, 15
    ]) - 1
    jS = np.array([
        2, 5, 1, 3, 6, 2, 4, 7, 3, 8, 1, 6, 9, 2, 5, 7, 10, 3, 6, 8, 11, 4, 7,
        12, 5, 10, 13, 6, 9, 11, 14, 7, 10, 12, 15, 8, 11, 16, 9, 14, 13, 10,
        15, 14, 11, 16, 15, 12, 2, 3, 6, 7, 10, 11, 14, 15
    ]) - 1

    for idx in range(0, len(iS)):
        #     rr = range(8*(iS[idx]-1),  8*(iS[idx])-1)
        #     cc = range(8*(jS[idx]-1),  8*(jS[idx])-1)
        rr = range(8 * iS[idx], 8 * (iS[idx] + 1))
        cc = range(8 * jS[idx], 8 * (jS[idx] + 1))

        for jdx in range(0, 8):
            A[rr[jdx]][cc[jdx]] = 1

        # Collision avoidance (CA)-- robot and system cannot occupy the same
        # gridcell
    col_avoid = np.array([[2, 1], [3, 2], [6, 3], [7, 4], [10, 5], [11, 6],
                          [14, 7], [15, 8]]) - 1  # -1 for zero-indexing
    for idx in range(0, len(col_avoid)):
        ii = 8 * (col_avoid[idx][0]) + col_avoid[idx][
            1]  # Zero-indexing and trying to get indexing right
        A[ii] = np.zeros(nS * nE)
        A[:, ii] = (np.zeros(nS * nE)).T

    plt.spy(A)
    G = nx.from_numpy_matrix(A)
    return G, A
Example #57
0
def plot_spectral(data, fout, args, title):
    '''Function to plot bipartite cluster'''

    print('Plotting')
    # Set figure size
    # plt.figure(figsize=args.psize)

    # Heatmap
    # sns.heatmap(data, xticklabels=[], yticklabels=[])
    # Spy plot
    plt.spy(data, markersize = 0.05)

    # Annotations
    plt.title(title)
    plt.savefig(args.pf + fout + '.png')
    plt.clf(); # Clear all plots
    print('Plotting done')
Example #58
0
def sample_er():
    """
    Test the generation and fitting of an Erdos Renyi model
    """
    N = 100
    a0 = 0.75
    b0 = 0.75
    model = ErdosRenyiNetwork(rho=None, x=(a0,b0))
    
    plt.figure()
    
    for ex in np.arange(3):
        plt.subplot(1,3,ex+1)
        (A,f,theta) = sample_network(model,N)
        plt.spy(A)
        plt.title("ER (rho=%.3f)" % theta)
    plt.show()
Example #59
0
def sample_er():
    """
    Test the generation and fitting of an Erdos Renyi model
    """
    N = 100
    a0 = 0.75
    b0 = 0.75
    model = ErdosRenyiNetwork(rho=None, x=(a0, b0))

    plt.figure()

    for ex in np.arange(3):
        plt.subplot(1, 3, ex + 1)
        (A, f, theta) = sample_network(model, N)
        plt.spy(A)
        plt.title("ER (rho=%.3f)" % theta)
    plt.show()