#!/usr/bin/env python # coding: utf-8 # # MatRepr # # Render sparse and dense matrices to HTML and Latex, with a Jupyter extension. # In[1]: import scipy.sparse import numpy as np np.random.seed(123) # so matrepr can be imported from the source tree. import sys sys.path.insert(0, '..') from matrepr import mdisplay, mprint # ### Load MatRepr Jupyter extension # In[2]: get_ipython().run_line_magic('load_ext', 'matrepr') # ## SciPy sparse matrix # In[3]: scipy.sparse.random(6, 6, density=0.5) # ## 2D NumPy array # In[4]: mat = np.random.random((10, 10)) mdisplay(mat, floatfmt=".2f") # In[5]: mat = np.random.random((500, 25)) mdisplay(mat, floatfmt=".2f", max_rows=15, max_cols=25) # ## 2D NumPy array with row and column labels # In[6]: cities = ["Boston", "Buffalo", "Chicago", "Cleveland", "Dallas", "Denver"] distances = np.array([ [None, 457, 983, 639, 1815, 1991], [457, None, 536, 192, 1387, 1561], [983, 536, None, 344, 931, 1050], [639, 192, 344, None, 1205, 1369], [1815, 1387, 931, 1205, None, 801], [1991, 1561, 1050, 1369, 801, None], ]) mdisplay(distances, title=None, row_labels=cities, col_labels=cities, fill_value="--") # ## 1D arrays and vectors # In[7]: vec = np.random.random((1000,)) mdisplay(vec) # In[8]: mprint(vec, indices=False, title=False) # ## Sparse N-dimensional Tensors # # Sparse multidimensional tensors are presented as a list of tuples. # In[9]: import sparse tensor_4d = sparse.random((1000, 10, 10, 10, 10), density=0.1234) mdisplay(tensor_4d) # In[10]: mprint(tensor_4d) # ## Dense N-dimensional Numpy Arrays # In[11]: dense_4d = np.random.random((3, 3, 3, 3)) mdisplay(dense_4d, floatfmt=".2f") # ## Graph Adjacency Matrix with Edge and Vertex Weights # In[12]: import graphblas as gb edges = gb.Matrix.from_coo( [3, 0, 3, 5, 6, 0, 6, 1, 6, 2, 4, 1], [0, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6], [3, 2, 3, 1, 5, 3, 7, 8, 3, 1, 7, 4], nrows=7, ncols=7 ) vertices = gb.Vector.from_coo([range(7)], [f"V{i+1}" for i in range(7)], size=7) mdisplay(edges, row_labels=vertices, col_labels=vertices, title=False) # ## Nested matrices # In[13]: # You may mix types if the datastructure allows, as a Python list does mat = [ [scipy.sparse.random(2, 2, density=0.8), [[1, 2], [3, 4]]], [np.array([[1, 2], [3, 4]]), scipy.sparse.random(2, 2, density=0.6)] ] mdisplay(mat, floatfmt=".2f") # ## Large matrices # In[14]: scipy.sparse.eye(100_000_000, format="csr") # In[15]: r = scipy.sparse.random(10000, 10000, density=0.23456789, format="csr") # In[16]: r # ## Duplicate entries # # Some sparse formats allow multiple values with the same indices. # In[17]: row = [0, 1, 1, 2, 2, 2] col = [0, 1, 1, 2, 2, 2] val = [1, 2.1, 2.2, 3.1, 3.2, 3.3] dupes = scipy.sparse.coo_array((val, (row, col)), shape=(3, 3)) mdisplay(dupes) # In[ ]: