SSparseMatrix


NameSSparseMatrix JSON
Version 0.3.4 PyPI version JSON
download
home_pagehttps://github.com/antononcube/Python-packages/tree/main/SSparseMatrix
SummarySSparseMatrix package based on SciPy sparse matrices.
upload_time2023-10-20 13:56:21
maintainer
docs_urlNone
authorAnton Antonov
requires_python>=3.7
license
keywords sparse matrix r s s-plus linear algebra linear algebra row names column names named rows named columns
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Sparse matrices with named rows and columns

![PyPI](https://img.shields.io/pypi/v/SSparseMatrix?label=pypi%20SSparseMatrix)
![PyPI - Downloads](https://img.shields.io/pypi/dm/SSparseMatrix)

PePy:   
[![Downloads](https://static.pepy.tech/badge/SSparseMatrix)](https://pepy.tech/project/SSparseMatrix)
[![Downloads](https://static.pepy.tech/badge/SSparseMatrix/month)](https://pepy.tech/project/SSparseMatrix)
[![Downloads](https://static.pepy.tech/badge/SSparseMatrix/week)](https://pepy.tech/project/SSparseMatrix)


## Introduction

This Python package provides the class `SSparseMatrix` the objects of which are sparse matrices with named rows and columns.

We can say the package attempts to cover as many as possible of the functionalities for 
sparse matrix objects that are provided by R’s library [Matrix](http://matrix.r-forge.r-project.org). ([R](https://en.wikipedia.org/wiki/R_(programming_language)) is a implementation of [S](https://en.wikipedia.org/wiki/S_(programming_language)). 
S introduced named data structures for statistical computations, [RB1], hence the name `SSparseMatrix`.)

The package builds on top of the [`scipy` sparse matrices](https://scipy.github.io/devdocs/reference/sparse.html). 
(The added functionalities though are general -- other sparse matrix implementations could be used.)

Here is a list of functionalities provided for `SSparseMatrix`:

- Sub-matrix extraction by row and column names:
   - Single element access
   - Subsets of row names and column names
- Slices (with integers)
- Row and column names propagation for dot products with:
   - Lists
   - Dense vectors (`numpy.array`)
   - `scipy` sparse matrices
   - `SSparseMatrix` objects
- Row and column sums 
   - Vector form
   - Dictionary form
- Transposing
- Representation:
  - Tabular, matrix form ("pretty printing")
  - String and `repr` forms
- Row and column binding of `SSparseMatrix` objects
- "Export" functions
  - Triplets
  - Row-dictionaries
  - Column-dictionaries
  - Wolfram Language full form representation

The full list of features and development status can be found in the 
[org-mode](https://orgmode.org)
file
[SSparseMatrix-work-plan.org](https://github.com/antononcube/Python-packages/blob/main/org/SSparseMatrix-work-plan.org).

This package more or less follows the design of the
Mathematica package
["SSparseMatrix."m"](https://github.com/antononcube/MathematicaForPrediction/blob/master/SSparseMatrix.m), [AAp1], and the corresponding paclet 
["SSparseMatrix"](https://resources.wolframcloud.com/PacletRepository/resources/AntonAntonov/SSparseMatrix/), [AAp3].

The usage examples below can be also run through the file ["examples.py"](./examples.py).

### Usage in other packages

The functionalities provided by "SSparseMatrix" (its class `SSparseMatrix`) 
are fundamental for the packages
["SparseMatrixRecommender"](https://github.com/antononcube/Python-packages/tree/main/SparseMatrixRecommender), [AAp4]
and
["LatentSemanticAnalyzer"](https://github.com/antononcube/Python-packages/tree/main/LatentSemanticAnalyzer). [AAp5],
The implementation of those packages was one of the primary motivations to develop "SSparseMatrix".

The package
["RandomSparseMatrix"](https://github.com/antononcube/Python-packages/tree/main/RandomSparseMatrix)
can be used to generate random sparse matrices (`SSparseMatrix` objects.)

------

## Installation

### Install from GitHub

```shell
pip install -e git+https://github.com/antononcube/Python-packages.git#egg=SSparseMatrix-antononcube\&subdirectory=SSparseMatrix
```

### From PyPi

```shell
pip install SSparseMatrix
```


------

## Setup

Import the package:


```python
from SSparseMatrix import *
```

The import command above is equivalent to the import commands:

```python
from SSparseMatrix.SSparseMatrix import SSparseMatrix
from SSparseMatrix.SSparseMatrix import make_s_sparse_matrix
from SSparseMatrix.SSparseMatrix import is_s_sparse_matrix
from SSparseMatrix.SSparseMatrix import column_bind
```

-----

## Creation

Create a sparse matrix with named rows and columns (a `SSparseMatrix` object):


```python
mat = [[1, 0, 0, 3], [4, 0, 0, 5], [0, 3, 0, 5], [0, 0, 1, 0], [0, 0, 0, 5]]
smat = SSparseMatrix(mat)
smat.set_row_names(["A", "B", "C", "D", "E"])
smat.set_column_names(["a", "b", "c", "d"])
```




    <5x4 SSparseMatrix (sparse matrix with named rows and columns) of type '<class 'numpy.int64'>'
    	with 8 stored elements in Compressed Sparse Row format, and fill-in 0.4>



Print the created sparse matrix:


```python
smat.print_matrix()
```

    ===================================
      |       a       b       c       d
    -----------------------------------
    A |       1       .       .       3
    B |       4       .       .       5
    C |       .       3       .       5
    D |       .       .       1       .
    E |       .       .       .       5
    ===================================


Another way to create using the function `make_s_sparse_matrix`:


```python
ssmat=make_s_sparse_matrix(mat)
ssmat
```




    <5x4 SSparseMatrix (sparse matrix with named rows and columns) of type '<class 'numpy.int64'>'
    	with 8 stored elements in Compressed Sparse Row format, and fill-in 0.4>



------

## Structure

The `SSparseMatrix` objects have a simple structure. Here are the attributes:
- `_sparseMatrix`
- `_rowNames`
- `_colNames`
- `_dimNames`

Here are the methods to "query" `SSparseMatrix` objects:
- `sparse_matrix()`
- `row_names()` and `row_names_dict()`
- `column_names()` and `column_names_dict()`
- `shape()`
- `dimension_names()`

`SSparseMatrix` over-writes the methods of `scipy.sparse.csr_matrix` that might require the handling of row names and column names.

Most of the rest of the `scipy.sparse.csr_matrix`
[methods](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html)
are delegated to the `_sparseMatrix` attribute.

For example, for a given `SSparseMatrix` object `smat` the dense version of `smat`'s sparse matrix attribute
can be obtained by accessing that attribute first and then using the method `todense`:


```python
print(smat.sparse_matrix().todense())
```

    [[1 0 0 3]
     [4 0 0 5]
     [0 3 0 5]
     [0 0 1 0]
     [0 0 0 5]]


Alternatively, we can use the "delegated" form and directly invoke `todense` on `smat`:


```python
print(smat.todense())
```

    [[1 0 0 3]
     [4 0 0 5]
     [0 3 0 5]
     [0 0 1 0]
     [0 0 0 5]]


Here is another example showing a direct application of the element-wise operation `sin` through
the `scipy.sparse.csr_matrix` method `sin`:


```python
smat.sin().print_matrix(n_digits=20)
```

    ===================================================================================
      |                   a                   b                   c                   d
    -----------------------------------------------------------------------------------
    A |  0.8414709848078965                   .                   .  0.1411200080598672
    B | -0.7568024953079282                   .                   . -0.9589242746631385
    C |                   .  0.1411200080598672                   . -0.9589242746631385
    D |                   .                   .  0.8414709848078965                   .
    E |                   .                   .                   . -0.9589242746631385
    ===================================================================================


------
## Representation

Here the function `print` uses the string representation of `SSparseMatrix` object:


```python
print(smat)
```

      ('A', 'a')	1
      ('A', 'd')	3
      ('B', 'a')	4
      ('B', 'd')	5
      ('C', 'b')	3
      ('C', 'd')	5
      ('D', 'c')	1
      ('E', 'd')	5


Here we print the representation obtained with [`repr`](https://docs.python.org/3.4/library/functions.html?highlight=repr#repr):


```python
print(repr(smat))
```

    <5x4 SSparseMatrix (sparse matrix with named rows and columns) of type '<class 'numpy.int64'>'
    	with 8 stored elements in Compressed Sparse Row format, and fill-in 0.4>


Here is the matrix form ("pretty printing" ):


```python
smat.print_matrix()
```

    ===================================
      |       a       b       c       d
    -----------------------------------
    A |       1       .       .       3
    B |       4       .       .       5
    C |       .       3       .       5
    D |       .       .       1       .
    E |       .       .       .       5
    ===================================


The method `triplets` can be used to obtain a list of `(row, column, value)` triplets:


```python
smat.triplets()
```




    [('A', 'a', 1),
     ('A', 'd', 3),
     ('B', 'a', 4),
     ('B', 'd', 5),
     ('C', 'b', 3),
     ('C', 'd', 5),
     ('D', 'c', 1),
     ('E', 'd', 5)]



The method `row_dictionaries` gives a dictionary with keys that are row-names and values that are column-name-to-matrix-value dictionaries:


```python
smat.row_dictionaries()
```




    {'A': {'a': 1, 'd': 3},
     'B': {'a': 4, 'd': 5},
     'C': {'b': 3, 'd': 5},
     'D': {'c': 1},
     'E': {'d': 5}}



Similarly, the method `column_dictionaries` gives a dictionary with keys that are column-names and values that are row-name-to-matrix-value dictionaries:


```python
smat.column_dictionaries()
```




    {'a': {'A': 1, 'B': 4},
     'b': {'C': 3},
     'c': {'D': 1},
     'd': {'A': 3, 'B': 5, 'C': 5, 'E': 5}}



------

## Multiplication

Multiply with the transpose and print:


```python
ssmat2 = ssmat.dot(smat.transpose())
ssmat2.print_matrix()
```

    ===========================================
      |       A       B       C       D       E
    -------------------------------------------
    0 |      10      19      15       .      15
    1 |      19      41      25       .      25
    2 |      15      25      34       .      25
    3 |       .       .       .       1       .
    4 |      15      25      25       .      25
    ===========================================


Multiply with a list-vector:


```python
smat3 = smat.dot([1, 2, 1, 0])
smat3.print_matrix()
```

    ===========
      |       0
    -----------
    A |       1
    B |       4
    C |       6
    D |       1
    E |       .
    ===========


**Remark:** The type of the `.dot` argument can be:
- `SSparseMatrix`
- `list`
- `numpy.array`
- `scipy.sparse.csr_matrix`

------

## Slices

Single element access:


```python
print(smat["A", "d"])
print(smat[0, 3])
```

    3
    3


Get sub-matrix of rows using row names:


```python
smat[["A", "D", "B"], :].print_matrix()
```

    ===================================
      |       a       b       c       d
    -----------------------------------
    A |       1       .       .       3
    D |       .       .       1       .
    B |       4       .       .       5
    ===================================


Get sub-matrix using row indices:


```python
smat[[0, 3, 1], :].print_matrix()
```

    ===================================
      |       a       b       c       d
    -----------------------------------
    A |       1       .       .       3
    D |       .       .       1       .
    B |       4       .       .       5
    ===================================


Get sub-matrix with columns names:


```python
smat[:, ['a', 'c']].print_matrix()
```

    ===================
      |       a       c
    -------------------
    A |       1       .
    B |       4       .
    C |       .       .
    D |       .       1
    E |       .       .
    ===================


Get sub-matrix with columns indices:


```python
smat[:, [0, 2]].print_matrix()
```

    ===================
      |       a       c
    -------------------
    A |       1       .
    B |       4       .
    C |       .       .
    D |       .       1
    E |       .       .
    ===================


**Remark:** The current implementation of `scipy` (1.7.1) does not allow retrieval
of sub-matrices by specifying *both* row and column ranges or slices. 

**Remark:** "Standard" slices with integers also work. 

-------

## Row and column sums

Row sums and dictionary of row sums:


```python
print(smat.row_sums())
print(smat.row_sums_dict())
```

    [4, 9, 8, 1, 5]
    {'A': 4, 'B': 9, 'C': 8, 'D': 1, 'E': 5}


Column sums and dictionary of column sums:


```python
print(smat.column_sums())
print(smat.column_sums_dict())
```

    [5, 3, 1, 18]
    {'a': 5, 'b': 3, 'c': 1, 'd': 18}


------

## Column and row binding

### Column binding

Here we create another `SSparseMatrix` object:


```python
mat2=smat.sparse_matrix().transpose()
smat2 = SSparseMatrix(mat2, row_names=list("ABCD"), column_names="c")
smat2.print_matrix()
```

    ===========================================
      |      c0      c1      c2      c3      c4
    -------------------------------------------
    A |       1       4       .       .       .
    B |       .       .       3       .       .
    C |       .       .       .       1       .
    D |       3       5       5       .       5
    ===========================================


Here we column-bind two SSparseMatrix objects:


```python
smat[list("ABCD"), :].column_bind(smat2).print_matrix()
```

    ===========================================================================
      |       a       b       c       d      c0      c1      c2      c3      c4
    ---------------------------------------------------------------------------
    A |       1       .       .       3       1       4       .       .       .
    B |       4       .       .       5       .       .       3       .       .
    C |       .       3       .       5       .       .       .       1       .
    D |       .       .       1       .       3       5       5       .       5
    ===========================================================================


**Remark:** If during column-binding some column names are duplicated then to the column names of both matrices are
added suffixes that designate to which matrix each column belongs to.

### Row binding

Here we rename the column names of `smat` to be the same as `smat2`:


```python
smat3 = smat.copy()
smat3.set_column_names(smat2.column_names()[0:4])
smat3 = smat3.impose_column_names(smat2.column_names())
smat3.print_matrix()
```

    ===========================================
      |      c0      c1      c2      c3      c4
    -------------------------------------------
    A |       1       .       .       3       .
    B |       4       .       .       5       .
    C |       .       3       .       5       .
    D |       .       .       1       .       .
    E |       .       .       .       5       .
    ===========================================


Here we row-bind `smat2` and `smat3`:


```python
smat2.row_bind(smat3).print_matrix()

```

    =============================================
        |      c0      c1      c2      c3      c4
    ---------------------------------------------
    A.1 |       1       4       .       .       .
    B.1 |       .       .       3       .       .
    C.1 |       .       .       .       1       .
    D.1 |       3       5       5       .       5
    A.2 |       1       .       .       3       .
    B.2 |       4       .       .       5       .
    C.2 |       .       3       .       5       .
    D.2 |       .       .       1       .       .
    E.2 |       .       .       .       5       .
    =============================================


**Remark:** If during row-binding some row names are duplicated then to the row names of both matrices are added
suffixes that designate to which matrix each row belongs to.

------

## In place computations

- The methods for setting row- and column-names are "in place" methods -- no new `SSparseMatrix` objects a created.

- The dot product, arithmetic, and transposing methods have an optional argument whether to do computations in place or not.
    - The optional argument is `copy`, which corresponds to argument with the same name and function in `scipy.sparse`.
    - By default, the computations are *not* in place: new objects are created.
    - I.e. `copy=True` default.

- The class `SSparseMatrix` has the method `copy()` that produces deep copies when invoked.

-------

## Unit tests

The unit tests (so far) are broken into functionalities; see the folder
[./tests](https://github.com/antononcube/Python-packages/tree/main/SSparseMatrix/tests).
Similar unit tests are given in [AAp2].

-------

## References

### Articles

[AA1] Anton Antonov,
["RSparseMatrix for sparse matrices with named rows and columns"](https://mathematicaforprediction.wordpress.com/2015/10/08/rsparsematrix-for-sparse-matrices-with-named-rows-and-columns/),
(2015),
[MathematicaForPrediction at WordPress](https://mathematicaforprediction.wordpress.com).

[RB1] Richard Becker, 
[“A Brief History of S”](https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.131.1428&rep=rep1&type=pdf),
(2004).

### Packages

[AAp1] Anton Antonov,
[SSparseMatrix.m](https://github.com/antononcube/MathematicaForPrediction/blob/master/SSparseMatrix.m),
(2018),
[MathematicaForPrediction at GitHub](https://github.com/antononcube/MathematicaForPrediction).

[AAp2] Anton Antonov,
[SSparseMatrix Mathematica unit tests](https://github.com/antononcube/MathematicaForPrediction/blob/master/UnitTests/SSparseMatrix-tests.wlt),
(2018),
[MathematicaForPrediction at GitHub](https://github.com/antononcube/MathematicaForPrediction).

[AAp3] Anton Antonov,
[SSparseMatrix WL paclet](https://resources.wolframcloud.com/PacletRepository/resources/AntonAntonov/SSparseMatrix/),
(2023),
[Wolfram Language Paclet Repository](https://resources.wolframcloud.com/PacletRepository/).

[AAp4] Anton Antonov,
[SparseMatrixRecommender Python package](https://pypi.org/project/SparseMatrixRecommender/),
(2021),
[PyPI.org/antononcube](https://pypi.org/user/antononcube/).

[AAp4] Anton Antonov,
[LatentSemanticAnalyzer Python package](https://pypi.org/project/LatentSemanticAnalyzer/),
(2021),
[PyPI.org/antononcube](https://pypi.org/user/antononcube/).


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/antononcube/Python-packages/tree/main/SSparseMatrix",
    "name": "SSparseMatrix",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "sparse,matrix,r,s,s-plus,linear algebra,linear,algebra,row names,column names,named rows,named columns",
    "author": "Anton Antonov",
    "author_email": "antononcube@posteo.net",
    "download_url": "https://files.pythonhosted.org/packages/9a/25/3dc244064b05032b12c3e081c1153bbbc797360c245f42ee6ff4b237bbe4/SSparseMatrix-0.3.4.tar.gz",
    "platform": null,
    "description": "# Sparse matrices with named rows and columns\n\n![PyPI](https://img.shields.io/pypi/v/SSparseMatrix?label=pypi%20SSparseMatrix)\n![PyPI - Downloads](https://img.shields.io/pypi/dm/SSparseMatrix)\n\nPePy:   \n[![Downloads](https://static.pepy.tech/badge/SSparseMatrix)](https://pepy.tech/project/SSparseMatrix)\n[![Downloads](https://static.pepy.tech/badge/SSparseMatrix/month)](https://pepy.tech/project/SSparseMatrix)\n[![Downloads](https://static.pepy.tech/badge/SSparseMatrix/week)](https://pepy.tech/project/SSparseMatrix)\n\n\n## Introduction\n\nThis Python package provides the class `SSparseMatrix` the objects of which are sparse matrices with named rows and columns.\n\nWe can say the package attempts to cover as many as possible of the functionalities for \nsparse matrix objects that are provided by R\u2019s library [Matrix](http://matrix.r-forge.r-project.org). ([R](https://en.wikipedia.org/wiki/R_(programming_language)) is a implementation of [S](https://en.wikipedia.org/wiki/S_(programming_language)). \nS introduced named data structures for statistical computations, [RB1], hence the name `SSparseMatrix`.)\n\nThe package builds on top of the [`scipy` sparse matrices](https://scipy.github.io/devdocs/reference/sparse.html). \n(The added functionalities though are general -- other sparse matrix implementations could be used.)\n\nHere is a list of functionalities provided for `SSparseMatrix`:\n\n- Sub-matrix extraction by row and column names:\n   - Single element access\n   - Subsets of row names and column names\n- Slices (with integers)\n- Row and column names propagation for dot products with:\n   - Lists\n   - Dense vectors (`numpy.array`)\n   - `scipy` sparse matrices\n   - `SSparseMatrix` objects\n- Row and column sums \n   - Vector form\n   - Dictionary form\n- Transposing\n- Representation:\n  - Tabular, matrix form (\"pretty printing\")\n  - String and `repr` forms\n- Row and column binding of `SSparseMatrix` objects\n- \"Export\" functions\n  - Triplets\n  - Row-dictionaries\n  - Column-dictionaries\n  - Wolfram Language full form representation\n\nThe full list of features and development status can be found in the \n[org-mode](https://orgmode.org)\nfile\n[SSparseMatrix-work-plan.org](https://github.com/antononcube/Python-packages/blob/main/org/SSparseMatrix-work-plan.org).\n\nThis package more or less follows the design of the\nMathematica package\n[\"SSparseMatrix.\"m\"](https://github.com/antononcube/MathematicaForPrediction/blob/master/SSparseMatrix.m), [AAp1], and the corresponding paclet \n[\"SSparseMatrix\"](https://resources.wolframcloud.com/PacletRepository/resources/AntonAntonov/SSparseMatrix/), [AAp3].\n\nThe usage examples below can be also run through the file [\"examples.py\"](./examples.py).\n\n### Usage in other packages\n\nThe functionalities provided by \"SSparseMatrix\" (its class `SSparseMatrix`) \nare fundamental for the packages\n[\"SparseMatrixRecommender\"](https://github.com/antononcube/Python-packages/tree/main/SparseMatrixRecommender), [AAp4]\nand\n[\"LatentSemanticAnalyzer\"](https://github.com/antononcube/Python-packages/tree/main/LatentSemanticAnalyzer). [AAp5],\nThe implementation of those packages was one of the primary motivations to develop \"SSparseMatrix\".\n\nThe package\n[\"RandomSparseMatrix\"](https://github.com/antononcube/Python-packages/tree/main/RandomSparseMatrix)\ncan be used to generate random sparse matrices (`SSparseMatrix` objects.)\n\n------\n\n## Installation\n\n### Install from GitHub\n\n```shell\npip install -e git+https://github.com/antononcube/Python-packages.git#egg=SSparseMatrix-antononcube\\&subdirectory=SSparseMatrix\n```\n\n### From PyPi\n\n```shell\npip install SSparseMatrix\n```\n\n\n------\n\n## Setup\n\nImport the package:\n\n\n```python\nfrom SSparseMatrix import *\n```\n\nThe import command above is equivalent to the import commands:\n\n```python\nfrom SSparseMatrix.SSparseMatrix import SSparseMatrix\nfrom SSparseMatrix.SSparseMatrix import make_s_sparse_matrix\nfrom SSparseMatrix.SSparseMatrix import is_s_sparse_matrix\nfrom SSparseMatrix.SSparseMatrix import column_bind\n```\n\n-----\n\n## Creation\n\nCreate a sparse matrix with named rows and columns (a `SSparseMatrix` object):\n\n\n```python\nmat = [[1, 0, 0, 3], [4, 0, 0, 5], [0, 3, 0, 5], [0, 0, 1, 0], [0, 0, 0, 5]]\nsmat = SSparseMatrix(mat)\nsmat.set_row_names([\"A\", \"B\", \"C\", \"D\", \"E\"])\nsmat.set_column_names([\"a\", \"b\", \"c\", \"d\"])\n```\n\n\n\n\n    <5x4 SSparseMatrix (sparse matrix with named rows and columns) of type '<class 'numpy.int64'>'\n    \twith 8 stored elements in Compressed Sparse Row format, and fill-in 0.4>\n\n\n\nPrint the created sparse matrix:\n\n\n```python\nsmat.print_matrix()\n```\n\n    ===================================\n      |       a       b       c       d\n    -----------------------------------\n    A |       1       .       .       3\n    B |       4       .       .       5\n    C |       .       3       .       5\n    D |       .       .       1       .\n    E |       .       .       .       5\n    ===================================\n\n\nAnother way to create using the function `make_s_sparse_matrix`:\n\n\n```python\nssmat=make_s_sparse_matrix(mat)\nssmat\n```\n\n\n\n\n    <5x4 SSparseMatrix (sparse matrix with named rows and columns) of type '<class 'numpy.int64'>'\n    \twith 8 stored elements in Compressed Sparse Row format, and fill-in 0.4>\n\n\n\n------\n\n## Structure\n\nThe `SSparseMatrix` objects have a simple structure. Here are the attributes:\n- `_sparseMatrix`\n- `_rowNames`\n- `_colNames`\n- `_dimNames`\n\nHere are the methods to \"query\" `SSparseMatrix` objects:\n- `sparse_matrix()`\n- `row_names()` and `row_names_dict()`\n- `column_names()` and `column_names_dict()`\n- `shape()`\n- `dimension_names()`\n\n`SSparseMatrix` over-writes the methods of `scipy.sparse.csr_matrix` that might require the handling of row names and column names.\n\nMost of the rest of the `scipy.sparse.csr_matrix`\n[methods](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html)\nare delegated to the `_sparseMatrix` attribute.\n\nFor example, for a given `SSparseMatrix` object `smat` the dense version of `smat`'s sparse matrix attribute\ncan be obtained by accessing that attribute first and then using the method `todense`:\n\n\n```python\nprint(smat.sparse_matrix().todense())\n```\n\n    [[1 0 0 3]\n     [4 0 0 5]\n     [0 3 0 5]\n     [0 0 1 0]\n     [0 0 0 5]]\n\n\nAlternatively, we can use the \"delegated\" form and directly invoke `todense` on `smat`:\n\n\n```python\nprint(smat.todense())\n```\n\n    [[1 0 0 3]\n     [4 0 0 5]\n     [0 3 0 5]\n     [0 0 1 0]\n     [0 0 0 5]]\n\n\nHere is another example showing a direct application of the element-wise operation `sin` through\nthe `scipy.sparse.csr_matrix` method `sin`:\n\n\n```python\nsmat.sin().print_matrix(n_digits=20)\n```\n\n    ===================================================================================\n      |                   a                   b                   c                   d\n    -----------------------------------------------------------------------------------\n    A |  0.8414709848078965                   .                   .  0.1411200080598672\n    B | -0.7568024953079282                   .                   . -0.9589242746631385\n    C |                   .  0.1411200080598672                   . -0.9589242746631385\n    D |                   .                   .  0.8414709848078965                   .\n    E |                   .                   .                   . -0.9589242746631385\n    ===================================================================================\n\n\n------\n## Representation\n\nHere the function `print` uses the string representation of `SSparseMatrix` object:\n\n\n```python\nprint(smat)\n```\n\n      ('A', 'a')\t1\n      ('A', 'd')\t3\n      ('B', 'a')\t4\n      ('B', 'd')\t5\n      ('C', 'b')\t3\n      ('C', 'd')\t5\n      ('D', 'c')\t1\n      ('E', 'd')\t5\n\n\nHere we print the representation obtained with [`repr`](https://docs.python.org/3.4/library/functions.html?highlight=repr#repr):\n\n\n```python\nprint(repr(smat))\n```\n\n    <5x4 SSparseMatrix (sparse matrix with named rows and columns) of type '<class 'numpy.int64'>'\n    \twith 8 stored elements in Compressed Sparse Row format, and fill-in 0.4>\n\n\nHere is the matrix form (\"pretty printing\" ):\n\n\n```python\nsmat.print_matrix()\n```\n\n    ===================================\n      |       a       b       c       d\n    -----------------------------------\n    A |       1       .       .       3\n    B |       4       .       .       5\n    C |       .       3       .       5\n    D |       .       .       1       .\n    E |       .       .       .       5\n    ===================================\n\n\nThe method `triplets` can be used to obtain a list of `(row, column, value)` triplets:\n\n\n```python\nsmat.triplets()\n```\n\n\n\n\n    [('A', 'a', 1),\n     ('A', 'd', 3),\n     ('B', 'a', 4),\n     ('B', 'd', 5),\n     ('C', 'b', 3),\n     ('C', 'd', 5),\n     ('D', 'c', 1),\n     ('E', 'd', 5)]\n\n\n\nThe method `row_dictionaries` gives a dictionary with keys that are row-names and values that are column-name-to-matrix-value dictionaries:\n\n\n```python\nsmat.row_dictionaries()\n```\n\n\n\n\n    {'A': {'a': 1, 'd': 3},\n     'B': {'a': 4, 'd': 5},\n     'C': {'b': 3, 'd': 5},\n     'D': {'c': 1},\n     'E': {'d': 5}}\n\n\n\nSimilarly, the method `column_dictionaries` gives a dictionary with keys that are column-names and values that are row-name-to-matrix-value dictionaries:\n\n\n```python\nsmat.column_dictionaries()\n```\n\n\n\n\n    {'a': {'A': 1, 'B': 4},\n     'b': {'C': 3},\n     'c': {'D': 1},\n     'd': {'A': 3, 'B': 5, 'C': 5, 'E': 5}}\n\n\n\n------\n\n## Multiplication\n\nMultiply with the transpose and print:\n\n\n```python\nssmat2 = ssmat.dot(smat.transpose())\nssmat2.print_matrix()\n```\n\n    ===========================================\n      |       A       B       C       D       E\n    -------------------------------------------\n    0 |      10      19      15       .      15\n    1 |      19      41      25       .      25\n    2 |      15      25      34       .      25\n    3 |       .       .       .       1       .\n    4 |      15      25      25       .      25\n    ===========================================\n\n\nMultiply with a list-vector:\n\n\n```python\nsmat3 = smat.dot([1, 2, 1, 0])\nsmat3.print_matrix()\n```\n\n    ===========\n      |       0\n    -----------\n    A |       1\n    B |       4\n    C |       6\n    D |       1\n    E |       .\n    ===========\n\n\n**Remark:** The type of the `.dot` argument can be:\n- `SSparseMatrix`\n- `list`\n- `numpy.array`\n- `scipy.sparse.csr_matrix`\n\n------\n\n## Slices\n\nSingle element access:\n\n\n```python\nprint(smat[\"A\", \"d\"])\nprint(smat[0, 3])\n```\n\n    3\n    3\n\n\nGet sub-matrix of rows using row names:\n\n\n```python\nsmat[[\"A\", \"D\", \"B\"], :].print_matrix()\n```\n\n    ===================================\n      |       a       b       c       d\n    -----------------------------------\n    A |       1       .       .       3\n    D |       .       .       1       .\n    B |       4       .       .       5\n    ===================================\n\n\nGet sub-matrix using row indices:\n\n\n```python\nsmat[[0, 3, 1], :].print_matrix()\n```\n\n    ===================================\n      |       a       b       c       d\n    -----------------------------------\n    A |       1       .       .       3\n    D |       .       .       1       .\n    B |       4       .       .       5\n    ===================================\n\n\nGet sub-matrix with columns names:\n\n\n```python\nsmat[:, ['a', 'c']].print_matrix()\n```\n\n    ===================\n      |       a       c\n    -------------------\n    A |       1       .\n    B |       4       .\n    C |       .       .\n    D |       .       1\n    E |       .       .\n    ===================\n\n\nGet sub-matrix with columns indices:\n\n\n```python\nsmat[:, [0, 2]].print_matrix()\n```\n\n    ===================\n      |       a       c\n    -------------------\n    A |       1       .\n    B |       4       .\n    C |       .       .\n    D |       .       1\n    E |       .       .\n    ===================\n\n\n**Remark:** The current implementation of `scipy` (1.7.1) does not allow retrieval\nof sub-matrices by specifying *both* row and column ranges or slices. \n\n**Remark:** \"Standard\" slices with integers also work. \n\n-------\n\n## Row and column sums\n\nRow sums and dictionary of row sums:\n\n\n```python\nprint(smat.row_sums())\nprint(smat.row_sums_dict())\n```\n\n    [4, 9, 8, 1, 5]\n    {'A': 4, 'B': 9, 'C': 8, 'D': 1, 'E': 5}\n\n\nColumn sums and dictionary of column sums:\n\n\n```python\nprint(smat.column_sums())\nprint(smat.column_sums_dict())\n```\n\n    [5, 3, 1, 18]\n    {'a': 5, 'b': 3, 'c': 1, 'd': 18}\n\n\n------\n\n## Column and row binding\n\n### Column binding\n\nHere we create another `SSparseMatrix` object:\n\n\n```python\nmat2=smat.sparse_matrix().transpose()\nsmat2 = SSparseMatrix(mat2, row_names=list(\"ABCD\"), column_names=\"c\")\nsmat2.print_matrix()\n```\n\n    ===========================================\n      |      c0      c1      c2      c3      c4\n    -------------------------------------------\n    A |       1       4       .       .       .\n    B |       .       .       3       .       .\n    C |       .       .       .       1       .\n    D |       3       5       5       .       5\n    ===========================================\n\n\nHere we column-bind two SSparseMatrix objects:\n\n\n```python\nsmat[list(\"ABCD\"), :].column_bind(smat2).print_matrix()\n```\n\n    ===========================================================================\n      |       a       b       c       d      c0      c1      c2      c3      c4\n    ---------------------------------------------------------------------------\n    A |       1       .       .       3       1       4       .       .       .\n    B |       4       .       .       5       .       .       3       .       .\n    C |       .       3       .       5       .       .       .       1       .\n    D |       .       .       1       .       3       5       5       .       5\n    ===========================================================================\n\n\n**Remark:** If during column-binding some column names are duplicated then to the column names of both matrices are\nadded suffixes that designate to which matrix each column belongs to.\n\n### Row binding\n\nHere we rename the column names of `smat` to be the same as `smat2`:\n\n\n```python\nsmat3 = smat.copy()\nsmat3.set_column_names(smat2.column_names()[0:4])\nsmat3 = smat3.impose_column_names(smat2.column_names())\nsmat3.print_matrix()\n```\n\n    ===========================================\n      |      c0      c1      c2      c3      c4\n    -------------------------------------------\n    A |       1       .       .       3       .\n    B |       4       .       .       5       .\n    C |       .       3       .       5       .\n    D |       .       .       1       .       .\n    E |       .       .       .       5       .\n    ===========================================\n\n\nHere we row-bind `smat2` and `smat3`:\n\n\n```python\nsmat2.row_bind(smat3).print_matrix()\n\n```\n\n    =============================================\n        |      c0      c1      c2      c3      c4\n    ---------------------------------------------\n    A.1 |       1       4       .       .       .\n    B.1 |       .       .       3       .       .\n    C.1 |       .       .       .       1       .\n    D.1 |       3       5       5       .       5\n    A.2 |       1       .       .       3       .\n    B.2 |       4       .       .       5       .\n    C.2 |       .       3       .       5       .\n    D.2 |       .       .       1       .       .\n    E.2 |       .       .       .       5       .\n    =============================================\n\n\n**Remark:** If during row-binding some row names are duplicated then to the row names of both matrices are added\nsuffixes that designate to which matrix each row belongs to.\n\n------\n\n## In place computations\n\n- The methods for setting row- and column-names are \"in place\" methods -- no new `SSparseMatrix` objects a created.\n\n- The dot product, arithmetic, and transposing methods have an optional argument whether to do computations in place or not.\n    - The optional argument is `copy`, which corresponds to argument with the same name and function in `scipy.sparse`.\n    - By default, the computations are *not* in place: new objects are created.\n    - I.e. `copy=True` default.\n\n- The class `SSparseMatrix` has the method `copy()` that produces deep copies when invoked.\n\n-------\n\n## Unit tests\n\nThe unit tests (so far) are broken into functionalities; see the folder\n[./tests](https://github.com/antononcube/Python-packages/tree/main/SSparseMatrix/tests).\nSimilar unit tests are given in [AAp2].\n\n-------\n\n## References\n\n### Articles\n\n[AA1] Anton Antonov,\n[\"RSparseMatrix for sparse matrices with named rows and columns\"](https://mathematicaforprediction.wordpress.com/2015/10/08/rsparsematrix-for-sparse-matrices-with-named-rows-and-columns/),\n(2015),\n[MathematicaForPrediction at WordPress](https://mathematicaforprediction.wordpress.com).\n\n[RB1] Richard Becker, \n[\u201cA Brief History of S\u201d](https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.131.1428&rep=rep1&type=pdf),\n(2004).\n\n### Packages\n\n[AAp1] Anton Antonov,\n[SSparseMatrix.m](https://github.com/antononcube/MathematicaForPrediction/blob/master/SSparseMatrix.m),\n(2018),\n[MathematicaForPrediction at GitHub](https://github.com/antononcube/MathematicaForPrediction).\n\n[AAp2] Anton Antonov,\n[SSparseMatrix Mathematica unit tests](https://github.com/antononcube/MathematicaForPrediction/blob/master/UnitTests/SSparseMatrix-tests.wlt),\n(2018),\n[MathematicaForPrediction at GitHub](https://github.com/antononcube/MathematicaForPrediction).\n\n[AAp3] Anton Antonov,\n[SSparseMatrix WL paclet](https://resources.wolframcloud.com/PacletRepository/resources/AntonAntonov/SSparseMatrix/),\n(2023),\n[Wolfram Language Paclet Repository](https://resources.wolframcloud.com/PacletRepository/).\n\n[AAp4] Anton Antonov,\n[SparseMatrixRecommender Python package](https://pypi.org/project/SparseMatrixRecommender/),\n(2021),\n[PyPI.org/antononcube](https://pypi.org/user/antononcube/).\n\n[AAp4] Anton Antonov,\n[LatentSemanticAnalyzer Python package](https://pypi.org/project/LatentSemanticAnalyzer/),\n(2021),\n[PyPI.org/antononcube](https://pypi.org/user/antononcube/).\n\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "SSparseMatrix package based on SciPy sparse matrices.",
    "version": "0.3.4",
    "project_urls": {
        "Homepage": "https://github.com/antononcube/Python-packages/tree/main/SSparseMatrix"
    },
    "split_keywords": [
        "sparse",
        "matrix",
        "r",
        "s",
        "s-plus",
        "linear algebra",
        "linear",
        "algebra",
        "row names",
        "column names",
        "named rows",
        "named columns"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "70f2cbd9281e10bdf6a6a481c740f3722be3e32f24b77fe9e3ffbcb71fafd5eb",
                "md5": "d255d71d7ea0572f0a7f4917123f6d45",
                "sha256": "9cdbbaf85bd767c8222aab29cfb5658ca08756c708909ca6f98d44f26364a1e2"
            },
            "downloads": -1,
            "filename": "SSparseMatrix-0.3.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d255d71d7ea0572f0a7f4917123f6d45",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 14157,
            "upload_time": "2023-10-20T13:56:19",
            "upload_time_iso_8601": "2023-10-20T13:56:19.871540Z",
            "url": "https://files.pythonhosted.org/packages/70/f2/cbd9281e10bdf6a6a481c740f3722be3e32f24b77fe9e3ffbcb71fafd5eb/SSparseMatrix-0.3.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9a253dc244064b05032b12c3e081c1153bbbc797360c245f42ee6ff4b237bbe4",
                "md5": "038d798d5b98af6d77c0838c2c984c20",
                "sha256": "e32529da7fa83fe6dd998b35859f65820b3b94e24097486e4c1afee7d7d59299"
            },
            "downloads": -1,
            "filename": "SSparseMatrix-0.3.4.tar.gz",
            "has_sig": false,
            "md5_digest": "038d798d5b98af6d77c0838c2c984c20",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 18724,
            "upload_time": "2023-10-20T13:56:21",
            "upload_time_iso_8601": "2023-10-20T13:56:21.090642Z",
            "url": "https://files.pythonhosted.org/packages/9a/25/3dc244064b05032b12c3e081c1153bbbc797360c245f42ee6ff4b237bbe4/SSparseMatrix-0.3.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-20 13:56:21",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "antononcube",
    "github_project": "Python-packages",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "ssparsematrix"
}
        
Elapsed time: 0.13965s