.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/vietoris_rips/plot_submatrix_index_tool.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_vietoris_rips_plot_submatrix_index_tool.py: .. _vietoris_submatrix_index_tool: Submatrix Index Tool ======================================== A common pain point in computational homological algebra is passing between matrix and integer indices for boundary and other matrices. OAT offers a :class:`oat_python.core.vietoris_rips.SubmatrixIndexTool` to help wth this. .. GENERATED FROM PYTHON SOURCE LINES 13-21 See also ------------------------------- See the :ref:`vietoris_rips_matrices` gallery for more examples! Setup ------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 24-33 .. code-block:: Python import oat_python as oat from fractions import Fraction import matplotlib.pyplot as plt import numpy as np import pandas as pd import plotly.graph_objects as go from scipy.sparse import csr_matrix .. GENERATED FROM PYTHON SOURCE LINES 34-35 Generate a point cloud .. GENERATED FROM PYTHON SOURCE LINES 35-38 .. code-block:: Python points = oat.point_cloud.sphere_or_slice(n_points=100) .. GENERATED FROM PYTHON SOURCE LINES 39-40 Plot the point cloud .. GENERATED FROM PYTHON SOURCE LINES 40-45 .. code-block:: Python trace = go.Scatter3d(x=points[:,0],y=points[:,1],z=points[:,2], mode="markers", marker=dict(opacity=1, size=4, color=points[:,2], colorscale="Aggrnyl")) fig = go.Figure(data=trace) fig.update_layout(title=dict(text="Point cloud"), height=800,width=850) fig .. raw:: html


.. GENERATED FROM PYTHON SOURCE LINES 46-48 Compute persistent homology ------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 50-51 We compute persistent homology by factoring the boundary matrix. The following cell generates a sparse distance matrix and feeds it to the persistent homology solver. The result is a decomposition boundary matrix. We will extract information from this matrix in the following cells. .. GENERATED FROM PYTHON SOURCE LINES 53-54 Prepare a dissimilarity matrix .. GENERATED FROM PYTHON SOURCE LINES 54-60 .. code-block:: Python dissimilarity_matrix = oat.dissimilarity.sparse_matrix_for_points( points = points, max_dissimilarity = 0.5, ) .. GENERATED FROM PYTHON SOURCE LINES 61-62 Create and decompose the boundary matrix .. GENERATED FROM PYTHON SOURCE LINES 62-68 .. code-block:: Python decomposition = oat.core.vietoris_rips.BoundaryMatrixDecomposition( dissimilarity_matrix = dissimilarity_matrix, max_homology_dimension = 1, ) .. GENERATED FROM PYTHON SOURCE LINES 69-73 Access indices ------------------------------------ .. GENERATED FROM PYTHON SOURCE LINES 75-76 Create a `oat_python.core.vietoris_rips.SubmatrixIndexTool` whose rows and columns are the vertices and edges of the Vietoris-Rips complex, respectively. .. GENERATED FROM PYTHON SOURCE LINES 78-84 .. code-block:: Python submatrix_index_tool = decomposition.submatrix_index_tool( row_dimensions = [0,], column_dimensions = [1,] ) submatrix_index_tool .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 85-86 The number of row and column indices can be accessed via lookup functions: .. GENERATED FROM PYTHON SOURCE LINES 88-90 .. code-block:: Python submatrix_index_tool.number_of_rows() .. rst-class:: sphx-glr-script-out .. code-block:: none 100 .. GENERATED FROM PYTHON SOURCE LINES 91-93 .. code-block:: Python submatrix_index_tool.number_of_columns() .. rst-class:: sphx-glr-script-out .. code-block:: none 292 .. GENERATED FROM PYTHON SOURCE LINES 94-95 The (ordered) lists of row and column indices can also be exported to dataframe format, for inspection: .. GENERATED FROM PYTHON SOURCE LINES 97-103 .. code-block:: Python oat.plot.display_dataframes_side_by_side( submatrix_index_tool.row_indices()[:5], submatrix_index_tool.column_indices()[:5], titles=["Row indices (vertices)","Column indices (edges)"] ) .. raw:: html

Row indices (vertices)

simplex filtration
0 (0,) 0.0
1 (1,) 0.0
2 (2,) 0.0
3 (3,) 0.0
4 (4,) 0.0

Column indices (edges)

simplex filtration
0 (0, 1) 0.200000
1 (96, 99) 0.220606
2 (98, 99) 0.272721
3 (0, 2) 0.282843
4 (1, 4) 0.319210


.. GENERATED FROM PYTHON SOURCE LINES 104-108 Write a submatrix to CSR ---------------------------------- A common task in data analysis is to export a submatrix of the boundary matrix into standard Python sparse matrix format, such as SciPy's CSR. In order to do this, you have to specify which rows and columns you want, and in what order. The :class:`oat_python.core.vietoris_rips.SubmatrixIndexTool` lets you specify these criteria exactly. .. GENERATED FROM PYTHON SOURCE LINES 110-116 .. code-block:: Python boundary_matrix = decomposition.boundary_matrix_oracle() boundary_submatrix = boundary_matrix.write_submatrix_to_csr( submatrix_index_tool ) boundary_submatrix .. rst-class:: sphx-glr-script-out .. code-block:: none <100x292 sparse matrix of type '' with 584 stored elements in Compressed Sparse Row format> .. GENERATED FROM PYTHON SOURCE LINES 117-122 .. code-block:: Python plt.figure(figsize=(6, 6)) plt.spy(boundary_submatrix, markersize=2, color="orange") plt.title(r'Boundary Matrix ($\partial_1$)', y=-0.18) # Move title to the bottom plt.tight_layout() .. image-sg:: /auto_examples/vietoris_rips/images/sphx_glr_plot_submatrix_index_tool_001.png :alt: Boundary Matrix ($\partial_1$) :srcset: /auto_examples/vietoris_rips/images/sphx_glr_plot_submatrix_index_tool_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_fontconfig_pattern.py:85: PyparsingDeprecationWarning: 'parseString' deprecated - use 'parse_string' parse = parser.parseString(pattern) /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_fontconfig_pattern.py:89: PyparsingDeprecationWarning: 'resetCache' deprecated - use 'reset_cache' parser.resetCache() /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:2010: PyparsingDeprecationWarning: 'oneOf' deprecated - use 'one_of' p.space = oneOf(self._space_widths)("space") /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:2012: PyparsingDeprecationWarning: 'oneOf' deprecated - use 'one_of' p.style_literal = oneOf( /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:2015: PyparsingDeprecationWarning: 'leaveWhitespace' deprecated - use 'leave_whitespace' p.symbol = Regex( /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:2024: PyparsingDeprecationWarning: 'oneOf' deprecated - use 'one_of' p.start_group = Optional(r"\math" + oneOf(self._fontnames)("font")) + "{" /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:2027: PyparsingDeprecationWarning: 'oneOf' deprecated - use 'one_of' p.delim = oneOf(self._delims) /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:1984: PyparsingDeprecationWarning: 'setName' deprecated - use 'set_name' val.setName(key) /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:1987: PyparsingDeprecationWarning: 'setParseAction' deprecated - use 'set_parse_action' val.setParseAction(getattr(self, key)) /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:1748: PyparsingDeprecationWarning: 'setParseAction' deprecated - use 'set_parse_action' return Empty().setParseAction(raise_error) /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:2088: PyparsingDeprecationWarning: 'endQuoteChar' argument is deprecated, use 'end_quote_char' p.text = cmd(r"\text", QuotedString('{', '\\', endQuoteChar="}")) /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:2097: PyparsingDeprecationWarning: 'oneOf' deprecated - use 'one_of' + OneOrMore(oneOf(["_", "^"]) - p.placeable)("subsuper") /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:2146: PyparsingDeprecationWarning: 'unquoteResults' argument is deprecated, use 'unquote_results' p.math_string = QuotedString('$', '\\', unquoteResults=False) /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:2147: PyparsingDeprecationWarning: 'leaveWhitespace' deprecated - use 'leave_whitespace' p.non_math = Regex(r"(?:(?:\\[$])|[^$])*").leaveWhitespace() /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:2170: PyparsingDeprecationWarning: 'parseString' deprecated - use 'parse_string' result = self._expression.parseString(s) /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:2197: PyparsingDeprecationWarning: 'parseString' deprecated - use 'parse_string' return self._math_expression.parseString(toks[0][1:-1], parseAll=True) /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/pyparsing/util.py:466: PyparsingDeprecationWarning: 'parseAll' argument is deprecated, use 'parse_all' return fn(self, *args, **kwargs) /home/docs/checkouts/readthedocs.org/user_builds/oat-python/envs/latest/lib/python3.9/site-packages/matplotlib/_mathtext.py:2178: PyparsingDeprecationWarning: 'resetCache' deprecated - use 'reset_cache' ParserElement.resetCache() .. GENERATED FROM PYTHON SOURCE LINES 123-125 Change index types ---------------------------------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 127-128 Get a row vector from the CSR matrix .. GENERATED FROM PYTHON SOURCE LINES 128-134 .. code-block:: Python # Right now we have to convert row coefficients to fractions, but in the future this will be taken care of automatically row_vector = boundary_submatrix[0].toarray().flatten() row_vector = np.vectorize(Fraction.from_float)(row_vector) row_vector[:10] .. rst-class:: sphx-glr-script-out .. code-block:: none array([Fraction(-1, 1), Fraction(0, 1), Fraction(0, 1), Fraction(-1, 1), Fraction(0, 1), Fraction(0, 1), Fraction(0, 1), Fraction(0, 1), Fraction(0, 1), Fraction(0, 1)], dtype=object) .. GENERATED FROM PYTHON SOURCE LINES 135-136 Convert integer indices to simplex indices: .. GENERATED FROM PYTHON SOURCE LINES 138-144 .. code-block:: Python chain = submatrix_index_tool.row_vector_dataframe_for_dense_array( row_vector ) chain .. raw:: html
simplex filtration coefficient
0 (0, 1) 0.200000 -1
1 (0, 2) 0.282843 -1
2 (0, 3) 0.346410 -1
3 (0, 4) 0.400000 -1
4 (0, 5) 0.447214 -1
5 (0, 6) 0.489898 -1


.. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.228 seconds) .. _sphx_glr_download_auto_examples_vietoris_rips_plot_submatrix_index_tool.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_submatrix_index_tool.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_submatrix_index_tool.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_submatrix_index_tool.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_