Skip to main content

Generate different types of sparsity pattern for sparse matrices.

Project description



Generate different types of sparsity pattern for sparse matrices.


The sparsity-pattern git repo is available as PyPi package

pip install sparsity-pattern
pip install git+ssh://


The block-diagonal pattern for tensorflow

import sparsity_pattern
import tensorflow as tf

n_rows, n_cols = 10, 12
idx = sparsity_pattern.get('block', min(n_rows, n_cols), block_sizes=[3, 1, 2])

mat = tf.sparse.SparseTensor(
    dense_shape=(n_rows, n_cols),
    indices=tf.convert_to_tensor(idx, dtype=tf.int64),
    values=range(1, len(idx)+1))


The circle pattern for pytorch

import sparsity_pattern
import torch

n_rows, n_cols = 5, 7
idx = sparsity_pattern.get('circle', min(n_rows, n_cols), offsets=[1, 2])

mat = torch.sparse_coo_tensor(
    indices=torch.tensor(idx).transpose(0, 1), 
    values=range(1, len(idx)+1),
    size=[n_rows, n_cols])


The triu pattern for scipy

import sparsity_pattern
import scipy.sparse
import numpy as np

n, k = 4, -1
idx = sparsity_pattern.get('triu', n, k)
idx_rows, idx_cols = np.array(idx)[:, 0], np.array(idx)[:, 1]
mat = scipy.sparse.lil_matrix((n, n), dtype=np.int64)
mat[idx_rows, idx_cols] = range(1, len(idx)+1)


Check the examples folder for more notebooks.


Install a virtual environment

python3.6 -m venv .venv
source .venv/bin/activate
pip3 install --upgrade pip
pip3 install -r requirements.txt

(If your git repo is stored in a folder with whitespaces, then don't use the subfolder .venv. Use an absolute path without whitespaces.)

Python commands

  • Jupyter for the examples: jupyter lab
  • Check syntax: flake8 --ignore=F401 --exclude=$(grep -v '^#' .gitignore | xargs | sed -e 's/ /,/g')
  • Run Unit Tests: pytest
  • Upload to PyPi with twine: python sdist && twine upload -r pypi dist/*

Clean up

find . -type f -name "*.pyc" | xargs rm
find . -type d -name "__pycache__" | xargs rm -r
rm -r .pytest_cache
rm -r .venv


Please open an issue for support.


Please contribute using Github Flow. Create a branch, add commits, and open a pull request.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for sparsity-pattern, version 0.3.0
Filename, size File type Python version Upload date Hashes
Filename, size sparsity-pattern-0.3.0.tar.gz (5.5 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page