diff options
Diffstat (limited to 'src/python/example')
21 files changed, 578 insertions, 172 deletions
diff --git a/src/python/example/alpha_complex_diagram_persistence_from_off_file_example.py b/src/python/example/alpha_complex_diagram_persistence_from_off_file_example.py index b8f283b3..c96121a6 100755 --- a/src/python/example/alpha_complex_diagram_persistence_from_off_file_example.py +++ b/src/python/example/alpha_complex_diagram_persistence_from_off_file_example.py @@ -1,10 +1,12 @@ #!/usr/bin/env python -import gudhi import argparse +import gudhi as gd -""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. - See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. +""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - + which is released under MIT. + See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full + license details. Author(s): Vincent Rouvreau Copyright (C) 2016 Inria @@ -21,12 +23,12 @@ parser = argparse.ArgumentParser( description="AlphaComplex creation from " "points read in a OFF file.", epilog="Example: " "example/alpha_complex_diagram_persistence_from_off_file_example.py " - "-f ../data/points/tore3D_300.off -a 0.6" + "-f ../data/points/tore3D_300.off" "- Constructs a alpha complex with the " "points from the given OFF file.", ) parser.add_argument("-f", "--file", type=str, required=True) -parser.add_argument("-a", "--max_alpha_square", type=float, default=0.5) +parser.add_argument("-a", "--max_alpha_square", type=float, required=False) parser.add_argument("-b", "--band", type=float, default=0.0) parser.add_argument( "--no-diagram", @@ -37,32 +39,24 @@ parser.add_argument( args = parser.parse_args() -with open(args.file, "r") as f: - first_line = f.readline() - if (first_line == "OFF\n") or (first_line == "nOFF\n"): - print("#####################################################################") - print("AlphaComplex creation from points read in a OFF file") - - message = "AlphaComplex with max_edge_length=" + repr(args.max_alpha_square) - print(message) - - alpha_complex = gudhi.AlphaComplex(off_file=args.file) - simplex_tree = alpha_complex.create_simplex_tree( - max_alpha_square=args.max_alpha_square - ) - - message = "Number of simplices=" + repr(simplex_tree.num_simplices()) - print(message) - - diag = simplex_tree.persistence() - - print("betti_numbers()=") - print(simplex_tree.betti_numbers()) - - if args.no_diagram == False: - pplot = gudhi.plot_persistence_diagram(diag, band=args.band) - pplot.show() - else: - print(args.file, "is not a valid OFF file") - - f.close() +print("##############################################################") +print("AlphaComplex creation from points read in a OFF file") + +points = gd.read_points_from_off_file(off_file = args.file) +alpha_complex = gd.AlphaComplex(points = points) +if args.max_alpha_square is not None: + print("with max_edge_length=", args.max_alpha_square) + simplex_tree = alpha_complex.create_simplex_tree( + max_alpha_square=args.max_alpha_square + ) +else: + simplex_tree = alpha_complex.create_simplex_tree() + +print("Number of simplices=", simplex_tree.num_simplices()) + +diag = simplex_tree.persistence() +print("betti_numbers()=", simplex_tree.betti_numbers()) +if args.no_diagram == False: + import matplotlib.pyplot as plot + gd.plot_persistence_diagram(diag, band=args.band) + plot.show() diff --git a/src/python/example/alpha_complex_from_generated_points_on_sphere_example.py b/src/python/example/alpha_complex_from_generated_points_on_sphere_example.py new file mode 100644 index 00000000..3558077e --- /dev/null +++ b/src/python/example/alpha_complex_from_generated_points_on_sphere_example.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python + +from gudhi.datasets.generators import _points +from gudhi import AlphaComplex + + +""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. + See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. + Author(s): Hind Montassif + + Copyright (C) 2021 Inria + + Modification(s): + - YYYY/MM Author: Description of the modification +""" + +__author__ = "Hind Montassif" +__copyright__ = "Copyright (C) 2021 Inria" +__license__ = "MIT" + +print("#####################################################################") +print("AlphaComplex creation from generated points on sphere") + + +gen_points = _points.sphere(n_samples = 50, ambient_dim = 2, radius = 1, sample = "random") + +# Create an alpha complex +alpha_complex = AlphaComplex(points = gen_points) +simplex_tree = alpha_complex.create_simplex_tree() + +result_str = 'Alpha complex is of dimension ' + repr(simplex_tree.dimension()) + ' - ' + \ + repr(simplex_tree.num_simplices()) + ' simplices - ' + \ + repr(simplex_tree.num_vertices()) + ' vertices.' +print(result_str) + diff --git a/src/python/example/alpha_complex_from_points_example.py b/src/python/example/alpha_complex_from_points_example.py index a746998c..5d5ca66a 100755 --- a/src/python/example/alpha_complex_from_points_example.py +++ b/src/python/example/alpha_complex_from_points_example.py @@ -19,7 +19,7 @@ __license__ = "MIT" print("#####################################################################") print("AlphaComplex creation from points") alpha_complex = AlphaComplex(points=[[0, 0], [1, 0], [0, 1], [1, 1]]) -simplex_tree = alpha_complex.create_simplex_tree(max_alpha_square=60.0) +simplex_tree = alpha_complex.create_simplex_tree() if simplex_tree.find([0, 1]): print("[0, 1] Found !!") @@ -47,9 +47,17 @@ else: print("[4] Not found...") print("dimension=", simplex_tree.dimension()) -print("filtrations=", simplex_tree.get_filtration()) +print("filtrations=") +for simplex_with_filtration in simplex_tree.get_filtration(): + print("(%s, %.2f)" % tuple(simplex_with_filtration)) + print("star([0])=", simplex_tree.get_star([0])) print("coface([0], 1)=", simplex_tree.get_cofaces([0], 1)) print("point[0]=", alpha_complex.get_point(0)) -print("point[5]=", alpha_complex.get_point(5)) +try: + print("point[5]=", alpha_complex.get_point(5)) +except IndexError: + pass +else: + assert False diff --git a/src/python/example/alpha_rips_persistence_bottleneck_distance.py b/src/python/example/alpha_rips_persistence_bottleneck_distance.py index 086307ee..6b97fb3b 100755 --- a/src/python/example/alpha_rips_persistence_bottleneck_distance.py +++ b/src/python/example/alpha_rips_persistence_bottleneck_distance.py @@ -1,11 +1,14 @@ #!/usr/bin/env python -import gudhi +import gudhi as gd import argparse import math +import numpy as np -""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. - See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. +""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - + which is released under MIT. + See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full + license details. Author(s): Vincent Rouvreau Copyright (C) 2016 Inria @@ -32,74 +35,60 @@ parser.add_argument("-t", "--threshold", type=float, default=0.5) parser.add_argument("-d", "--max_dimension", type=int, default=1) args = parser.parse_args() -with open(args.file, "r") as f: - first_line = f.readline() - if (first_line == "OFF\n") or (first_line == "nOFF\n"): - point_cloud = gudhi.read_off(off_file=args.file) - print("#####################################################################") - print("RipsComplex creation from points read in a OFF file") - - message = "RipsComplex with max_edge_length=" + repr(args.threshold) - print(message) - - rips_complex = gudhi.RipsComplex( - points=point_cloud, max_edge_length=args.threshold - ) - - rips_stree = rips_complex.create_simplex_tree(max_dimension=args.max_dimension) - - message = "Number of simplices=" + repr(rips_stree.num_simplices()) - print(message) - - rips_diag = rips_stree.persistence() - - print("#####################################################################") - print("AlphaComplex creation from points read in a OFF file") - - message = "AlphaComplex with max_edge_length=" + repr(args.threshold) - print(message) - - alpha_complex = gudhi.AlphaComplex(points=point_cloud) - alpha_stree = alpha_complex.create_simplex_tree( - max_alpha_square=(args.threshold * args.threshold) - ) - - message = "Number of simplices=" + repr(alpha_stree.num_simplices()) - print(message) - - alpha_diag = alpha_stree.persistence() - - max_b_distance = 0.0 - for dim in range(args.max_dimension): - # Alpha persistence values needs to be transform because filtration - # values are alpha square values - funcs = [math.sqrt, math.sqrt] - alpha_intervals = [] - for interval in alpha_stree.persistence_intervals_in_dimension(dim): - alpha_intervals.append( - map(lambda func, value: func(value), funcs, interval) - ) - - rips_intervals = rips_stree.persistence_intervals_in_dimension(dim) - bottleneck_distance = gudhi.bottleneck_distance( - rips_intervals, alpha_intervals - ) - message = ( - "In dimension " - + repr(dim) - + ", bottleneck distance = " - + repr(bottleneck_distance) - ) - print(message) - max_b_distance = max(bottleneck_distance, max_b_distance) - - print( - "================================================================================" - ) - message = "Bottleneck distance is " + repr(max_b_distance) - print(message) - - else: - print(args.file, "is not a valid OFF file") - - f.close() +point_cloud = gd.read_points_from_off_file(off_file=args.file) +print("##############################################################") +print("RipsComplex creation from points read in a OFF file") + +message = "RipsComplex with max_edge_length=" + repr(args.threshold) +print(message) + +rips_complex = gd.RipsComplex( + points=point_cloud, max_edge_length=args.threshold +) + +rips_stree = rips_complex.create_simplex_tree( + max_dimension=args.max_dimension) + +message = "Number of simplices=" + repr(rips_stree.num_simplices()) +print(message) + +rips_stree.compute_persistence() + +print("##############################################################") +print("AlphaComplex creation from points read in a OFF file") + +message = "AlphaComplex with max_edge_length=" + repr(args.threshold) +print(message) + +alpha_complex = gd.AlphaComplex(points=point_cloud) +alpha_stree = alpha_complex.create_simplex_tree( + max_alpha_square=(args.threshold * args.threshold) +) + +message = "Number of simplices=" + repr(alpha_stree.num_simplices()) +print(message) + +alpha_stree.compute_persistence() + +max_b_distance = 0.0 +for dim in range(args.max_dimension): + # Alpha persistence values needs to be transform because filtration + # values are alpha square values + alpha_intervals = np.sqrt(alpha_stree.persistence_intervals_in_dimension(dim)) + + rips_intervals = rips_stree.persistence_intervals_in_dimension(dim) + bottleneck_distance = gd.bottleneck_distance( + rips_intervals, alpha_intervals + ) + message = ( + "In dimension " + + repr(dim) + + ", bottleneck distance = " + + repr(bottleneck_distance) + ) + print(message) + max_b_distance = max(bottleneck_distance, max_b_distance) + +print("==============================================================") +message = "Bottleneck distance is " + repr(max_b_distance) +print(message) diff --git a/src/python/example/diagram_vectorizations_distances_kernels.py b/src/python/example/diagram_vectorizations_distances_kernels.py new file mode 100755 index 00000000..2801576e --- /dev/null +++ b/src/python/example/diagram_vectorizations_distances_kernels.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python + +import matplotlib.pyplot as plt +import numpy as np +from sklearn.kernel_approximation import RBFSampler +from sklearn.preprocessing import MinMaxScaler + +from gudhi.representations import (DiagramSelector, Clamping, Landscape, Silhouette, BettiCurve, ComplexPolynomial,\ + TopologicalVector, DiagramScaler, BirthPersistenceTransform,\ + PersistenceImage, PersistenceWeightedGaussianKernel, Entropy, \ + PersistenceScaleSpaceKernel, SlicedWassersteinDistance,\ + SlicedWassersteinKernel, PersistenceFisherKernel, WassersteinDistance) + +D1 = np.array([[0.,4.],[1.,2.],[3.,8.],[6.,8.], [0., np.inf], [5., np.inf]]) + +proc1 = DiagramSelector(use=True, point_type="finite") +proc2 = DiagramScaler(use=True, scalers=[([0,1], MinMaxScaler())]) +proc3 = DiagramScaler(use=True, scalers=[([1], Clamping(maximum=.9))]) +D1 = proc3(proc2(proc1(D1))) + +plt.scatter(D1[:,0], D1[:,1]) +plt.plot([0.,1.],[0.,1.]) +plt.title("Test Persistence Diagram for vector methods") +plt.show() + +LS = Landscape(resolution=1000) +L = LS(D1) +plt.plot(L[:1000]) +plt.plot(L[1000:2000]) +plt.plot(L[2000:3000]) +plt.title("Landscape") +plt.show() + +def pow(n): + return lambda x: np.power(x[1]-x[0],n) + +SH = Silhouette(resolution=1000, weight=pow(2)) +plt.plot(SH(D1)) +plt.title("Silhouette") +plt.show() + +BC = BettiCurve(resolution=1000) +plt.plot(BC(D1)) +plt.title("Betti Curve") +plt.show() + +CP = ComplexPolynomial(threshold=-1, polynomial_type="T") +print("Complex polynomial is " + str(CP(D1))) + +TV = TopologicalVector(threshold=-1) +print("Topological vector is " + str(TV(D1))) + +PI = PersistenceImage(bandwidth=.1, weight=lambda x: x[1], im_range=[0,1,0,1], resolution=[100,100]) +plt.imshow(np.flip(np.reshape(PI(D1), [100,100]), 0)) +plt.title("Persistence Image") +plt.show() + +ET = Entropy(mode="scalar") +print("Entropy statistic is " + str(ET(D1))) + +ET = Entropy(mode="vector", normalized=False) +plt.plot(ET(D1)) +plt.title("Entropy function") +plt.show() + +D2 = np.array([[1.,5.],[3.,6.],[2.,7.]]) +D2 = proc3(proc2(proc1(D2))) + +plt.scatter(D1[:,0], D1[:,1]) +plt.scatter(D2[:,0], D2[:,1]) +plt.plot([0.,1.],[0.,1.]) +plt.title("Test Persistence Diagrams for kernel methods") +plt.show() + +def arctan(C,p): + return lambda x: C*np.arctan(np.power(x[1], p)) + +PWG = PersistenceWeightedGaussianKernel(bandwidth=1., kernel_approx=None, weight=arctan(1.,1.)) +print("PWG kernel is " + str(PWG(D1, D2))) + +PWG = PersistenceWeightedGaussianKernel(kernel_approx=RBFSampler(gamma=1./2, n_components=100000).fit(np.ones([1,2])), weight=arctan(1.,1.)) +print("Approximate PWG kernel is " + str(PWG(D1, D2))) + +PSS = PersistenceScaleSpaceKernel(bandwidth=1.) +print("PSS kernel is " + str(PSS(D1, D2))) + +PSS = PersistenceScaleSpaceKernel(kernel_approx=RBFSampler(gamma=1./2, n_components=100000).fit(np.ones([1,2]))) +print("Approximate PSS kernel is " + str(PSS(D1, D2))) + +sW = SlicedWassersteinDistance(num_directions=100) +print("SW distance is " + str(sW(D1, D2))) + +SW = SlicedWassersteinKernel(num_directions=100, bandwidth=1.) +print("SW kernel is " + str(SW(D1, D2))) + +try: + W = WassersteinDistance(order=2, internal_p=2, mode="pot") + print("Wasserstein distance (POT) is " + str(W(D1, D2))) +except ImportError: + print("WassersteinDistance (POT) is not available, you may be missing pot.") + +W = WassersteinDistance(order=2, internal_p=2, mode="hera", delta=0.0001) +print("Wasserstein distance (hera) is " + str(W(D1, D2))) + +try: + from gudhi.representations import BottleneckDistance + W = BottleneckDistance(epsilon=.001) + print("Bottleneck distance is " + str(W(D1, D2))) +except ImportError: + print("BottleneckDistance is not available, you may be missing CGAL.") + +PF = PersistenceFisherKernel(bandwidth_fisher=1., bandwidth=1.) +print("PF kernel is " + str(PF(D1, D2))) + +PF = PersistenceFisherKernel(bandwidth_fisher=1., bandwidth=1., kernel_approx=RBFSampler(gamma=1./2, n_components=100000).fit(np.ones([1,2]))) +print("Approximate PF kernel is " + str(PF(D1, D2))) diff --git a/src/python/example/euclidean_strong_witness_complex_diagram_persistence_from_off_file_example.py b/src/python/example/euclidean_strong_witness_complex_diagram_persistence_from_off_file_example.py index 610ba44f..4e97cfe3 100755 --- a/src/python/example/euclidean_strong_witness_complex_diagram_persistence_from_off_file_example.py +++ b/src/python/example/euclidean_strong_witness_complex_diagram_persistence_from_off_file_example.py @@ -1,10 +1,14 @@ #!/usr/bin/env python -import gudhi import argparse +import errno +import os +import gudhi -""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. - See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. +""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - + which is released under MIT. + See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full + license details. Author(s): Vincent Rouvreau Copyright (C) 2016 Inria @@ -43,10 +47,11 @@ args = parser.parse_args() with open(args.file, "r") as f: first_line = f.readline() if (first_line == "OFF\n") or (first_line == "nOFF\n"): - print("#####################################################################") - print("EuclideanStrongWitnessComplex creation from points read in a OFF file") + print("##############################################################") + print("EuclideanStrongWitnessComplex creation from points read "\ + "in a OFF file") - witnesses = gudhi.read_off(off_file=args.file) + witnesses = gudhi.read_points_from_off_file(off_file=args.file) landmarks = gudhi.pick_n_random_points( points=witnesses, nb_points=args.number_of_landmarks ) @@ -63,7 +68,8 @@ with open(args.file, "r") as f: witnesses=witnesses, landmarks=landmarks ) simplex_tree = witness_complex.create_simplex_tree( - max_alpha_square=args.max_alpha_square, limit_dimension=args.limit_dimension + max_alpha_square=args.max_alpha_square, + limit_dimension=args.limit_dimension ) message = "Number of simplices=" + repr(simplex_tree.num_simplices()) @@ -75,9 +81,11 @@ with open(args.file, "r") as f: print(simplex_tree.betti_numbers()) if args.no_diagram == False: - pplot = gudhi.plot_persistence_diagram(diag, band=args.band) - pplot.show() + import matplotlib.pyplot as plot + gudhi.plot_persistence_diagram(diag, band=args.band) + plot.show() else: - print(args.file, "is not a valid OFF file") + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), + args.file) f.close() diff --git a/src/python/example/euclidean_witness_complex_diagram_persistence_from_off_file_example.py b/src/python/example/euclidean_witness_complex_diagram_persistence_from_off_file_example.py index 7587b732..29076c74 100755 --- a/src/python/example/euclidean_witness_complex_diagram_persistence_from_off_file_example.py +++ b/src/python/example/euclidean_witness_complex_diagram_persistence_from_off_file_example.py @@ -1,10 +1,14 @@ #!/usr/bin/env python -import gudhi import argparse +import errno +import os +import gudhi -""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. - See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. +""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - + which is released under MIT. + See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full + license details. Author(s): Vincent Rouvreau Copyright (C) 2016 Inria @@ -45,7 +49,7 @@ with open(args.file, "r") as f: print("#####################################################################") print("EuclideanWitnessComplex creation from points read in a OFF file") - witnesses = gudhi.read_off(off_file=args.file) + witnesses = gudhi.read_points_from_off_file(off_file=args.file) landmarks = gudhi.pick_n_random_points( points=witnesses, nb_points=args.number_of_landmarks ) @@ -74,9 +78,11 @@ with open(args.file, "r") as f: print(simplex_tree.betti_numbers()) if args.no_diagram == False: - pplot = gudhi.plot_persistence_diagram(diag, band=args.band) - pplot.show() + import matplotlib.pyplot as plot + gudhi.plot_persistence_diagram(diag, band=args.band) + plot.show() else: - print(args.file, "is not a valid OFF file") + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), + args.file) f.close() diff --git a/src/python/example/gudhi_graphical_tools_example.py b/src/python/example/gudhi_graphical_tools_example.py index 3b0ca54d..37ecbf53 100755 --- a/src/python/example/gudhi_graphical_tools_example.py +++ b/src/python/example/gudhi_graphical_tools_example.py @@ -1,5 +1,6 @@ #!/usr/bin/env python +import matplotlib.pyplot as plot import gudhi """ This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. @@ -29,15 +30,24 @@ persistence = [ (0, (0.0, 1.0)), ] gudhi.plot_persistence_barcode(persistence) +plot.show() print("#####################################################################") print("Show diagram persistence example") -pplot = gudhi.plot_persistence_diagram(persistence) -pplot.show() +gudhi.plot_persistence_diagram(persistence) +plot.show() print("#####################################################################") print("Show diagram persistence example with a confidence band") -pplot = gudhi.plot_persistence_diagram(persistence, band=0.2) -pplot.show() +gudhi.plot_persistence_diagram(persistence, band=0.2) +plot.show() + +print("#####################################################################") +print("Show barcode and diagram persistence side by side example") +fig, axes = plot.subplots(nrows=1, ncols=2) +gudhi.plot_persistence_barcode(persistence, axes = axes[0]) +gudhi.plot_persistence_diagram(persistence, axes = axes[1]) +fig.suptitle("barcode versus diagram") +plot.show() diff --git a/src/python/example/periodic_cubical_complex_barcode_persistence_from_perseus_file_example.py b/src/python/example/periodic_cubical_complex_barcode_persistence_from_perseus_file_example.py index 9cb855cd..ee3290c6 100755 --- a/src/python/example/periodic_cubical_complex_barcode_persistence_from_perseus_file_example.py +++ b/src/python/example/periodic_cubical_complex_barcode_persistence_from_perseus_file_example.py @@ -1,10 +1,14 @@ #!/usr/bin/env python -import gudhi import argparse +import errno +import os +import gudhi -""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. - See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. +""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - + which is released under MIT. + See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full + license details. Author(s): Vincent Rouvreau Copyright (C) 2016 Inria @@ -56,9 +60,10 @@ parser.add_argument( args = parser.parse_args() if is_file_perseus(args.file): - print("#####################################################################") + print("##################################################################") print("PeriodicCubicalComplex creation") - periodic_cubical_complex = gudhi.PeriodicCubicalComplex(perseus_file=args.file) + periodic_cubical_complex = gudhi.PeriodicCubicalComplex( + perseus_file=args.file) print("persistence(homology_coeff_field=3, min_persistence=0)=") diag = periodic_cubical_complex.persistence( @@ -69,6 +74,9 @@ if is_file_perseus(args.file): print("betti_numbers()=") print(periodic_cubical_complex.betti_numbers()) if args.no_barcode == False: + import matplotlib.pyplot as plot gudhi.plot_persistence_barcode(diag) + plot.show() else: - print(args.file, "is not a valid perseus style file") + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), + args.file) diff --git a/src/python/example/plot_alpha_complex.py b/src/python/example/plot_alpha_complex.py new file mode 100755 index 00000000..0924619b --- /dev/null +++ b/src/python/example/plot_alpha_complex.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python + +import numpy as np +import gudhi as gd +points = gd.read_points_from_off_file(off_file = '../../data/points/tore3D_1307.off') +ac = gd.AlphaComplex(points = points) +st = ac.create_simplex_tree() +points = np.array([ac.get_point(i) for i in range(st.num_vertices())]) +# We want to plot the alpha-complex with alpha=0.1. +# We are only going to plot the triangles +triangles = np.array([s[0] for s in st.get_skeleton(2) if len(s[0])==3 and s[1] <= .1]) + +# First possibility: plotly +import plotly.graph_objects as go +fig = go.Figure(data=[ + go.Mesh3d( + x=points[:,0], + y=points[:,1], + z=points[:,2], + i = triangles[:,0], + j = triangles[:,1], + k = triangles[:,2], + ) +]) +fig.show() + +# Second possibility: matplotlib +from mpl_toolkits.mplot3d import Axes3D +import matplotlib.pyplot as plt +fig = plt.figure() +ax = fig.gca(projection='3d') +ax.plot_trisurf(points[:,0], points[:,1], points[:,2], triangles=triangles) +plt.show() + +# Third possibility: mayavi +from mayavi import mlab +mlab.triangular_mesh(points[:,0], points[:,1], points[:,2], triangles); +mlab.show() diff --git a/src/python/example/plot_rips_complex.py b/src/python/example/plot_rips_complex.py new file mode 100755 index 00000000..214a3c0a --- /dev/null +++ b/src/python/example/plot_rips_complex.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python + +import numpy as np +import gudhi +points = np.array(gudhi.read_points_from_off_file('../../data/points/Kl.off')) +rc = gudhi.RipsComplex(points=points, max_edge_length=.2) +st = rc.create_simplex_tree(max_dimension=2) +# We are only going to plot the triangles +triangles = np.array([s[0] for s in st.get_skeleton(2) if len(s[0])==3]) + +# First possibility: plotly +import plotly.graph_objects as go +fig = go.Figure(data=[ + go.Mesh3d( + # Use the first 3 coordinates, but we could as easily pick others + x=points[:,0], + y=points[:,1], + z=points[:,2], + i = triangles[:,0], + j = triangles[:,1], + k = triangles[:,2], + ) +]) +fig.show() + +# Second possibility: matplotlib +from mpl_toolkits.mplot3d import Axes3D +import matplotlib.pyplot as plt +fig = plt.figure() +ax = fig.gca(projection='3d') +ax.plot_trisurf(points[:,0], points[:,1], points[:,2], triangles=triangles) +plt.show() + +# Third possibility: mayavi +# (this may take a while) +from mayavi import mlab +mlab.triangular_mesh(points[:,0], points[:,1], points[:,2], triangles); +mlab.show() diff --git a/src/python/example/plot_simplex_tree_dim012.py b/src/python/example/plot_simplex_tree_dim012.py new file mode 100755 index 00000000..5b962131 --- /dev/null +++ b/src/python/example/plot_simplex_tree_dim012.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +import numpy as np +import gudhi + +# Coordinates of the points +points=np.array([[0,0,0],[1,0,0],[0,1,0],[0,0,1],[1,1,1],[1,1,0],[0,1,1]]) +# Build the simplicial complex with a tetrahedon, an edge and an isolated vertex +cplx=gudhi.SimplexTree() +cplx.insert([1,2,3,5]) +cplx.insert([4,6]) +cplx.insert([0]) +# List of triangles (point indices) +triangles = np.array([s[0] for s in cplx.get_skeleton(2) if len(s[0])==3]) +# List of edges (point coordinates) +edges = [] +for s in cplx.get_skeleton(1): + e = s[0] + if len(e) == 2: + edges.append(points[[e[0],e[1]]]) + +## With plotly +import plotly.graph_objects as go +# Plot triangles +f2 = go.Mesh3d( + x=points[:,0], + y=points[:,1], + z=points[:,2], + i = triangles[:,0], + j = triangles[:,1], + k = triangles[:,2], + ) +# Plot points +f0 = go.Scatter3d(x=points[:,0], y=points[:,1], z=points[:,2], mode="markers") +data = [f2, f0] +# Plot edges +for pts in edges: + seg = go.Scatter3d(x=pts[:,0],y=pts[:,1],z=pts[:,2],mode="lines",line=dict(color='green')) + data.append(seg) +fig = go.Figure(data=data,layout=dict(showlegend=False)) +# By default plotly would give each edge its own color and legend, that's too much +fig.show() + +## With matplotlib +from mpl_toolkits.mplot3d import Axes3D +from mpl_toolkits.mplot3d.art3d import Line3DCollection +import matplotlib.pyplot as plt +fig = plt.figure() +ax = fig.gca(projection='3d') +# Plot triangles +ax.plot_trisurf(points[:,0], points[:,1], points[:,2], triangles=triangles) +# Plot points +ax.scatter3D(points[:,0], points[:,1], points[:,2]) +# Plot edges +ax.add_collection3d(Line3DCollection(segments=edges)) +plt.show() + +## With mayavi +from mayavi import mlab +# Plot triangles +mlab.triangular_mesh(points[:,0], points[:,1], points[:,2], triangles); +# Plot points +mlab.points3d(points[:,0], points[:,1], points[:,2]) +# Plot edges +for pts in edges: + mlab.plot3d(pts[:,0],pts[:,1],pts[:,2],tube_radius=None) +mlab.show() diff --git a/src/python/example/rips_complex_diagram_persistence_from_correlation_matrix_file_example.py b/src/python/example/rips_complex_diagram_persistence_from_correlation_matrix_file_example.py index 3571580b..0b35dbc5 100755 --- a/src/python/example/rips_complex_diagram_persistence_from_correlation_matrix_file_example.py +++ b/src/python/example/rips_complex_diagram_persistence_from_correlation_matrix_file_example.py @@ -1,8 +1,8 @@ #!/usr/bin/env python -import gudhi import sys import argparse +import gudhi """ This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. @@ -40,7 +40,7 @@ parser.add_argument( args = parser.parse_args() if not (-1.0 < args.min_edge_correlation < 1.0): - print("Wrong value of the treshold corelation (should be between -1 and 1).") + print("Wrong value of the threshold corelation (should be between -1 and 1).") sys.exit(1) print("#####################################################################") @@ -83,5 +83,6 @@ invert_diag = [ ] if args.no_diagram == False: - pplot = gudhi.plot_persistence_diagram(invert_diag, band=args.band) - pplot.show() + import matplotlib.pyplot as plot + gudhi.plot_persistence_diagram(invert_diag, band=args.band) + plot.show() diff --git a/src/python/example/rips_complex_diagram_persistence_from_distance_matrix_file_example.py b/src/python/example/rips_complex_diagram_persistence_from_distance_matrix_file_example.py index 0b9a9ba9..8a9cc857 100755 --- a/src/python/example/rips_complex_diagram_persistence_from_distance_matrix_file_example.py +++ b/src/python/example/rips_complex_diagram_persistence_from_distance_matrix_file_example.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -import gudhi import argparse +import gudhi """ This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. @@ -21,11 +21,12 @@ parser = argparse.ArgumentParser( description="RipsComplex creation from " "a distance matrix read in a csv file.", epilog="Example: " "example/rips_complex_diagram_persistence_from_distance_matrix_file_example.py " - "-f ../data/distance_matrix/lower_triangular_distance_matrix.csv -e 12.0 -d 3" + "-f ../data/distance_matrix/lower_triangular_distance_matrix.csv -s , -e 12.0 -d 3" "- Constructs a Rips complex with the " "distance matrix from the given csv file.", ) parser.add_argument("-f", "--file", type=str, required=True) +parser.add_argument("-s", "--separator", type=str, required=True) parser.add_argument("-e", "--max_edge_length", type=float, default=0.5) parser.add_argument("-d", "--max_dimension", type=int, default=1) parser.add_argument("-b", "--band", type=float, default=0.0) @@ -44,7 +45,7 @@ print("RipsComplex creation from distance matrix read in a csv file") message = "RipsComplex with max_edge_length=" + repr(args.max_edge_length) print(message) -distance_matrix = gudhi.read_lower_triangular_matrix_from_csv_file(csv_file=args.file) +distance_matrix = gudhi.read_lower_triangular_matrix_from_csv_file(csv_file=args.file, separator=args.separator) rips_complex = gudhi.RipsComplex( distance_matrix=distance_matrix, max_edge_length=args.max_edge_length ) @@ -59,5 +60,6 @@ print("betti_numbers()=") print(simplex_tree.betti_numbers()) if args.no_diagram == False: - pplot = gudhi.plot_persistence_diagram(diag, band=args.band) - pplot.show() + import matplotlib.pyplot as plot + gudhi.plot_persistence_diagram(diag, band=args.band) + plot.show() diff --git a/src/python/example/rips_complex_diagram_persistence_from_off_file_example.py b/src/python/example/rips_complex_diagram_persistence_from_off_file_example.py index 2b335bba..e80233a9 100755 --- a/src/python/example/rips_complex_diagram_persistence_from_off_file_example.py +++ b/src/python/example/rips_complex_diagram_persistence_from_off_file_example.py @@ -1,10 +1,14 @@ #!/usr/bin/env python -import gudhi import argparse +import errno +import os +import gudhi -""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. - See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. +""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - + which is released under MIT. + See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full + license details. Author(s): Vincent Rouvreau Copyright (C) 2016 Inria @@ -41,13 +45,14 @@ args = parser.parse_args() with open(args.file, "r") as f: first_line = f.readline() if (first_line == "OFF\n") or (first_line == "nOFF\n"): - print("#####################################################################") + print("##############################################################") print("RipsComplex creation from points read in a OFF file") - message = "RipsComplex with max_edge_length=" + repr(args.max_edge_length) + message = "RipsComplex with max_edge_length=" + \ + repr(args.max_edge_length) print(message) - point_cloud = gudhi.read_off(off_file=args.file) + point_cloud = gudhi.read_points_from_off_file(off_file=args.file) rips_complex = gudhi.RipsComplex( points=point_cloud, max_edge_length=args.max_edge_length ) @@ -64,9 +69,11 @@ with open(args.file, "r") as f: print(simplex_tree.betti_numbers()) if args.no_diagram == False: - pplot = gudhi.plot_persistence_diagram(diag, band=args.band) - pplot.show() + import matplotlib.pyplot as plot + gudhi.plot_persistence_diagram(diag, band=args.band) + plot.show() else: - print(args.file, "is not a valid OFF file") + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), + args.file) f.close() diff --git a/src/python/example/rips_complex_edge_collapse_example.py b/src/python/example/rips_complex_edge_collapse_example.py new file mode 100755 index 00000000..b26eb9fc --- /dev/null +++ b/src/python/example/rips_complex_edge_collapse_example.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python + +import gudhi +import matplotlib.pyplot as plt +import time + +""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. + See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. + Author(s): Vincent Rouvreau + + Copyright (C) 2016 Inria + + Modification(s): + - YYYY/MM Author: Description of the modification +""" + +__author__ = "Vincent Rouvreau" +__copyright__ = "Copyright (C) 2020 Inria" +__license__ = "MIT" + + +print("#####################################################################") +print("RipsComplex (only the one-skeleton) creation from tore3D_300.off file") + +off_file = gudhi.__root_source_dir__ + '/data/points/tore3D_300.off' +point_cloud = gudhi.read_points_from_off_file(off_file = off_file) +rips_complex = gudhi.RipsComplex(points=point_cloud, max_edge_length=12.0) +simplex_tree = rips_complex.create_simplex_tree(max_dimension=1) +print('1. Rips complex is of dimension ', simplex_tree.dimension(), ' - ', + simplex_tree.num_simplices(), ' simplices - ', + simplex_tree.num_vertices(), ' vertices.') + +# Expansion of this one-skeleton would require a lot of memory. Let's collapse it +start = time.process_time() +simplex_tree.collapse_edges() +print('2. Rips complex is of dimension ', simplex_tree.dimension(), ' - ', + simplex_tree.num_simplices(), ' simplices - ', + simplex_tree.num_vertices(), ' vertices.') +simplex_tree.expansion(3) +diag = simplex_tree.persistence() +print("Collapse, expansion and persistence computation took ", time.process_time() - start, " sec.") + +# Use subplots to display diagram and density side by side +fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 5)) +gudhi.plot_persistence_diagram(diag, axes=axes[0]) +axes[0].set_title("Persistence after 1 collapse") + +# Collapse can be performed several times. Let's collapse it 3 times +start = time.process_time() +simplex_tree.collapse_edges(nb_iterations = 3) +print('3. Rips complex is of dimension ', simplex_tree.dimension(), ' - ', + simplex_tree.num_simplices(), ' simplices - ', + simplex_tree.num_vertices(), ' vertices.') +simplex_tree.expansion(3) +diag = simplex_tree.persistence() +print("Collapse, expansion and persistence computation took ", time.process_time() - start, " sec.") + +gudhi.plot_persistence_diagram(diag, axes=axes[1]) +axes[1].set_title("Persistence after 3 more collapses") + +# Plot the 2 persistence diagrams side to side to check the persistence is the same +plt.show()
\ No newline at end of file diff --git a/src/python/example/rips_complex_from_points_example.py b/src/python/example/rips_complex_from_points_example.py index 59d8a261..c05703c6 100755 --- a/src/python/example/rips_complex_from_points_example.py +++ b/src/python/example/rips_complex_from_points_example.py @@ -22,6 +22,9 @@ rips = gudhi.RipsComplex(points=[[0, 0], [1, 0], [0, 1], [1, 1]], max_edge_lengt simplex_tree = rips.create_simplex_tree(max_dimension=1) -print("filtrations=", simplex_tree.get_filtration()) +print("filtrations=") +for simplex_with_filtration in simplex_tree.get_filtration(): + print("(%s, %.2f)" % tuple(simplex_with_filtration)) + print("star([0])=", simplex_tree.get_star([0])) print("coface([0], 1)=", simplex_tree.get_cofaces([0], 1)) diff --git a/src/python/example/rips_persistence_diagram.py b/src/python/example/rips_persistence_diagram.py index f5897d7b..2a90b4bc 100755 --- a/src/python/example/rips_persistence_diagram.py +++ b/src/python/example/rips_persistence_diagram.py @@ -1,5 +1,6 @@ #!/usr/bin/env python +import matplotlib.pyplot as plot import gudhi """ This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. @@ -26,5 +27,5 @@ simplex_tree = rips.create_simplex_tree(max_dimension=1) diag = simplex_tree.persistence(homology_coeff_field=2, min_persistence=0) print("diag=", diag) -pplot = gudhi.plot_persistence_diagram(diag) -pplot.show() +gudhi.plot_persistence_diagram(diag) +plot.show() diff --git a/src/python/example/simplex_tree_example.py b/src/python/example/simplex_tree_example.py index 30de00da..c4635dc5 100755 --- a/src/python/example/simplex_tree_example.py +++ b/src/python/example/simplex_tree_example.py @@ -38,8 +38,14 @@ else: print("dimension=", st.dimension()) -st.initialize_filtration() -print("filtration=", st.get_filtration()) +print("simplices=") +for simplex_with_filtration in st.get_simplices(): + print("(%s, %.2f)" % tuple(simplex_with_filtration)) + +print("filtration=") +for simplex_with_filtration in st.get_filtration(): + print("(%s, %.2f)" % tuple(simplex_with_filtration)) + print("filtration[1, 2]=", st.filtration([1, 2])) print("filtration[4, 2]=", st.filtration([4, 2])) diff --git a/src/python/example/sparse_rips_persistence_diagram.py b/src/python/example/sparse_rips_persistence_diagram.py index 671d5e34..410a6a86 100755 --- a/src/python/example/sparse_rips_persistence_diagram.py +++ b/src/python/example/sparse_rips_persistence_diagram.py @@ -1,5 +1,6 @@ #!/usr/bin/env python +import matplotlib.pyplot as plot import gudhi """ This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. @@ -28,5 +29,5 @@ simplex_tree = rips.create_simplex_tree(max_dimension=2) diag = simplex_tree.persistence(homology_coeff_field=2, min_persistence=0) print("diag=", diag) -pplot = gudhi.plot_persistence_diagram(diag) -pplot.show() +gudhi.plot_persistence_diagram(diag) +plot.show() diff --git a/src/python/example/tangential_complex_plain_homology_from_off_file_example.py b/src/python/example/tangential_complex_plain_homology_from_off_file_example.py index 456bc9eb..a4b4e9f5 100755 --- a/src/python/example/tangential_complex_plain_homology_from_off_file_example.py +++ b/src/python/example/tangential_complex_plain_homology_from_off_file_example.py @@ -1,10 +1,14 @@ #!/usr/bin/env python -import gudhi import argparse +import errno +import os +import gudhi -""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. - See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. +""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - + which is released under MIT. + See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full + license details. Author(s): Vincent Rouvreau Copyright (C) 2016 Inria @@ -18,7 +22,7 @@ __copyright__ = "Copyright (C) 2016 Inria" __license__ = "MIT" parser = argparse.ArgumentParser( - description="TangentialComplex creation from " "points read in a OFF file.", + description="TangentialComplex creation from points read in a OFF file.", epilog="Example: " "example/tangential_complex_plain_homology_from_off_file_example.py " "-f ../data/points/tore3D_300.off -i 3" @@ -40,10 +44,11 @@ args = parser.parse_args() with open(args.file, "r") as f: first_line = f.readline() if (first_line == "OFF\n") or (first_line == "nOFF\n"): - print("#####################################################################") + print("##############################################################") print("TangentialComplex creation from points read in a OFF file") - tc = gudhi.TangentialComplex(intrisic_dim=args.intrisic_dim, off_file=args.file) + tc = gudhi.TangentialComplex(intrisic_dim=args.intrisic_dim, + off_file=args.file) tc.compute_tangential_complex() st = tc.create_simplex_tree() @@ -56,9 +61,11 @@ with open(args.file, "r") as f: print(st.betti_numbers()) if args.no_diagram == False: - pplot = gudhi.plot_persistence_diagram(diag, band=args.band) - pplot.show() + import matplotlib.pyplot as plot + gudhi.plot_persistence_diagram(diag, band=args.band) + plot.show() else: - print(args.file, "is not a valid OFF file") + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), + args.file) f.close() |