In this notebook we explore a few of the core features included in `giotto-tda`

's implementation of the Mapper algorithm.

If you are looking at a static version of this notebook and would like to run its contents, head over to github.

- An introduction to Topological Data Analysis: fundamental and practical aspects for data scientists
- An Introduction to Topological Data Analysis for Physicists: From LGM to FRBs

**License: AGPLv3**

In [ ]:

```
# Data wrangling
import numpy as np
import pandas as pd # Not a requirement of giotto-tda, but is compatible with the gtda.mapper module
# Data viz
from gtda.plotting import plot_point_cloud
# TDA magic
from gtda.mapper import (
CubicalCover,
make_mapper_pipeline,
Projection,
plot_static_mapper_graph,
plot_interactive_mapper_graph,
)
from gtda.mapper.utils.visualization import set_node_sizeref
# ML tools
from sklearn import datasets
from sklearn.cluster import DBSCAN
from sklearn.decomposition import PCA
```

As a simple example, let's generate a two-dimensional point cloud of two concentric circles. The goal will be to examine how Mapper can be used to generate a topological graph that captures the salient features of the data.

In [ ]:

```
data, _ = datasets.make_circles(n_samples=5000, noise=0.05, factor=0.3, random_state=42)
plot_point_cloud(data)
```

Given a dataset ${\cal D}$ of points $x \in \mathbb{R}^n$, the basic steps behind Mapper are as follows:

- Map ${\cal D}$ to a lower-dimensional space using a
**filter function**$f: \mathbb{R}^n \to \mathbb{R}^m$. Common choices for the filter function include projection onto one or more axes via PCA or density-based methods. In`giotto-tda`

, you can import a variety of filter functions as follows:

```
from gtda.mapper.filter import FilterFunctionName
```

- Construct a cover of the filter values ${\cal U} = (U_i)_{i\in I}$, typically in the form of a set of overlapping intervals which have constant length. As with the filter, a choice of cover can be imported as follows:

```
from gtda.mapper.cover import CoverName
```

- For each interval $U_i \in {\cal U}$ cluster the points in the preimage $f^{-1}(U_i)$ into sets $C_{i,1}, \ldots , C_{i,k_i}$. The choice of clustering algorithm can be any of
`scikit-learn`

's clustering methods or an implementation of agglomerative clustering in`giotto-tda`

:

```
# scikit-learn method
from sklearn.cluster import ClusteringAlgorithm
# giotto-tda method
from gtda.mapper.cluster import FirstSimpleGap
```

- Construct the topological graph whose vertices are the cluster sets $(C_{i,j})_{i\in I, j \in \{1,\ldots,k_i\}}$ and an edge exists between two nodes if they share points in common: $C_{i,j} \cap C_{k,l} \neq \emptyset$. This step is handled automatically by
`giotto-tda`

.

These four steps are implemented in the `MapperPipeline`

object that mimics the `Pipeline`

class from `scikit-learn`

. We provide a convenience function `make_mapper_pipeline()`

that allows you to pass the choice of filter function, cover, and clustering algorithm as arguments. For example, to project our data onto the $x$- and $y$-axes, we could setup the pipeline as follows:

In [ ]:

```
# Define filter function - can be any scikit-learn transformer
filter_func = Projection(columns=[0, 1])
# Define cover
cover = CubicalCover(n_intervals=10, overlap_frac=0.3)
# Choose clustering algorithm - default is DBSCAN
clusterer = DBSCAN()
# Configure parallelism of clustering step
n_jobs = 1
# Initialise pipeline
pipe = make_mapper_pipeline(
filter_func=filter_func,
cover=cover,
clusterer=clusterer,
verbose=False,
n_jobs=n_jobs,
)
```

With the Mapper pipeline at hand, it is now a simple matter to visualise it. To warm up, let's examine the graph in two-dimensions using the default arguments of `giotto-tda`

's plotting function:

In [ ]:

```
fig = plot_static_mapper_graph(pipe, data)
fig.show(config={'scrollZoom': True})
```

From the figure we can see that we have captured the salient topological features of our underlying data, namely two holes!

By default, the nodes of the Mapper graph are colored by the mean value of the points that belong to a given node. However, in this example it is more instructive to colour by the $x$- and $y$-axes. This can be achieved by toggling the `color_by_columns_dropdown`

, which calculates the coloring for each column in the input data array. At the same time, let's configure the choice of colorscale:

In [ ]:

```
plotly_kwargs = {"node_trace_marker_colorscale": "Blues"}
fig = plot_static_mapper_graph(
pipe, data, color_by_columns_dropdown=True, plotly_kwargs=plotly_kwargs
)
fig.show(config={'scrollZoom': True})
```

In the dropdown menu, the entry `color_variable`

refers to a user-defined quantity to color by - by default it is the average value of the points in each node. In general, one can configure this quantity to be an array, a `scikit-learn`

transformer, or a list of indices to select from the data. For example, coloring by a PCA component can be implemented as follows:

In [ ]:

```
# Initialise estimator to color graph by
pca = PCA(n_components=1).fit(data)
fig = plot_static_mapper_graph(
pipe, data, color_by_columns_dropdown=True, color_variable=pca
)
fig.show(config={'scrollZoom': True})
```

It is also possible to feed `plot_static_mapper_graph()`

a pandas DataFrame:

In [ ]:

```
data_df = pd.DataFrame(data, columns=["x", "y"])
data_df.head()
```

Before plotting we need to update the Mapper pipeline to know about the projection onto the column names. This can be achieved using the `set_params()`

method as follows:

In [ ]:

```
pipe.set_params(filter_func=Projection(columns=["x", "y"]));
```

In [ ]:

```
fig = plot_static_mapper_graph(pipe, data_df, color_by_columns_dropdown=True)
fig.show(config={'scrollZoom': True})
```

By default, `plot_static_mapper_graph()`

uses the Kamadaâ€“Kawai algorithm for the layout; however any of the layout algorithms defined in python-igraph are supported (see here for a list of possible layouts). For example, we can switch to the Fruchtermanâ€“Reingold layout as follows:

In [ ]:

```
# Reset back to numpy projection
pipe.set_params(filter_func=Projection(columns=[0, 1]));
```

In [ ]:

```
fig = plot_static_mapper_graph(
pipe, data, layout="fruchterman_reingold", color_by_columns_dropdown=True
)
fig.show(config={'scrollZoom': True})
```

It is also possible to visualise the Mapper graph in 3-dimensions by configuring the `layout_dim`

argument:

In [ ]:

```
fig = plot_static_mapper_graph(pipe, data, layout_dim=3, color_by_columns_dropdown=True)
fig.show(config={'scrollZoom': True})
```

Behind the scenes of `plot_static_mapper_graph()`

is a `MapperPipeline`

object `pipe`

that can be used like a typical `scikit-learn`

estimator. For example, to extract the underlying graph data structure we can do the following:

In [ ]:

```
graph = pipe.fit_transform(data)
```

The resulting graph is an python-igraph object that contains metadata that is stored in the form of dictionaries. We can access this data as follows:

In [ ]:

```
graph["node_metadata"].keys()
```

Here `node_id`

is a globally unique node identifier used to construct the graph, while `pullback_set_label`

and `partial_cluster_label`

refer to the interval and cluster sets described above. The `node_elements`

refers to the indices of our original data that belong to each node. For example, to find which points belong to the first node of the graph we can access the desired data as follows:

In [ ]:

```
node_id, node_elements = (
graph["node_metadata"]["node_id"],
graph["node_metadata"]["node_elements"],
)
```

In [ ]:

```
print(
"Node Id: {}, \nNode elements: {}, \nData points: {}".format(
node_id[0], node_elements[0], data[node_elements[0]]
)
)
```

The `node_elements`

are handy for situations when we want to customise e.g. the size of the node scale. In this example, we use the utility function `set_node_sizeref()`

and pass the function as a plotly argument:

In [ ]:

```
# Configure scale for node sizes
plotly_kwargs = {
"node_trace_marker_sizeref": set_node_sizeref(node_elements, node_scale=30)
}
fig = plot_static_mapper_graph(
pipe,
data,
layout_dim=3,
color_by_columns_dropdown=True,
plotly_kwargs=plotly_kwargs,
)
fig.show(config={'scrollZoom': True})
```

The resulting graph is much easier to decipher with the enlarged node scaling!

In some cases, the list of filter functions provided in `gtda.mapper.filter.py`

or `scikit-learn`

may not be sufficient for the task at hand. In such cases, one can pass any callable to the pipeline that acts **row-wise** on the input data. For example, we can project by taking the sum of the $(x,y)$ coordinates as follows:

In [ ]:

```
filter_func = np.sum
pipe = make_mapper_pipeline(
filter_func=filter_func,
cover=cover,
clusterer=clusterer,
verbose=True,
n_jobs=n_jobs,
)
```

In [ ]:

```
fig = plot_static_mapper_graph(pipe, data, plotly_kwargs=None)
fig.show(config={'scrollZoom': True})
```

In general, building useful Mapper graphs requires some iteration through the various parameters in the cover and clustering algorithm. To simplify that process, `giotto-tda`

provides an interactive figure that can be configured in real time.

If invalid parameters are selected, the *Show logs* checkbox can be used to see what went wrong.

To see the interactive output, please **download** the notebook from github and execute it locally.

In [ ]:

```
pipe = make_mapper_pipeline()
# Generate interactive widget
plot_interactive_mapper_graph(pipe, data, color_by_columns_dropdown=True)
```