### Install giotto-tda in Development Mode Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/installation.rst Installs the giotto-tda library in editable mode, allowing for immediate use of the latest changes from the source code. It's recommended to upgrade pip and setuptools before installation. ```bash cd giotto-tda python -m pip install -e ".[dev]" ``` -------------------------------- ### Install giotto-tda dependencies on Linux Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/installation.rst Installs required C++ build tools (compiler, CMake, Boost) on Linux systems using apt-get. This is part of the developer installation process and ensures the necessary components are available for building from source. ```bash sudo apt-get install cmake libboost-dev ``` -------------------------------- ### Troubleshoot Boost Headers with Verbose Pip Install Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/installation.rst Installs giotto-tda with verbose output to help identify the compiler's search paths for Boost headers. This is useful for resolving Boost-related installation issues. ```bash python -m pip install -e . -v ``` -------------------------------- ### Install giotto-tda using pip Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/installation.rst Installs the latest stable version of giotto-tda using pip. This command will also automatically install all necessary dependencies. It is recommended to use an up-to-date version of pip for a smooth installation. ```bash python -m pip install -U giotto-tda ``` -------------------------------- ### Install giotto-tda nightly builds Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/installation.rst Installs pre-release, experimental builds of giotto-tda which include the latest features and bug fixes. These builds come with pre-compiled wheels, eliminating the need for C++ dependencies. Do not install alongside the stable version. ```bash python -m pip install -U giotto-tda-nightly ``` -------------------------------- ### Import Giotto-TDA Module Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/release.rst Example of how to import the main module of the Giotto-TDA library in Python scripts or notebooks. ```python import gtda ``` -------------------------------- ### Python Example Sentence Printing Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/local_hom_NLP_disambiguation.ipynb This snippet demonstrates how to print example preprocessed sentences, highlighting the usage of 'note' as a verb and in a musical context. It utilizes f-strings for formatted output and accesses elements from a `refined_list` which is assumed to be populated by prior text processing steps. ```python print(f"Example of a preprocessed sentence where 'note' is used as a verb:\nrefined_list[0] = {refined_list[0]}\n\nExample of preprocessed sentence where 'note' refers to music:\nrefined_list[1] = {refined_list[1]}") ``` -------------------------------- ### Plot Persistence Diagrams using VietorisRipsPersistence Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/persistent_homology_graphs.ipynb Shows how to visualize the computed persistence diagrams using the `plot` method of the VietorisRipsPersistence transformer. This example specifically plots the diagram for the first sample in the `diagrams` collection. ```python VR.plot(diagrams, sample=0) ``` -------------------------------- ### Module Class Documentation Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/templates/deprecated_class_without_init.rst Documentation template for Giotto-TDA classes, including deprecation warnings and usage examples. ```APIDOC ## CLASS DOCUMENTATION ### Description This endpoint provides the structural documentation for a specific class within the Giotto-TDA module, including auto-generated class definitions and associated examples. ### Method GET ### Endpoint /api/docs/classes/{module}/{objname} ### Parameters #### Path Parameters - **module** (string) - Required - The name of the module containing the class. - **objname** (string) - Required - The name of the class to document. ### Request Example GET /api/docs/classes/giotto.tda/VietorisRipsPersistence ### Response #### Success Response (200) - **content** (string) - The rendered documentation content including class methods and attributes. #### Response Example { "status": "success", "data": { "class": "VietorisRipsPersistence", "deprecated": true, "documentation": "..." } } ``` -------------------------------- ### Install giotto-tda dependencies on macOS Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/installation.rst Installs required C++ build tools (GCC, CMake, Boost) on macOS using the Homebrew package manager. This command is essential for developers needing to build giotto-tda from source on a macOS system. ```bash brew install gcc cmake boost ``` -------------------------------- ### GET /mapper/visualize/static Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/mapper_quickstart.ipynb Generates a static visualization of the Mapper graph with configurable layout and node scaling. ```APIDOC ## GET /mapper/visualize/static ### Description Creates a static plot of the Mapper graph. Supports 3D layout configuration and node size scaling. ### Method GET ### Endpoint /mapper/visualize/static ### Parameters #### Query Parameters - **layout_dim** (integer) - Optional - Dimension of the layout (e.g., 2 or 3). - **node_scale** (integer) - Optional - Scaling factor for node sizes. ### Request Example { "layout_dim": 3, "node_scale": 30 } ### Response #### Success Response (200) - **figure** (object) - The static visualization figure object. #### Response Example { "figure": "plotly_figure_object" } ``` -------------------------------- ### Initialize Takens Embedding with Parameter Search Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/topology_time_series.ipynb Configures a SingleTakensEmbedding object to perform a parameter search for optimal embedding dimension and time delay. This setup is essential for preparing time series data for topological analysis. ```python max_embedding_dimension = 30 max_time_delay = 30 stride = 5 embedder_periodic = SingleTakensEmbedding( parameters_type="search", time_delay=max_time_delay, dimension=max_embedding_dimension, stride=stride, ) ``` -------------------------------- ### Compute Local Features with Collapse Edges and Parallel Jobs (Python) Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/local_homology.ipynb Computes local topological features for a combined line, plane, and cube point cloud. This example utilizes RadiusLocalVietorisRips with `collapse_edges=True` and `n_jobs=-1` for potential performance improvements and parallel processing. ```python radii = (0.01, 0.25) homology_dimensions = (1, 2, 3) collapse_edges = True n_jobs = -1 r_lh = RadiusLocalVietorisRips(radii=radii, homology_dimensions=homology_dimensions, collapse_edges=collapse_edges, n_jobs=n_jobs) pipe = make_pipeline(r_lh, mod_pe) loc_dim_features = pipe.fit_transform(line_plane_cube) dimension = 1 dim_index = homology_dimensions.index(dimension) colors = loc_dim_features[:, dim_index] plot_coloured_cloud(line_plane_cube, colors) ``` -------------------------------- ### Giotto-TDA Class Documentation Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/templates/class.rst Documentation for a specific class within the Giotto-TDA library, including its constructor and examples. ```APIDOC ## {{objname}} ### Description Documentation for the {{objname}} class. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Initialization (`__init__`) #### Description Initializes the {{objname}} object. #### Parameters (Details for `__init__` parameters would typically be listed here if available in the source) ### Examples (Examples for {{objname}} would be listed here if available in the source) ``` -------------------------------- ### Documenting Giotto-TDA Functions Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/templates/deprecated_function.rst This snippet demonstrates the reStructuredText template used for documenting functions in the giotto-tda library. It includes metadata for search indexing, a deprecation warning, and directives for automatic documentation generation and example inclusion. ```rst :mod:`{{module}}`.{{objname}} {{ underline }}==================== .. meta:: :robots: noindex .. warning:: **DEPRECATED** .. currentmodule:: {{module}} .. autofunction:: {{objname}} .. include:: {{module}}.{{objname}}.{{examples}} ``` -------------------------------- ### Pipeline Creation and Usage Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/vietoris_rips_quickstart.ipynb Demonstrates how to define, train, and evaluate a machine learning pipeline using Giotto-TDA and scikit-learn. ```APIDOC ## Pipeline Creation and Usage ### Description This section details the process of creating an end-to-end machine learning pipeline by combining transformers from the ``giotto-tda`` library with standard ``scikit-learn`` components. It covers data preparation, pipeline fitting, and performance evaluation. ### Method This is a conceptual guide, not a direct API endpoint. The code demonstrates a common workflow. ### Endpoint N/A ### Parameters N/A ### Request Example ```python from sklearn.pipeline import make_pipeline from sklearn.model_selection import train_test_split from giotto_tda.transformers import VietorisRipsPersistence, PersistenceEntropy from sklearn.ensemble import RandomForestClassifier # Assuming 'point_clouds' and 'labels' are pre-defined numpy arrays or similar # point_clouds = ... # labels = ... # Define the pipeline steps steps = [ VietorisRipsPersistence(homology_dimensions=[0, 1, 2]), PersistenceEntropy(), RandomForestClassifier() ] # Create the pipeline pipeline = make_pipeline(*steps) # Split the data # Note: Ensure point_clouds and labels are correctly formatted for train_test_split # pcs_train, pcs_valid, labels_train, labels_valid = train_test_split(point_clouds, labels, test_size=0.2, random_state=42) # Fit the pipeline on the training data # pipeline.fit(pcs_train, labels_train) # Score the fitted pipeline on the test data # score = pipeline.score(pcs_valid, labels_valid) # print(f"Pipeline score on test data: {score}") ``` ### Response #### Success Response (Conceptual) This workflow does not return a direct API response but rather a performance score. #### Response Example ``` Pipeline score on test data: 0.85 ``` ``` -------------------------------- ### GET /api/docs/class Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/templates/class_without_init.rst Retrieves the documentation for a specific class within the Giotto-TDA module, including its definition and examples. ```APIDOC ## GET /api/docs/class ### Description Fetches the autogenerated documentation for a specified class within a module. ### Method GET ### Endpoint /api/docs/{module}/{objname} ### Parameters #### Path Parameters - **module** (string) - Required - The name of the module containing the class. - **objname** (string) - Required - The name of the class to document. ### Request Example GET /api/docs/giotto.homology/VietorisRipsPersistence ### Response #### Success Response (200) - **content** (string) - The rendered documentation content including class definition and examples. #### Response Example { "content": "class VietorisRipsPersistence(...): ..." } ``` -------------------------------- ### Importing giotto-tda and supporting libraries Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/lorenz_attractor.ipynb Initializes the environment by importing necessary modules from giotto-tda, numpy, scikit-learn, and plotly for data processing and visualization. ```python from gtda.time_series import Resampler, SlidingWindow, takens_embedding_optimal_parameters, TakensEmbedding, PermutationEntropy from gtda.homology import WeakAlphaPersistence, VietorisRipsPersistence from gtda.diagrams import Scaler, Filtering, PersistenceEntropy, BettiCurve, PairwiseDistance from gtda.graphs import KNeighborsGraph, GraphGeodesicDistance from gtda.pipeline import Pipeline import numpy as np from sklearn.metrics import pairwise_distances import plotly.express as px from plotly.offline import init_notebook_mode, iplot init_notebook_mode(connected=True) from gtda.plotting import plot_heatmap, plot_point_cloud import openml ``` -------------------------------- ### POST /mapper/visualize/interactive Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/mapper_quickstart.ipynb Initializes an interactive Mapper plotter for real-time hyperparameter tuning. ```APIDOC ## POST /mapper/visualize/interactive ### Description Creates an interactive widget for exploring Mapper graph parameters in real-time. ### Method POST ### Endpoint /mapper/visualize/interactive ### Parameters #### Request Body - **pipe** (object) - Required - The configured MapperPipeline object. - **data** (array) - Required - The dataset to visualize. ### Request Example { "pipe": "pipeline_instance", "data": [[0.1, 0.2]] } ### Response #### Success Response (200) - **widget** (object) - The interactive widget instance. #### Response Example { "widget": "interactive_plotter_instance" } ``` -------------------------------- ### Importing giotto-tda Mapper modules Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/mapper_quickstart.ipynb Initializes the necessary environment by importing data manipulation, visualization, and TDA-specific modules from giotto-tda and scikit-learn. ```python import numpy as np import pandas as pd from gtda.plotting import plot_point_cloud from gtda.mapper import ( CubicalCover, make_mapper_pipeline, Projection, plot_static_mapper_graph, plot_interactive_mapper_graph, MapperInteractivePlotter ) from sklearn import datasets from sklearn.cluster import DBSCAN from sklearn.decomposition import PCA ``` -------------------------------- ### Import Libraries and Initialize Vietoris-Rips Persistence Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/voids_on_the_plane.ipynb Imports necessary libraries including numpy for numerical operations and VietorisRipsPersistence from giotto.homology for topological analysis. It also sets the random seed for reproducibility and initializes the Vietoris-Rips persistence object for computing homology in dimension 2. ```python import numpy as np from gtda.homology import VietorisRipsPersistence import itertools import matplotlib.pyplot as plt # Not a requirement of giotto-tda, but is needed here np.random.seed(1) # Set numpy's random seed ``` ```python # Initialize the Vietoris–Rips transformer VR = VietorisRipsPersistence(homology_dimensions=(2,), max_edge_length=np.inf) ``` -------------------------------- ### Using Convenience Plotting Methods Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/plotting_api.ipynb Shows how to use the transform_plot and fit_transform_plot methods to combine transformation and visualization into streamlined workflows. ```python VR = VietorisRipsPersistence() VR.fit(X) Xt = VR.transform_plot(X, sample=i) # Or using the one-liner fit_transform_plot Xt = VR.fit_transform_plot(X, sample=i) ``` -------------------------------- ### Prepare Time Series Targets with Labeller Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/time_series_forecasting.ipynb Shows how to use the Labeller class to create target variables from time series data. It illustrates the fit_transform_resample method for aligning inputs and targets for predictive modeling. ```python from gtda.time_series import Labeller X = np.arange(10) Lab = Labeller(size=1, func=np.max) Xl, yl = Lab.fit_transform_resample(X, X) SW = SlidingWindow(size=5) TE = TakensEmbedding(time_delay=1, dimension=2) VR = VietorisRipsPersistence() Ampl = Amplitude() RFR = RandomForestRegressor() pipe = make_pipeline(Lab, SW, TE, VR, Ampl, RFR) pipe.fit(X, X) y_pred = pipe.predict(X) ``` -------------------------------- ### Clear CMake Cache Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/installation.rst Removes the CMake build cache, which can be necessary if multiple versions of Boost have been installed, to ensure a clean build. ```bash rm -rf build/ ``` -------------------------------- ### Option 1: SlidingWindow + TakensEmbedding for Time Series Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/time_series_forecasting.ipynb This snippet demonstrates the first approach, applying a SlidingWindow to the time series data and then using TakensEmbedding to transform the windows into point clouds. It's suitable for parallel processing pipelines and ensures compatibility with other feature generation methods. ```python from gtda.time_series import TakensEmbedding X = np.arange(n_timestamps) window_size = 5 stride = 2 SW = SlidingWindow(size=window_size, stride=stride) X_sw, yr = SW.fit_transform_resample(X, y) X_sw, yr ``` ```python time_delay = 1 dimension = 2 TE = TakensEmbedding(time_delay=time_delay, dimension=dimension) X_te = TE.fit_transform(X_sw) X_te ``` ```python VR = VietorisRipsPersistence() Ampl = Amplitude() RFR = RandomForestRegressor() pipe = make_pipeline(SW, TE, VR, Ampl, RFR) pipe ``` ```python pipe.fit(X, y) y_pred = pipe.predict(X) score = pipe.score(X, y) y_pred, score ``` -------------------------------- ### Run TDA Pipeline and Get Feature Shape Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/MNIST_classification.ipynb Applies the fitted TDA pipeline to training data and returns the shape of the transformed features. This step is crucial for understanding the dimensionality of the extracted topological features. ```python X_train_tda = tda_union.fit_transform(X_train) X_train_tda.shape ``` -------------------------------- ### Change Mapper Graph Layout Algorithm Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/mapper_quickstart.ipynb Demonstrates how to switch the graph layout algorithm, such as using Fruchterman-Reingold instead of the default Kamada-Kawai, to optimize visual representation. ```python fig = plot_static_mapper_graph( pipe, data, layout="fruchterman_reingold", color_data=data ) fig.show(config={'scrollZoom': True}) ``` -------------------------------- ### Create and Train a Giotto-TDA Pipeline Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/vietoris_rips_quickstart.ipynb This snippet demonstrates how to construct a pipeline using VietorisRipsPersistence and PersistenceEntropy from giotto-tda, followed by a RandomForestClassifier. It includes splitting the point cloud data, fitting the pipeline, and calculating the accuracy score. ```python from sklearn.pipeline import make_pipeline from sklearn.model_selection import train_test_split steps = [VietorisRipsPersistence(homology_dimensions=[0, 1, 2]), PersistenceEntropy(), RandomForestClassifier()] pipeline = make_pipeline(*steps) pcs_train, pcs_valid, labels_train, labels_valid = train_test_split(point_clouds, labels) pipeline.fit(pcs_train, labels_train) pipeline.score(pcs_valid, labels_valid) ``` -------------------------------- ### Import Libraries for Local Homology NLP Analysis (Python) Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/local_hom_NLP_disambiguation.ipynb Imports necessary Python libraries for data manipulation, machine learning pipelines, dimensionality reduction, topological data analysis (giotto-tda), and Natural Language Processing (gensim). Some libraries like umap-learn and gensim are external dependencies for this specific example. ```python # Import PyData libraries import numpy as np import matplotlib.pyplot as plt %matplotlib inline from sklearn.base import BaseEstimator, TransformerMixin from sklearn.preprocessing import StandardScaler, FunctionTransformer from sklearn.pipeline import make_pipeline, Pipeline # Import umap for dimensionality reduction and visualization # umap-learn is not a requirement of giotto-tda, but is needed here. from umap import UMAP # giotto-tda imports from gtda.plotting import plot_point_cloud from gtda.local_homology import KNeighborsLocalVietorisRips from gtda.diagrams import PersistenceEntropy # Import needed NLP libraries # gensim is not a requirement of giotto-tda, but is needed here. from gensim.models import Word2Vec from gensim.test.utils import common_texts from gensim.parsing.preprocessing import remove_stopwords, stem ``` -------------------------------- ### Generate and Plot Persistence Diagrams with VietorisRipsPersistence Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/plotting_api.ipynb Demonstrates how to generate random point cloud data, compute persistence diagrams using VietorisRipsPersistence, and visualize the results using the built-in plot method. ```python import numpy as np from gtda.homology import VietorisRipsPersistence from sklearn.datasets import make_circles from gtda.plotting import plot_point_cloud np.random.seed(seed=42) X = np.asarray([make_circles(100, factor=np.random.random())[0] for i in range(10)]) i = 0 plot_point_cloud(X[i]) VR = VietorisRipsPersistence() Xt = VR.fit_transform(X) VR.plot(Xt, sample=i) ``` -------------------------------- ### Generating and visualizing sample data Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/mapper_quickstart.ipynb Creates a two-dimensional point cloud representing two concentric circles and displays it using giotto-tda's plotting utility. ```python data, _ = datasets.make_circles(n_samples=5000, noise=0.05, factor=0.3, random_state=42) plot_point_cloud(data) ``` -------------------------------- ### Configure Automated Embedding Parameters Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/topology_time_series.ipynb Initializes the SingleTakensEmbedding transformer with automatic parameter search enabled. The time_delay and dimension arguments act as upper bounds for the search algorithms. ```python embedder = SingleTakensEmbedding( parameters_type="search", time_delay=time_delay, dimension=embedding_dimension, ) ``` -------------------------------- ### Loading and visualizing Lorenz attractor data Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/lorenz_attractor.ipynb Fetches the Lorenz dataset from OpenML and renders the point cloud trajectory using giotto-tda's plotting utilities. ```python from openml.datasets.functions import get_dataset point_cloud = get_dataset(42182).get_data(dataset_format='array')[0] plot_point_cloud(point_cloud) ``` -------------------------------- ### Load and Preprocess Text Data (Python) Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/local_hom_NLP_disambiguation.ipynb Reads plain text content from an XML file ('data/note.n.xml') and performs initial preprocessing. This step is crucial for preparing the text data for subsequent NLP tasks and word embedding generation. ```python # Preprocess the data with open("data/note.n.xml", "r") as f: content = f.read() ``` -------------------------------- ### Run giotto-tda Tests Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/installation.rst Executes the test suite for the giotto-tda library. This command should be run from outside the source directory. ```bash pytest gtda ``` -------------------------------- ### Configure Simplex Tree Module (CMake) Source: https://github.com/giotto-ai/giotto-tda/blob/master/CMakeLists.txt This CMake script sets up the build for the simplex tree module. It defines the target, specifies the C++ standard, and links to Boost and OpenMP. Crucially, it includes a comprehensive set of include directories for various Giotto-TDA components and external libraries like Eigen. Compiler optimizations and debug flags are configured, with platform-specific adjustments for MSVC. ```cmake pybind11_add_module(gtda_simplex_tree MODULE "${BINDINGS_DIR}/simplex_tree_bindings.cpp") set_property(TARGET gtda_simplex_tree PROPERTY CXX_STANDARD 14) if(OpenMP_FOUND) target_link_libraries(gtda_simplex_tree PRIVATE OpenMP::OpenMP_CXX) endif() target_link_libraries(gtda_simplex_tree LINK_PUBLIC ${Boost_LIBRARIES}) target_compile_definitions(gtda_simplex_tree PRIVATE BOOST_RESULT_OF_USE_DECLTYPE=1 BOOST_ALL_NO_LIB=1 BOOST_SYSTEM_NO_DEPRECATED=1) target_include_directories(gtda_simplex_tree PRIVATE "${GUDHI_SRC_DIR}/Simplex_tree/include") target_include_directories(gtda_simplex_tree PRIVATE "${GUDHI_SRC_DIR}/common/include") target_include_directories(gtda_simplex_tree PRIVATE "${GUDHI_SRC_DIR}/Cech_complex/include") target_include_directories(gtda_simplex_tree PRIVATE "${GUDHI_SRC_DIR}/Persistent_cohomology/include") target_include_directories(gtda_simplex_tree PRIVATE "${GUDHI_SRC_DIR}/Subsampling/include") target_include_directories(gtda_simplex_tree PRIVATE "${GUDHI_SRC_DIR}/python/include") target_include_directories(gtda_simplex_tree PRIVATE "${GUDHI_SRC_DIR}/Collapse/include") target_include_directories(gtda_simplex_tree PRIVATE "${EIGEN_DIR}") if(MSVC) target_compile_options(gtda_simplex_tree PUBLIC $<$: /O2 /Wall /fp:strict>) target_compile_options(gtda_simplex_tree PUBLIC $<$:/O1 /DEBUG:FULL /Zi /Zo>) else() target_compile_options(gtda_simplex_tree PUBLIC $<$: -Ofast -shared -pthread -fPIC -fwrapv -Wall -fno-strict-aliasing -frounding-math>) target_compile_options(gtda_simplex_tree PUBLIC $<$:-O2 -ggdb -D_GLIBCXX_DEBUG>) endif() ``` -------------------------------- ### Load and Prepare 3D Point Cloud Data Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/classifying_shapes.ipynb Loads a dataset of 3D shapes from OpenML, filters for specific objects, and prepares the data for topological analysis. It demonstrates how to query a pandas DataFrame and plot a point cloud. ```python from openml.datasets.functions import get_dataset df = get_dataset('shapes').get_data(dataset_format='dataframe')[0] df.head() plot_point_cloud(df.query('target == "biplane0"')[["x", "y", "z"]].values) ``` -------------------------------- ### Create Mapper Pipeline Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/release.rst Demonstrates the creation of a Mapper pipeline object using the `make_mapper_pipeline` function. This pipeline can be used for topological data analysis. ```python from gtda.mapper import make_mapper_pipeline mapper_pipeline = make_mapper_pipeline(...) ``` -------------------------------- ### Initialize Local Homology Transformers Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/local_homology.ipynb Imports necessary modules for local homology analysis, including KNeighborsLocalVietorisRips and RadiusLocalVietorisRips, to prepare for topological feature extraction. ```python import numpy as np from gtda.plotting import plot_point_cloud from gtda.local_homology import KNeighborsLocalVietorisRips, RadiusLocalVietorisRips ``` -------------------------------- ### Customize Node Color Statistics Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/mapper_quickstart.ipynb Illustrates how to control node coloring by providing custom statistical functions or direct arrays. This allows for flexible aggregation of color features into node-specific values. ```python fig = plot_static_mapper_graph( pipe, data, color_data=data, color_features=pca, node_color_statistic=lambda x: np.mean(x) / 2 ) fig.show(config={'scrollZoom': True}) ``` -------------------------------- ### Build and Run Giotto TDA Pipeline Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/classifying_shapes.ipynb This snippet illustrates how to construct a machine learning pipeline using Giotto TDA's Pipeline class. It chains together topological feature extraction (VietorisRipsPersistence and PersistenceEntropy) with a final estimator (RandomForestClassifier). The pipeline simplifies the workflow by managing the sequence of transformations and fitting. ```python from gtda.pipeline import Pipeline from gtda.diagrams import VietorisRipsPersistence, PersistenceEntropy from sklearn.ensemble import RandomForestClassifier steps = [ ("persistence", VietorisRipsPersistence(metric="euclidean", homology_dimensions=homology_dimensions, n_jobs=6)), ("entropy", PersistenceEntropy()), ("model", RandomForestClassifier(oob_score=True)), ] pipeline = Pipeline(steps) pipeline.fit(point_clouds_basic, labels_basic) # Access the Random Forest model by its key to get the OOB score pipeline["model"].oob_score_ ``` -------------------------------- ### Function Documentation Template Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/templates/function.rst Standard documentation format for Giotto-TDA library functions. ```APIDOC ## [FUNCTION] {{objname}} ### Description This endpoint/function provides access to the {{objname}} utility within the {{module}} module of the Giotto-TDA library. It is designed to perform specific topological data analysis operations. ### Method N/A (Library Function) ### Endpoint {{module}}.{{objname}} ### Parameters #### Path Parameters - **module** (string) - Required - The parent module containing the function. - **objname** (string) - Required - The name of the function to be documented. ### Request Example ```python from {{module}} import {{objname}} result = {{objname}}(data) ``` ### Response #### Success Response (200) - **result** (object) - The output of the topological transformation or analysis. #### Response Example { "status": "success", "data": "result_object" } ``` -------------------------------- ### Configure Mapper Graph Coloring and Colorscale Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/mapper_quickstart.ipynb Demonstrates how to color Mapper nodes based on input data features and configure the Plotly colorscale. This allows for interactive exploration of data properties mapped onto the graph structure. ```python plotly_params = {"node_trace": {"marker_colorscale": "Blues"}} fig = plot_static_mapper_graph( pipe, data, color_data=data, plotly_params=plotly_params ) fig.show(config={'scrollZoom': True}) ``` -------------------------------- ### Custom Mapper Pipelines with Different Filter Functions Source: https://context7.com/giotto-ai/giotto-tda/llms.txt Demonstrates creating custom Mapper pipelines using different filter functions like Eccentricity or Projection, along with various cover and clustering strategies. This allows for flexible topological analysis of data. Dependencies include scikit-learn and Giotto TDA. ```python from sklearn.preprocessing import MinMaxScaler from gtda.mapper import ( make_mapper_pipeline, OneDimensionalCover, Projection, Eccentricity, FirstHistogramGap ) # Use eccentricity as filter function mapper_ecc = make_mapper_pipeline( scaler=MinMaxScaler(), filter_func=Eccentricity(), cover=OneDimensionalCover(n_intervals=15, overlap_frac=0.4), clusterer=FirstHistogramGap(), n_jobs=-1 ) # Or use projection onto specific columns mapper_proj = make_mapper_pipeline( filter_func=Projection(columns=[0, 1]), cover=CubicalCover(n_intervals=10, overlap_frac=0.3), clusterer=DBSCAN(eps=0.3) ) graph = mapper_ecc.fit_transform(X) ``` -------------------------------- ### Class and Method Documentation Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/templates/deprecated_class.rst Standard documentation structure for classes and methods within the Giotto-TDA library. ```APIDOC ## Class Definition ### Description This section covers the documentation for specific classes within the Giotto-TDA module, including their initialization and associated methods. ### Note This module or object is marked as **DEPRECATED**. ### Usage - **Module**: {{module}} - **Object**: {{objname}} ### Methods - **__init__**: Initializes the class instance with the required parameters. ### Examples Refer to the included examples file: {{module}}.{{objname}}.{{examples}} ``` -------------------------------- ### Configuring the Mapper pipeline Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/mapper_quickstart.ipynb Sets up a Mapper pipeline by defining a filter function, a cover, and a clustering algorithm. This pipeline is used to transform high-dimensional data into a topological graph. ```python filter_func = Projection(columns=[0, 1]) cover = CubicalCover(n_intervals=10, overlap_frac=0.3) clusterer = DBSCAN() n_jobs = 1 pipe = make_mapper_pipeline( filter_func=filter_func, cover=cover, clusterer=clusterer, verbose=False, n_jobs=n_jobs, ) ``` -------------------------------- ### Generate and Plot a Point Cloud (Python) Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/local_homology.ipynb Generates a 3D point cloud composed of three connected line segments. This serves as an input for topological analysis, demonstrating a non-trivial structure for a primarily one-dimensional object. ```python line1 = [[x, 0, 0] for x in np.arange(-1, 1, 1/10)] line2 = [[0, y, 0] for y in np.arange(-1, 1, 1/10)] line3 = [[x, 1, 0] for x in np.arange(-1, 1, 1/10)] lines = np.array(line1 + line2 + line3) plot_point_cloud(lines) ``` -------------------------------- ### Construct and Train a Topological Pipeline Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/time_series_forecasting.ipynb Builds a scikit-learn compatible pipeline integrating sliding windows, topological transformers, and a final regression estimator. ```python from sklearn.ensemble import RandomForestRegressor from gtda.pipeline import make_pipeline RFR = RandomForestRegressor() pipe = make_pipeline(SW, PD, VR, Ampl, RFR) pipe.fit(X, y) y_pred = pipe.predict(X) score = pipe.score(X, y) ``` -------------------------------- ### Create and Run Scikit-learn Pipeline with Giotto TDA in Python Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/lorenz_attractor.ipynb Constructs and executes a scikit-learn compatible pipeline that integrates Giotto TDA transformers for time series analysis. The pipeline includes sampling, windowing, embedding, and diagram computation steps. ```python # Steps of the Pipeline steps = [('sampling', periodicSampler), ('window', SW), ('embedding', TE), ('diagrams', WA)] # Define the Pipeline pipeline = Pipeline(steps) # Run the pipeline X_diagrams = pipeline.fit_transform(X) ``` -------------------------------- ### Initialize Time Series Data for Sliding Window Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/time_series_forecasting.ipynb Initializes a numpy array for time series data (X) and a corresponding target variable (y) of the same length, suitable for demonstrating sliding window operations. ```python import numpy as np n_timestamps = 10 X, y = np.arange(n_timestamps), np.arange(n_timestamps) - n_timestamps X, y ``` -------------------------------- ### PersistenceLandscape Generation (Python) Source: https://context7.com/giotto-ai/giotto-tda/llms.txt Computes persistence landscapes from persistence diagrams, offering a stable, multi-scale functional representation. Landscapes are generated for a specified number of layers. Requires Giotto TDA's PersistenceLandscape. ```python from gtda.diagrams import PersistenceLandscape # Assuming 'diagrams' is already computed # Example placeholder data: import numpy as np from gtda.homology import VietorisRipsPersistence point_clouds = np.random.random((10, 100, 3)) vr = VietorisRipsPersistence(homology_dimensions=(0, 1)) diagrams = vr.fit_transform(point_clouds) # Compute persistence landscapes with 3 layers pl = PersistenceLandscape(n_layers=3, n_bins=100) landscapes = pl.fit_transform(diagrams) # Output: (n_samples, n_homology_dimensions * n_layers, n_bins) print(f"Landscapes shape: {landscapes.shape}") # Example: (10, 6, 100) - 2 dimensions * 3 layers # Plot landscapes # fig = pl.plot(landscapes, sample=0) ``` -------------------------------- ### Transition Graph Construction for Time Series Source: https://context7.com/giotto-ai/giotto-tda/llms.txt Constructs transition graphs from time series, useful for analyzing dynamical systems. This method represents the transitions between states in a time series as a graph. It takes sequences of states as input and outputs transition graphs. ```python from gtda.graphs import TransitionGraph import numpy as np # Time series represented as sequences of states sequences = np.random.randint(0, 10, size=(5, 100)) # Build transition graphs tg = TransitionGraph() transition_graphs = tg.fit_transform(sequences) print(f"Transition graphs shape: {transition_graphs.shape}") ``` -------------------------------- ### Analyze Directed Circle with Alternating Edges Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/persistent_homology_graphs.ipynb Shows how to construct a circle graph with flipped edge directions and analyze its persistence diagram using FlagserPersistence. ```python row_flipped = np.concatenate([row[::2], col[1::2]]) column_flipped = np.concatenate([col[::2], row[1::2]]) weights = np.ones(n_vertices) directed_circle_flipped = coo_matrix((weights, (row_flipped, column_flipped))) FlagserPersistence().fit_transform_plot([directed_circle_flipped]) X_ggd = GraphGeodesicDistance(directed=True, unweighted=True).fit_transform([directed_circle_flipped]) FlagserPersistence().fit_transform_plot(X_ggd) ``` -------------------------------- ### Compute Persistence for Directed Circle Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/persistent_homology_graphs.ipynb Demonstrates creating a directed circle graph and computing its persistence using FlagserPersistence, both directly and with GraphGeodesicDistance preprocessing. ```python n_vertices = 10 directed_circle = make_circle_adjacency(n_vertices, directed=True) row, col = directed_circle.nonzero() graph = Graph(n=n_vertices, edges=list(zip(row, col)), directed=True) FlagserPersistence().fit_transform_plot([directed_circle]) X_ggd = GraphGeodesicDistance(directed=True, unweighted=True).fit_transform([directed_circle]) FlagserPersistence().fit_transform_plot(X_ggd) ``` -------------------------------- ### Build Witness Complex Module (CMake) Source: https://github.com/giotto-ai/giotto-tda/blob/master/CMakeLists.txt This CMake script configures the build for the Witness Complex module using pybind11. It sets the C++ standard, links against Boost and OpenMP if available, and defines necessary include paths for various Giotto-TDA components and Eigen. Compile options are tailored for Release and Debug builds, and for MSVC and other compilers. ```cmake pybind11_add_module(gtda_witness_complex MODULE "${BINDINGS_DIR}/witness_complex_bindings.cpp") set_property(TARGET gtda_witness_complex PROPERTY CXX_STANDARD 14) if(OpenMP_FOUND) target_link_libraries(gtda_witness_complex PRIVATE OpenMP::OpenMP_CXX) endif() target_link_libraries(gtda_witness_complex LINK_PUBLIC ${Boost_LIBRARIES}) target_compile_definitions(gtda_witness_complex PRIVATE BOOST_RESULT_OF_USE_DECLTYPE=1 BOOST_ALL_NO_LIB=1 BOOST_SYSTEM_NO_DEPRECATED=1) target_include_directories(gtda_witness_complex PRIVATE "${GUDHI_SRC_DIR}/Witness_complex/include") target_include_directories(gtda_witness_complex PRIVATE "${GUDHI_SRC_DIR}/Simplex_tree/include") target_include_directories(gtda_witness_complex PRIVATE "${GUDHI_SRC_DIR}/Cech_complex/include") target_include_directories(gtda_witness_complex PRIVATE "${GUDHI_SRC_DIR}/Persistent_cohomology/include") target_include_directories(gtda_witness_complex PRIVATE "${GUDHI_SRC_DIR}/python/include") target_include_directories(gtda_witness_complex PRIVATE "${GUDHI_SRC_DIR}/common/include") target_include_directories(gtda_witness_complex PRIVATE "${GUDHI_SRC_DIR}/Collapse/include") target_include_directories(gtda_witness_complex PRIVATE "${EIGEN_DIR}") if(MSVC) target_compile_options(gtda_witness_complex PUBLIC $<$: /O2 /Wall /fp:strict>) target_compile_options(gtda_witness_complex PUBLIC $<$:/O1 /DEBUG:FULL /Zi /Zo>) else() target_compile_options(gtda_witness_complex PUBLIC $<$: -Ofast -shared -pthread -fPIC -fwrapv -Wall -fno-strict-aliasing -frounding-math>) target_compile_options(gtda_witness_complex PUBLIC $<$:-O2 -ggdb -D_GLIBCXX_DEBUG>) endif() ``` -------------------------------- ### Compute Persistence for Point Clouds Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/persistent_homology_graphs.ipynb Shows that computing persistence on a point cloud directly is equivalent to computing it on a precomputed distance matrix. ```python from gtda.homology import VietorisRipsPersistence from scipy.spatial.distance import pdist, squareform import numpy as np # 1 point cloud with 20 points in 5 dimensions point_cloud = np.random.rand(20, 5) # Corresponding matrix of Euclidean pairwise distances pairwise_distances = squareform(pdist(point_cloud)) # Compute using point cloud directly vs precomputed distances X_vr_pc = VietorisRipsPersistence().fit_transform([point_cloud]) X_vr_graph = VietorisRipsPersistence(metric="precomputed").fit_transform([pairwise_distances]) assert np.array_equal(X_vr_pc, X_vr_graph) ``` -------------------------------- ### Implement Mapper Algorithm Pipeline Source: https://github.com/giotto-ai/giotto-tda/blob/master/doc/library.rst Creates a Mapper pipeline using scikit-learn components for topological data visualization and analysis. ```python from gtda.mapper import make_mapper_pipeline from sklearn.decomposition import PCA from sklearn.cluster import DBSCAN pipe = make_mapper_pipeline(filter_func=PCA(), clusterer=DBSCAN()) plot_interactive_mapper_graph(pipe, data) ``` -------------------------------- ### BettiCurve Generation from Diagrams (Python) Source: https://context7.com/giotto-ai/giotto-tda/llms.txt Converts persistence diagrams into Betti curves, which represent the number of topological features alive at each filtration value. This provides a functional representation of the diagram. Requires Giotto TDA's VietorisRipsPersistence and BettiCurve. ```python import numpy as np from gtda.homology import VietorisRipsPersistence from gtda.diagrams import BettiCurve # Generate data and diagrams point_clouds = np.random.random((10, 100, 3)) vr = VietorisRipsPersistence(homology_dimensions=(0, 1)) diagrams = vr.fit_transform(point_clouds) # Compute Betti curves bc = BettiCurve(n_bins=100) betti_curves = bc.fit_transform(diagrams) # Output: (n_samples, n_homology_dimensions, n_bins) print(f"Betti curves shape: {betti_curves.shape}") # Example: (10, 2, 100) # Plot Betti curves # fig = bc.plot(betti_curves, sample=0) ``` -------------------------------- ### Visualize Composite Estimators with Scikit-learn Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/MNIST_classification.ipynb Demonstrates how to visualize composite estimators using scikit-learn's display configuration. This allows for a clear representation of the structure of the TDA pipeline. ```python from sklearn import set_config set_config(display='diagram') tda_union ``` -------------------------------- ### Extract Persistence Diagrams using VietorisRipsPersistence for graphs Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/persistent_homology_graphs.ipynb Demonstrates how to instantiate and use the VietorisRipsPersistence transformer to compute persistence diagrams from a collection of graph adjacency matrices. The transformer is initialized with `metric='precomputed'` and its `fit_transform` method is called on the input data `X`. ```python # Instantiate topological transformer VR = VietorisRipsPersistence(metric="precomputed") # Compute persistence diagrams corresponding to each graph in X diagrams = VR.fit_transform(X) ``` -------------------------------- ### Option 2: SingleTakensEmbedding + SlidingWindow for Time Series Source: https://github.com/giotto-ai/giotto-tda/blob/master/examples/time_series_forecasting.ipynb This snippet illustrates the second approach, where SingleTakensEmbedding is applied first to create a global embedding, followed by a SlidingWindow. This method allows for automatic computation of optimal 'time delay' and 'embedding dimension' parameters, though it's generally less recommended due to its order. ```python from gtda.time_series import SingleTakensEmbedding X = np.arange(n_timestamps) STE = SingleTakensEmbedding(parameters_type="search", time_delay=2, dimension=3) X_ste, yr = STE.fit_transform_resample(X, y) X_ste, yr ``` ```python window_size = 5 stride = 2 SW = SlidingWindow(size=window_size, stride=stride) X_sw, yr = SW.fit_transform_resample(X_ste, yr) X_sw, yr ``` ```python VR = VietorisRipsPersistence() Ampl = Amplitude() RFR = RandomForestRegressor() pipe = make_pipeline(STE, SW, VR, Ampl, RFR) pipe ``` ```python pipe.fit(X, y) y_pred = pipe.predict(X) score = pipe.score(X, y) y_pred, score ```