From 17da2842a3af3db3abec7c2ce03f77dad47ef5dc Mon Sep 17 00:00:00 2001 From: ROUVREAU Vincent Date: Tue, 15 Jun 2021 18:01:20 +0200 Subject: Remove deprecated max_barcodes in plot_persistence_barcode and max_plots in plot_persistence_diagram. Fix #453 and factorize code --- src/python/gudhi/persistence_graphical_tools.py | 63 ++++++++++++------------- 1 file changed, 29 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/python/gudhi/persistence_graphical_tools.py b/src/python/gudhi/persistence_graphical_tools.py index 848dc03e..460e2558 100644 --- a/src/python/gudhi/persistence_graphical_tools.py +++ b/src/python/gudhi/persistence_graphical_tools.py @@ -12,6 +12,7 @@ from os import path from math import isfinite import numpy as np from functools import lru_cache +import warnings from gudhi.reader_utils import read_persistence_intervals_in_dimension from gudhi.reader_utils import read_persistence_intervals_grouped_by_dimension @@ -58,6 +59,26 @@ def _array_handler(a): else: return a +def _limit_to_max_intervals(persistence, max_intervals, key): + '''This function returns truncated persistence if length is bigger than max_intervals. + :param persistence: Persistence intervals values list. Can be grouped by dimension or not. + :type persistence: an array of (dimension, array of (birth, death)) or an array of (birth, death). + :param max_intervals: maximal number of intervals to display. + Selected intervals are those with the longest life time. Set it + to 0 to see all. Default value is 1000. + :type max_intervals: int. + :param key: key function for sort algorithm. + :type key: function or lambda. + ''' + if max_intervals > 0 and max_intervals < len(persistence): + warnings.warn('There are %s intervals given as input, whereas max_intervals is set to %s.' % + (len(persistence), max_intervals) + ) + # Sort by life time, then takes only the max_intervals elements + return sorted(persistence, key = key, reverse = True)[:max_intervals] + else: + return persistence + @lru_cache(maxsize=1) def _matplotlib_can_use_tex(): """This function returns True if matplotlib can deal with LaTeX, False otherwise. @@ -75,7 +96,6 @@ def plot_persistence_barcode( persistence_file="", alpha=0.6, max_intervals=1000, - max_barcodes=1000, inf_delta=0.1, legend=False, colormap=None, @@ -142,18 +162,9 @@ def plot_persistence_barcode( persistence = _array_handler(persistence) - if max_barcodes != 1000: - print("Deprecated parameter. It has been replaced by max_intervals") - max_intervals = max_barcodes - - if max_intervals > 0 and max_intervals < len(persistence): - # Sort by life time, then takes only the max_intervals elements - persistence = sorted( - persistence, - key=lambda life_time: life_time[1][1] - life_time[1][0], - reverse=True, - )[:max_intervals] - + persistence = _limit_to_max_intervals(persistence, max_intervals, + key = lambda life_time: life_time[1][1] - life_time[1][0]) + if colormap == None: colormap = plt.cm.Set1.colors if axes == None: @@ -220,7 +231,6 @@ def plot_persistence_diagram( alpha=0.6, band=0.0, max_intervals=1000, - max_plots=1000, inf_delta=0.1, legend=False, colormap=None, @@ -291,17 +301,8 @@ def plot_persistence_diagram( persistence = _array_handler(persistence) - if max_plots != 1000: - print("Deprecated parameter. It has been replaced by max_intervals") - max_intervals = max_plots - - if max_intervals > 0 and max_intervals < len(persistence): - # Sort by life time, then takes only the max_intervals elements - persistence = sorted( - persistence, - key=lambda life_time: life_time[1][1] - life_time[1][0], - reverse=True, - )[:max_intervals] + persistence = _limit_to_max_intervals(persistence, max_intervals, + key = lambda life_time: life_time[1][1] - life_time[1][0]) if colormap == None: colormap = plt.cm.Set1.colors @@ -474,15 +475,9 @@ def plot_persistence_density( ) persistence_dim = persistence_dim[np.isfinite(persistence_dim[:, 1])] - if max_intervals > 0 and max_intervals < len(persistence_dim): - # Sort by life time, then takes only the max_intervals elements - persistence_dim = np.array( - sorted( - persistence_dim, - key=lambda life_time: life_time[1] - life_time[0], - reverse=True, - )[:max_intervals] - ) + + persistence_dim = np.array(_limit_to_max_intervals(persistence_dim, max_intervals, + key = lambda life_time: life_time[1] - life_time[0])) # Set as numpy array birth and death (remove undefined values - inf and NaN) birth = persistence_dim[:, 0] -- cgit v1.2.3 From 8587b70b268aaf7be2ab5b0e163d43f5587b0aac Mon Sep 17 00:00:00 2001 From: ROUVREAU Vincent Date: Tue, 15 Jun 2021 18:03:45 +0200 Subject: Fix MatplotlibDeprecationWarning: shading='flat' when X and Y have the same dimensions as C as it is deprecated since 3.3 --- src/python/gudhi/persistence_graphical_tools.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/python/gudhi/persistence_graphical_tools.py b/src/python/gudhi/persistence_graphical_tools.py index 460e2558..460029fb 100644 --- a/src/python/gudhi/persistence_graphical_tools.py +++ b/src/python/gudhi/persistence_graphical_tools.py @@ -502,7 +502,7 @@ def plot_persistence_density( zi = k(np.vstack([xi.flatten(), yi.flatten()])) # Make the plot - img = axes.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=cmap) + img = axes.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=cmap, shading='auto') if greyblock: axes.add_patch(mpatches.Polygon([[birth.min(), birth.min()], [death.max(), birth.min()], [death.max(), death.max()]], fill=True, color='lightgrey')) -- cgit v1.2.3 From 2eb2f96248f09e5c793760cfb44ce7b1a40c1af4 Mon Sep 17 00:00:00 2001 From: ROUVREAU Vincent Date: Tue, 15 Jun 2021 18:32:33 +0200 Subject: Ignore figure as not used on default subplot --- src/python/gudhi/persistence_graphical_tools.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/python/gudhi/persistence_graphical_tools.py b/src/python/gudhi/persistence_graphical_tools.py index 460029fb..b129b375 100644 --- a/src/python/gudhi/persistence_graphical_tools.py +++ b/src/python/gudhi/persistence_graphical_tools.py @@ -168,7 +168,7 @@ def plot_persistence_barcode( if colormap == None: colormap = plt.cm.Set1.colors if axes == None: - fig, axes = plt.subplots(1, 1) + _, axes = plt.subplots(1, 1) persistence = sorted(persistence, key=lambda birth: birth[1][0]) @@ -307,7 +307,7 @@ def plot_persistence_diagram( if colormap == None: colormap = plt.cm.Set1.colors if axes == None: - fig, axes = plt.subplots(1, 1) + _, axes = plt.subplots(1, 1) (min_birth, max_death) = __min_birth_max_death(persistence, band) delta = (max_death - min_birth) * inf_delta @@ -487,7 +487,7 @@ def plot_persistence_density( if cmap is None: cmap = plt.cm.hot_r if axes == None: - fig, axes = plt.subplots(1, 1) + _, axes = plt.subplots(1, 1) # line display of equation : birth = death x = np.linspace(death.min(), birth.max(), 1000) -- cgit v1.2.3 From 486b281c726cbb6110cfe3c63b3f225690bcd348 Mon Sep 17 00:00:00 2001 From: ROUVREAU Vincent Date: Thu, 17 Jun 2021 11:01:18 +0200 Subject: Use float as it can be ambiguous. Do not work if we remove np.inf value --- src/python/doc/persistence_graphical_tools_user.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/python/doc/persistence_graphical_tools_user.rst b/src/python/doc/persistence_graphical_tools_user.rst index d95b9d2b..e1d28c71 100644 --- a/src/python/doc/persistence_graphical_tools_user.rst +++ b/src/python/doc/persistence_graphical_tools_user.rst @@ -60,7 +60,7 @@ of shape (N x 2) encoding a persistence diagram (in a given dimension). import matplotlib.pyplot as plt import gudhi import numpy as np - d = np.array([[0, 1], [1, 2], [1, np.inf]]) + d = np.array([[0., 1.], [1., 2.], [1., np.inf]]) gudhi.plot_persistence_diagram(d) plt.show() -- cgit v1.2.3 From cb108929433617f553e0a0c7185b3073cce35696 Mon Sep 17 00:00:00 2001 From: ROUVREAU Vincent Date: Thu, 17 Jun 2021 15:43:30 +0200 Subject: Fix #461 and review all error cases (no more prints, warnings and exceptions instead) --- src/python/CMakeLists.txt | 4 + src/python/gudhi/persistence_graphical_tools.py | 245 +++++++++++++----------- 2 files changed, 141 insertions(+), 108 deletions(-) (limited to 'src') diff --git a/src/python/CMakeLists.txt b/src/python/CMakeLists.txt index 98f2b85f..1f0d74d4 100644 --- a/src/python/CMakeLists.txt +++ b/src/python/CMakeLists.txt @@ -542,6 +542,10 @@ if(PYTHONINTERP_FOUND) add_gudhi_py_test(test_dtm_rips_complex) endif() + # persistence graphical tools + if(MATPLOTLIB_FOUND) + add_gudhi_py_test(test_persistence_graphical_tools) + endif() # Set missing or not modules set(GUDHI_MODULES ${GUDHI_MODULES} "python" CACHE INTERNAL "GUDHI_MODULES") diff --git a/src/python/gudhi/persistence_graphical_tools.py b/src/python/gudhi/persistence_graphical_tools.py index b129b375..9bfc19e0 100644 --- a/src/python/gudhi/persistence_graphical_tools.py +++ b/src/python/gudhi/persistence_graphical_tools.py @@ -13,6 +13,8 @@ from math import isfinite import numpy as np from functools import lru_cache import warnings +import errno +import os from gudhi.reader_utils import read_persistence_intervals_in_dimension from gudhi.reader_utils import read_persistence_intervals_grouped_by_dimension @@ -45,6 +47,9 @@ def __min_birth_max_death(persistence, band=0.0): min_birth = float(interval[1][0]) if band > 0.0: max_death += band + # can happen if only points at inf death + if min_birth == max_death: + max_death = max_death + 1. return (min_birth, max_death) @@ -54,7 +59,7 @@ def _array_handler(a): persistence-compatible list (padding with 0), so that the plot can be performed seamlessly. ''' - if isinstance(a[0][1], np.float64) or isinstance(a[0][1], float): + if isinstance(a[0][1], np.floating) or isinstance(a[0][1], float): return [[0, x] for x in a] else: return a @@ -88,7 +93,7 @@ def _matplotlib_can_use_tex(): from matplotlib import checkdep_usetex return checkdep_usetex(True) except ImportError: - print("This function is not available, you may be missing matplotlib.") + warnings.warn("This function is not available, you may be missing matplotlib.") def plot_persistence_barcode( @@ -157,53 +162,58 @@ def plot_persistence_barcode( for persistence_interval in diag[key]: persistence.append((key, persistence_interval)) else: - print("file " + persistence_file + " not found.") - return None + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), persistence_file) - persistence = _array_handler(persistence) - - persistence = _limit_to_max_intervals(persistence, max_intervals, - key = lambda life_time: life_time[1][1] - life_time[1][0]) - - if colormap == None: - colormap = plt.cm.Set1.colors - if axes == None: - _, axes = plt.subplots(1, 1) - - persistence = sorted(persistence, key=lambda birth: birth[1][0]) + try: + persistence = _array_handler(persistence) + persistence = _limit_to_max_intervals(persistence, max_intervals, + key = lambda life_time: life_time[1][1] - life_time[1][0]) + (min_birth, max_death) = __min_birth_max_death(persistence) + persistence = sorted(persistence, key=lambda birth: birth[1][0]) + except IndexError: + min_birth, max_death = 0., 1. + pass - (min_birth, max_death) = __min_birth_max_death(persistence) - ind = 0 delta = (max_death - min_birth) * inf_delta # Replace infinity values with max_death + delta for bar code to be more # readable infinity = max_death + delta axis_start = min_birth - delta + + if axes == None: + _, axes = plt.subplots(1, 1) + if colormap == None: + colormap = plt.cm.Set1.colors + ind = 0 + # Draw horizontal bars in loop for interval in reversed(persistence): - if float(interval[1][1]) != float("inf"): - # Finite death case - axes.barh( - ind, - (interval[1][1] - interval[1][0]), - height=0.8, - left=interval[1][0], - alpha=alpha, - color=colormap[interval[0]], - linewidth=0, - ) - else: - # Infinite death case for diagram to be nicer - axes.barh( - ind, - (infinity - interval[1][0]), - height=0.8, - left=interval[1][0], - alpha=alpha, - color=colormap[interval[0]], - linewidth=0, - ) - ind = ind + 1 + try: + if float(interval[1][1]) != float("inf"): + # Finite death case + axes.barh( + ind, + (interval[1][1] - interval[1][0]), + height=0.8, + left=interval[1][0], + alpha=alpha, + color=colormap[interval[0]], + linewidth=0, + ) + else: + # Infinite death case for diagram to be nicer + axes.barh( + ind, + (infinity - interval[1][0]), + height=0.8, + left=interval[1][0], + alpha=alpha, + color=colormap[interval[0]], + linewidth=0, + ) + ind = ind + 1 + except IndexError: + pass if legend: dimensions = list(set(item[0] for item in persistence)) @@ -218,11 +228,12 @@ def plot_persistence_barcode( axes.set_title("Persistence barcode", fontsize=fontsize) # Ends plot on infinity value and starts a little bit before min_birth - axes.axis([axis_start, infinity, 0, ind]) + if ind != 0: + axes.axis([axis_start, infinity, 0, ind]) return axes except ImportError: - print("This function is not available, you may be missing matplotlib.") + warnings.warn("This function is not available, you may be missing matplotlib.") def plot_persistence_diagram( @@ -296,20 +307,17 @@ def plot_persistence_diagram( for persistence_interval in diag[key]: persistence.append((key, persistence_interval)) else: - print("file " + persistence_file + " not found.") - return None - - persistence = _array_handler(persistence) - - persistence = _limit_to_max_intervals(persistence, max_intervals, - key = lambda life_time: life_time[1][1] - life_time[1][0]) + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), persistence_file) - if colormap == None: - colormap = plt.cm.Set1.colors - if axes == None: - _, axes = plt.subplots(1, 1) + try: + persistence = _array_handler(persistence) + persistence = _limit_to_max_intervals(persistence, max_intervals, + key = lambda life_time: life_time[1][1] - life_time[1][0]) + min_birth, max_death = __min_birth_max_death(persistence, band) + except IndexError: + min_birth, max_death = 0., 1. + pass - (min_birth, max_death) = __min_birth_max_death(persistence, band) delta = (max_death - min_birth) * inf_delta # Replace infinity values with max_death + delta for diagram to be more # readable @@ -317,33 +325,43 @@ def plot_persistence_diagram( axis_end = max_death + delta / 2 axis_start = min_birth - delta + if axes == None: + _, axes = plt.subplots(1, 1) + if colormap == None: + colormap = plt.cm.Set1.colors # bootstrap band if band > 0.0: x = np.linspace(axis_start, infinity, 1000) axes.fill_between(x, x, x + band, alpha=alpha, facecolor="red") # lower diag patch if greyblock: - axes.add_patch(mpatches.Polygon([[axis_start, axis_start], [axis_end, axis_start], [axis_end, axis_end]], fill=True, color='lightgrey')) + axes.add_patch(mpatches.Polygon([[axis_start, axis_start], [axis_end, axis_start], [axis_end, axis_end]], + fill=True, color='lightgrey')) + # line display of equation : birth = death + axes.plot([axis_start, axis_end], [axis_start, axis_end], linewidth=1.0, color="k") + # Draw points in loop pts_at_infty = False # Records presence of pts at infty for interval in reversed(persistence): - if float(interval[1][1]) != float("inf"): - # Finite death case - axes.scatter( - interval[1][0], - interval[1][1], - alpha=alpha, - color=colormap[interval[0]], - ) - else: - pts_at_infty = True - # Infinite death case for diagram to be nicer - axes.scatter( - interval[1][0], infinity, alpha=alpha, color=colormap[interval[0]] - ) + try: + if float(interval[1][1]) != float("inf"): + # Finite death case + axes.scatter( + interval[1][0], + interval[1][1], + alpha=alpha, + color=colormap[interval[0]], + ) + else: + pts_at_infty = True + # Infinite death case for diagram to be nicer + axes.scatter( + interval[1][0], infinity, alpha=alpha, color=colormap[interval[0]] + ) + except IndexError: + pass if pts_at_infty: # infinity line and text - axes.plot([axis_start, axis_end], [axis_start, axis_end], linewidth=1.0, color="k") axes.plot([axis_start, axis_end], [infinity, infinity], linewidth=1.0, color="k", alpha=alpha) # Infinity label yt = axes.get_yticks() @@ -371,7 +389,7 @@ def plot_persistence_diagram( return axes except ImportError: - print("This function is not available, you may be missing matplotlib.") + warnings.warn("This function is not available, you may be missing matplotlib.") def plot_persistence_density( @@ -461,27 +479,7 @@ def plot_persistence_density( persistence_file=persistence_file, only_this_dim=dimension ) else: - print("file " + persistence_file + " not found.") - return None - - if len(persistence) > 0: - persistence = _array_handler(persistence) - persistence_dim = np.array( - [ - (dim_interval[1][0], dim_interval[1][1]) - for dim_interval in persistence - if (dim_interval[0] == dimension) or (dimension is None) - ] - ) - - persistence_dim = persistence_dim[np.isfinite(persistence_dim[:, 1])] - - persistence_dim = np.array(_limit_to_max_intervals(persistence_dim, max_intervals, - key = lambda life_time: life_time[1] - life_time[0])) - - # Set as numpy array birth and death (remove undefined values - inf and NaN) - birth = persistence_dim[:, 0] - death = persistence_dim[:, 1] + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), persistence_file) # default cmap value cannot be done at argument definition level as matplotlib is not yet defined. if cmap is None: @@ -489,23 +487,56 @@ def plot_persistence_density( if axes == None: _, axes = plt.subplots(1, 1) + try: + if len(persistence) > 0: + # if not read from file but given by an argument + persistence = _array_handler(persistence) + persistence_dim = np.array( + [ + (dim_interval[1][0], dim_interval[1][1]) + for dim_interval in persistence + if (dim_interval[0] == dimension) or (dimension is None) + ] + ) + persistence_dim = persistence_dim[np.isfinite(persistence_dim[:, 1])] + persistence_dim = np.array(_limit_to_max_intervals(persistence_dim, max_intervals, + key = lambda life_time: life_time[1] - life_time[0])) + + # Set as numpy array birth and death (remove undefined values - inf and NaN) + birth = persistence_dim[:, 0] + death = persistence_dim[:, 1] + birth_min = birth.min() + birth_max = birth.max() + death_min = death.min() + death_max = death.max() + + # Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents + k = kde.gaussian_kde([birth, death], bw_method=bw_method) + xi, yi = np.mgrid[ + birth_min : birth_max : nbins * 1j, + death_min : death_max : nbins * 1j, + ] + zi = k(np.vstack([xi.flatten(), yi.flatten()])) + # Make the plot + img = axes.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=cmap, shading='auto') + + # IndexError on empty diagrams, ValueError on only inf death values + except (IndexError, ValueError): + birth_min = 0. + birth_max = 1. + death_min = 0. + death_max = 1. + pass + # line display of equation : birth = death - x = np.linspace(death.min(), birth.max(), 1000) + x = np.linspace(death_min, birth_max, 1000) axes.plot(x, x, color="k", linewidth=1.0) - # Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents - k = kde.gaussian_kde([birth, death], bw_method=bw_method) - xi, yi = np.mgrid[ - birth.min() : birth.max() : nbins * 1j, - death.min() : death.max() : nbins * 1j, - ] - zi = k(np.vstack([xi.flatten(), yi.flatten()])) - - # Make the plot - img = axes.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=cmap, shading='auto') - if greyblock: - axes.add_patch(mpatches.Polygon([[birth.min(), birth.min()], [death.max(), birth.min()], [death.max(), death.max()]], fill=True, color='lightgrey')) + axes.add_patch(mpatches.Polygon([[birth_min, birth_min], + [death_max, birth_min], + [death_max, death_max]], + fill=True, color='lightgrey')) if legend: plt.colorbar(img, ax=axes) @@ -517,6 +548,4 @@ def plot_persistence_density( return axes except ImportError: - print( - "This function is not available, you may be missing matplotlib and/or scipy." - ) + warnings.warn("This function is not available, you may be missing matplotlib and/or scipy.") -- cgit v1.2.3 From 72f72770ccf0d1ddb78a7f23103b2777f407e72c Mon Sep 17 00:00:00 2001 From: ROUVREAU Vincent Date: Thu, 17 Jun 2021 16:29:18 +0200 Subject: Forgot to add test file for graphical --- .../test/test_persistence_graphical_tools.py | 105 +++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 src/python/test/test_persistence_graphical_tools.py (limited to 'src') diff --git a/src/python/test/test_persistence_graphical_tools.py b/src/python/test/test_persistence_graphical_tools.py new file mode 100644 index 00000000..1ad1ae23 --- /dev/null +++ b/src/python/test/test_persistence_graphical_tools.py @@ -0,0 +1,105 @@ +""" 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) 2021 Inria + + Modification(s): + - YYYY/MM Author: Description of the modification +""" + +import gudhi as gd +import numpy as np +import matplotlib as plt +import pytest + +def test_array_handler(): + diags = np.array([[1, 2], [3, 4], [5, 6]], np.float) + arr_diags = gd.persistence_graphical_tools._array_handler(diags) + for idx in range(len(diags)): + assert arr_diags[idx][0] == 0 + np.testing.assert_array_equal(arr_diags[idx][1], diags[idx]) + + diags = [(1., 2.), (3., 4.), (5., 6.)] + arr_diags = gd.persistence_graphical_tools._array_handler(diags) + for idx in range(len(diags)): + assert arr_diags[idx][0] == 0 + assert arr_diags[idx][1] == diags[idx] + + diags = [(0, (1., 2.)), (0, (3., 4.)), (0, (5., 6.))] + assert gd.persistence_graphical_tools._array_handler(diags) == diags + +def test_min_birth_max_death(): + diags = [ + (0, (0., float("inf"))), + (0, (0.0983494, float("inf"))), + (0, (0., 0.122545)), + (0, (0., 0.12047)), + (0, (0., 0.118398)), + (0, (0.118398, 1.)), + (0, (0., 0.117908)), + (0, (0., 0.112307)), + (0, (0., 0.107535)), + (0, (0., 0.106382)), + ] + assert gd.persistence_graphical_tools.__min_birth_max_death(diags) == (0., 1.) + assert gd.persistence_graphical_tools.__min_birth_max_death(diags, band=4.) == (0., 5.) + +def test_limit_min_birth_max_death(): + diags = [ + (0, (2., float("inf"))), + (0, (2., float("inf"))), + ] + assert gd.persistence_graphical_tools.__min_birth_max_death(diags) == (2., 3.) + assert gd.persistence_graphical_tools.__min_birth_max_death(diags, band = 4.) == (2., 6.) + +def test_limit_to_max_intervals(): + diags = [ + (0, (0., float("inf"))), + (0, (0.0983494, float("inf"))), + (0, (0., 0.122545)), + (0, (0., 0.12047)), + (0, (0., 0.118398)), + (0, (0.118398, 1.)), + (0, (0., 0.117908)), + (0, (0., 0.112307)), + (0, (0., 0.107535)), + (0, (0., 0.106382)), + ] + # check no warnings if max_intervals equals to the diagrams number + with pytest.warns(None) as record: + truncated_diags = gd.persistence_graphical_tools._limit_to_max_intervals(diags, 10, + key = lambda life_time: life_time[1][1] - life_time[1][0]) + # check diagrams are not sorted + assert truncated_diags == diags + assert len(record) == 0 + + # check warning if max_intervals lower than the diagrams number + with pytest.warns(UserWarning) as record: + truncated_diags = gd.persistence_graphical_tools._limit_to_max_intervals(diags, 5, + key = lambda life_time: life_time[1][1] - life_time[1][0]) + # check diagrams are truncated and sorted by life time + assert truncated_diags == [(0, (0., float("inf"))), + (0, (0.0983494, float("inf"))), + (0, (0.118398, 1.0)), + (0, (0., 0.122545)), + (0, (0., 0.12047))] + assert len(record) == 1 + +def _limit_plot_persistence(function): + pplot = function(persistence=[()]) + assert issubclass(type(pplot), plt.axes.SubplotBase) + pplot = function(persistence=[(0, float("inf"))]) + assert issubclass(type(pplot), plt.axes.SubplotBase) + +def test_limit_plot_persistence(): + for function in [gd.plot_persistence_barcode, gd.plot_persistence_diagram, gd.plot_persistence_density]: + _limit_plot_persistence(function) + +def _non_existing_persistence_file(function): + with pytest.raises(FileNotFoundError): + function(persistence_file="pouetpouettralala.toubiloubabdou") + +def test_non_existing_persistence_file(): + for function in [gd.plot_persistence_barcode, gd.plot_persistence_diagram, gd.plot_persistence_density]: + _non_existing_persistence_file(function) -- cgit v1.2.3 From f9b1e50a6adaadf88c4940cb4214f9ecef542144 Mon Sep 17 00:00:00 2001 From: ROUVREAU Vincent Date: Tue, 22 Jun 2021 18:47:46 +0200 Subject: black -l 120 modified files --- src/python/gudhi/persistence_graphical_tools.py | 144 +++++++++++---------- .../test/test_persistence_graphical_tools.py | 82 +++++++----- 2 files changed, 120 insertions(+), 106 deletions(-) (limited to 'src') diff --git a/src/python/gudhi/persistence_graphical_tools.py b/src/python/gudhi/persistence_graphical_tools.py index 9bfc19e0..837218ca 100644 --- a/src/python/gudhi/persistence_graphical_tools.py +++ b/src/python/gudhi/persistence_graphical_tools.py @@ -25,6 +25,7 @@ __license__ = "MIT" _gudhi_matplotlib_use_tex = True + def __min_birth_max_death(persistence, band=0.0): """This function returns (min_birth, max_death) from the persistence. @@ -49,23 +50,24 @@ def __min_birth_max_death(persistence, band=0.0): max_death += band # can happen if only points at inf death if min_birth == max_death: - max_death = max_death + 1. + max_death = max_death + 1.0 return (min_birth, max_death) def _array_handler(a): - ''' + """ :param a: if array, assumes it is a (n x 2) np.array and return a persistence-compatible list (padding with 0), so that the plot can be performed seamlessly. - ''' + """ if isinstance(a[0][1], np.floating) or isinstance(a[0][1], float): return [[0, x] for x in a] else: return a + def _limit_to_max_intervals(persistence, max_intervals, key): - '''This function returns truncated persistence if length is bigger than max_intervals. + """This function returns truncated persistence if length is bigger than max_intervals. :param persistence: Persistence intervals values list. Can be grouped by dimension or not. :type persistence: an array of (dimension, array of (birth, death)) or an array of (birth, death). :param max_intervals: maximal number of intervals to display. @@ -74,16 +76,18 @@ def _limit_to_max_intervals(persistence, max_intervals, key): :type max_intervals: int. :param key: key function for sort algorithm. :type key: function or lambda. - ''' + """ if max_intervals > 0 and max_intervals < len(persistence): - warnings.warn('There are %s intervals given as input, whereas max_intervals is set to %s.' % - (len(persistence), max_intervals) - ) + warnings.warn( + "There are %s intervals given as input, whereas max_intervals is set to %s." + % (len(persistence), max_intervals) + ) # Sort by life time, then takes only the max_intervals elements - return sorted(persistence, key = key, reverse = True)[:max_intervals] + return sorted(persistence, key=key, reverse=True)[:max_intervals] else: return persistence + @lru_cache(maxsize=1) def _matplotlib_can_use_tex(): """This function returns True if matplotlib can deal with LaTeX, False otherwise. @@ -91,6 +95,7 @@ def _matplotlib_can_use_tex(): """ try: from matplotlib import checkdep_usetex + return checkdep_usetex(True) except ImportError: warnings.warn("This function is not available, you may be missing matplotlib.") @@ -144,20 +149,19 @@ def plot_persistence_barcode( import matplotlib.pyplot as plt import matplotlib.patches as mpatches from matplotlib import rc + if _gudhi_matplotlib_use_tex and _matplotlib_can_use_tex(): - plt.rc('text', usetex=True) - plt.rc('font', family='serif') + plt.rc("text", usetex=True) + plt.rc("font", family="serif") else: - plt.rc('text', usetex=False) - plt.rc('font', family='DejaVu Sans') + plt.rc("text", usetex=False) + plt.rc("font", family="DejaVu Sans") if persistence_file != "": if path.isfile(persistence_file): # Reset persistence persistence = [] - diag = read_persistence_intervals_grouped_by_dimension( - persistence_file=persistence_file - ) + diag = read_persistence_intervals_grouped_by_dimension(persistence_file=persistence_file) for key in diag.keys(): for persistence_interval in diag[key]: persistence.append((key, persistence_interval)) @@ -166,12 +170,13 @@ def plot_persistence_barcode( try: persistence = _array_handler(persistence) - persistence = _limit_to_max_intervals(persistence, max_intervals, - key = lambda life_time: life_time[1][1] - life_time[1][0]) + persistence = _limit_to_max_intervals( + persistence, max_intervals, key=lambda life_time: life_time[1][1] - life_time[1][0] + ) (min_birth, max_death) = __min_birth_max_death(persistence) persistence = sorted(persistence, key=lambda birth: birth[1][0]) except IndexError: - min_birth, max_death = 0., 1. + min_birth, max_death = 0.0, 1.0 pass delta = (max_death - min_birth) * inf_delta @@ -218,11 +223,7 @@ def plot_persistence_barcode( if legend: dimensions = list(set(item[0] for item in persistence)) axes.legend( - handles=[ - mpatches.Patch(color=colormap[dim], label=str(dim)) - for dim in dimensions - ], - loc="lower right", + handles=[mpatches.Patch(color=colormap[dim], label=str(dim)) for dim in dimensions], loc="lower right", ) axes.set_title("Persistence barcode", fontsize=fontsize) @@ -247,7 +248,7 @@ def plot_persistence_diagram( colormap=None, axes=None, fontsize=16, - greyblock=True + greyblock=True, ): """This function plots the persistence diagram from persistence values list, a np.array of shape (N x 2) representing a diagram in a single @@ -289,20 +290,19 @@ def plot_persistence_diagram( import matplotlib.pyplot as plt import matplotlib.patches as mpatches from matplotlib import rc + if _gudhi_matplotlib_use_tex and _matplotlib_can_use_tex(): - plt.rc('text', usetex=True) - plt.rc('font', family='serif') + plt.rc("text", usetex=True) + plt.rc("font", family="serif") else: - plt.rc('text', usetex=False) - plt.rc('font', family='DejaVu Sans') + plt.rc("text", usetex=False) + plt.rc("font", family="DejaVu Sans") if persistence_file != "": if path.isfile(persistence_file): # Reset persistence persistence = [] - diag = read_persistence_intervals_grouped_by_dimension( - persistence_file=persistence_file - ) + diag = read_persistence_intervals_grouped_by_dimension(persistence_file=persistence_file) for key in diag.keys(): for persistence_interval in diag[key]: persistence.append((key, persistence_interval)) @@ -311,11 +311,12 @@ def plot_persistence_diagram( try: persistence = _array_handler(persistence) - persistence = _limit_to_max_intervals(persistence, max_intervals, - key = lambda life_time: life_time[1][1] - life_time[1][0]) + persistence = _limit_to_max_intervals( + persistence, max_intervals, key=lambda life_time: life_time[1][1] - life_time[1][0] + ) min_birth, max_death = __min_birth_max_death(persistence, band) except IndexError: - min_birth, max_death = 0., 1. + min_birth, max_death = 0.0, 1.0 pass delta = (max_death - min_birth) * inf_delta @@ -335,8 +336,13 @@ def plot_persistence_diagram( axes.fill_between(x, x, x + band, alpha=alpha, facecolor="red") # lower diag patch if greyblock: - axes.add_patch(mpatches.Polygon([[axis_start, axis_start], [axis_end, axis_start], [axis_end, axis_end]], - fill=True, color='lightgrey')) + axes.add_patch( + mpatches.Polygon( + [[axis_start, axis_start], [axis_end, axis_start], [axis_end, axis_end]], + fill=True, + color="lightgrey", + ) + ) # line display of equation : birth = death axes.plot([axis_start, axis_end], [axis_start, axis_end], linewidth=1.0, color="k") @@ -347,17 +353,12 @@ def plot_persistence_diagram( if float(interval[1][1]) != float("inf"): # Finite death case axes.scatter( - interval[1][0], - interval[1][1], - alpha=alpha, - color=colormap[interval[0]], + interval[1][0], interval[1][1], alpha=alpha, color=colormap[interval[0]], ) else: pts_at_infty = True # Infinite death case for diagram to be nicer - axes.scatter( - interval[1][0], infinity, alpha=alpha, color=colormap[interval[0]] - ) + axes.scatter(interval[1][0], infinity, alpha=alpha, color=colormap[interval[0]]) except IndexError: pass if pts_at_infty: @@ -365,27 +366,22 @@ def plot_persistence_diagram( axes.plot([axis_start, axis_end], [infinity, infinity], linewidth=1.0, color="k", alpha=alpha) # Infinity label yt = axes.get_yticks() - yt = yt[np.where(yt < axis_end)] # to avoid ploting ticklabel higher than infinity + yt = yt[np.where(yt < axis_end)] # to avoid ploting ticklabel higher than infinity yt = np.append(yt, infinity) ytl = ["%.3f" % e for e in yt] # to avoid float precision error - ytl[-1] = r'$+\infty$' + ytl[-1] = r"$+\infty$" axes.set_yticks(yt) axes.set_yticklabels(ytl) if legend: dimensions = list(set(item[0] for item in persistence)) - axes.legend( - handles=[ - mpatches.Patch(color=colormap[dim], label=str(dim)) - for dim in dimensions - ] - ) + axes.legend(handles=[mpatches.Patch(color=colormap[dim], label=str(dim)) for dim in dimensions]) axes.set_xlabel("Birth", fontsize=fontsize) axes.set_ylabel("Death", fontsize=fontsize) axes.set_title("Persistence diagram", fontsize=fontsize) # Ends plot on infinity value and starts a little bit before min_birth - axes.axis([axis_start, axis_end, axis_start, infinity + delta/2]) + axes.axis([axis_start, axis_end, axis_start, infinity + delta / 2]) return axes except ImportError: @@ -403,7 +399,7 @@ def plot_persistence_density( legend=False, axes=None, fontsize=16, - greyblock=False + greyblock=False, ): """This function plots the persistence density from persistence values list, np.array of shape (N x 2) representing a diagram @@ -463,12 +459,13 @@ def plot_persistence_density( import matplotlib.patches as mpatches from scipy.stats import kde from matplotlib import rc + if _gudhi_matplotlib_use_tex and _matplotlib_can_use_tex(): - plt.rc('text', usetex=True) - plt.rc('font', family='serif') + plt.rc("text", usetex=True) + plt.rc("font", family="serif") else: - plt.rc('text', usetex=False) - plt.rc('font', family='DejaVu Sans') + plt.rc("text", usetex=False) + plt.rc("font", family="DejaVu Sans") if persistence_file != "": if dimension is None: @@ -499,8 +496,11 @@ def plot_persistence_density( ] ) persistence_dim = persistence_dim[np.isfinite(persistence_dim[:, 1])] - persistence_dim = np.array(_limit_to_max_intervals(persistence_dim, max_intervals, - key = lambda life_time: life_time[1] - life_time[0])) + persistence_dim = np.array( + _limit_to_max_intervals( + persistence_dim, max_intervals, key=lambda life_time: life_time[1] - life_time[0] + ) + ) # Set as numpy array birth and death (remove undefined values - inf and NaN) birth = persistence_dim[:, 0] @@ -513,19 +513,18 @@ def plot_persistence_density( # Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents k = kde.gaussian_kde([birth, death], bw_method=bw_method) xi, yi = np.mgrid[ - birth_min : birth_max : nbins * 1j, - death_min : death_max : nbins * 1j, + birth_min : birth_max : nbins * 1j, death_min : death_max : nbins * 1j, ] zi = k(np.vstack([xi.flatten(), yi.flatten()])) # Make the plot - img = axes.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=cmap, shading='auto') + img = axes.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=cmap, shading="auto") # IndexError on empty diagrams, ValueError on only inf death values except (IndexError, ValueError): - birth_min = 0. - birth_max = 1. - death_min = 0. - death_max = 1. + birth_min = 0.0 + birth_max = 1.0 + death_min = 0.0 + death_max = 1.0 pass # line display of equation : birth = death @@ -533,10 +532,13 @@ def plot_persistence_density( axes.plot(x, x, color="k", linewidth=1.0) if greyblock: - axes.add_patch(mpatches.Polygon([[birth_min, birth_min], - [death_max, birth_min], - [death_max, death_max]], - fill=True, color='lightgrey')) + axes.add_patch( + mpatches.Polygon( + [[birth_min, birth_min], [death_max, birth_min], [death_max, death_max]], + fill=True, + color="lightgrey", + ) + ) if legend: plt.colorbar(img, ax=axes) diff --git a/src/python/test/test_persistence_graphical_tools.py b/src/python/test/test_persistence_graphical_tools.py index 1ad1ae23..7d9bae90 100644 --- a/src/python/test/test_persistence_graphical_tools.py +++ b/src/python/test/test_persistence_graphical_tools.py @@ -13,6 +13,7 @@ import numpy as np import matplotlib as plt import pytest + def test_array_handler(): diags = np.array([[1, 2], [3, 4], [5, 6]], np.float) arr_diags = gd.persistence_graphical_tools._array_handler(diags) @@ -20,86 +21,97 @@ def test_array_handler(): assert arr_diags[idx][0] == 0 np.testing.assert_array_equal(arr_diags[idx][1], diags[idx]) - diags = [(1., 2.), (3., 4.), (5., 6.)] + diags = [(1.0, 2.0), (3.0, 4.0), (5.0, 6.0)] arr_diags = gd.persistence_graphical_tools._array_handler(diags) for idx in range(len(diags)): assert arr_diags[idx][0] == 0 assert arr_diags[idx][1] == diags[idx] - diags = [(0, (1., 2.)), (0, (3., 4.)), (0, (5., 6.))] + diags = [(0, (1.0, 2.0)), (0, (3.0, 4.0)), (0, (5.0, 6.0))] assert gd.persistence_graphical_tools._array_handler(diags) == diags + def test_min_birth_max_death(): diags = [ - (0, (0., float("inf"))), + (0, (0.0, float("inf"))), (0, (0.0983494, float("inf"))), - (0, (0., 0.122545)), - (0, (0., 0.12047)), - (0, (0., 0.118398)), - (0, (0.118398, 1.)), - (0, (0., 0.117908)), - (0, (0., 0.112307)), - (0, (0., 0.107535)), - (0, (0., 0.106382)), + (0, (0.0, 0.122545)), + (0, (0.0, 0.12047)), + (0, (0.0, 0.118398)), + (0, (0.118398, 1.0)), + (0, (0.0, 0.117908)), + (0, (0.0, 0.112307)), + (0, (0.0, 0.107535)), + (0, (0.0, 0.106382)), ] - assert gd.persistence_graphical_tools.__min_birth_max_death(diags) == (0., 1.) - assert gd.persistence_graphical_tools.__min_birth_max_death(diags, band=4.) == (0., 5.) + assert gd.persistence_graphical_tools.__min_birth_max_death(diags) == (0.0, 1.0) + assert gd.persistence_graphical_tools.__min_birth_max_death(diags, band=4.0) == (0.0, 5.0) + def test_limit_min_birth_max_death(): diags = [ - (0, (2., float("inf"))), - (0, (2., float("inf"))), + (0, (2.0, float("inf"))), + (0, (2.0, float("inf"))), ] - assert gd.persistence_graphical_tools.__min_birth_max_death(diags) == (2., 3.) - assert gd.persistence_graphical_tools.__min_birth_max_death(diags, band = 4.) == (2., 6.) + assert gd.persistence_graphical_tools.__min_birth_max_death(diags) == (2.0, 3.0) + assert gd.persistence_graphical_tools.__min_birth_max_death(diags, band=4.0) == (2.0, 6.0) + def test_limit_to_max_intervals(): diags = [ - (0, (0., float("inf"))), + (0, (0.0, float("inf"))), (0, (0.0983494, float("inf"))), - (0, (0., 0.122545)), - (0, (0., 0.12047)), - (0, (0., 0.118398)), - (0, (0.118398, 1.)), - (0, (0., 0.117908)), - (0, (0., 0.112307)), - (0, (0., 0.107535)), - (0, (0., 0.106382)), + (0, (0.0, 0.122545)), + (0, (0.0, 0.12047)), + (0, (0.0, 0.118398)), + (0, (0.118398, 1.0)), + (0, (0.0, 0.117908)), + (0, (0.0, 0.112307)), + (0, (0.0, 0.107535)), + (0, (0.0, 0.106382)), ] # check no warnings if max_intervals equals to the diagrams number with pytest.warns(None) as record: - truncated_diags = gd.persistence_graphical_tools._limit_to_max_intervals(diags, 10, - key = lambda life_time: life_time[1][1] - life_time[1][0]) + truncated_diags = gd.persistence_graphical_tools._limit_to_max_intervals( + diags, 10, key=lambda life_time: life_time[1][1] - life_time[1][0] + ) # check diagrams are not sorted assert truncated_diags == diags assert len(record) == 0 # check warning if max_intervals lower than the diagrams number with pytest.warns(UserWarning) as record: - truncated_diags = gd.persistence_graphical_tools._limit_to_max_intervals(diags, 5, - key = lambda life_time: life_time[1][1] - life_time[1][0]) + truncated_diags = gd.persistence_graphical_tools._limit_to_max_intervals( + diags, 5, key=lambda life_time: life_time[1][1] - life_time[1][0] + ) # check diagrams are truncated and sorted by life time - assert truncated_diags == [(0, (0., float("inf"))), - (0, (0.0983494, float("inf"))), - (0, (0.118398, 1.0)), - (0, (0., 0.122545)), - (0, (0., 0.12047))] + assert truncated_diags == [ + (0, (0.0, float("inf"))), + (0, (0.0983494, float("inf"))), + (0, (0.118398, 1.0)), + (0, (0.0, 0.122545)), + (0, (0.0, 0.12047)), + ] assert len(record) == 1 + def _limit_plot_persistence(function): pplot = function(persistence=[()]) assert issubclass(type(pplot), plt.axes.SubplotBase) pplot = function(persistence=[(0, float("inf"))]) assert issubclass(type(pplot), plt.axes.SubplotBase) + def test_limit_plot_persistence(): for function in [gd.plot_persistence_barcode, gd.plot_persistence_diagram, gd.plot_persistence_density]: _limit_plot_persistence(function) + def _non_existing_persistence_file(function): with pytest.raises(FileNotFoundError): function(persistence_file="pouetpouettralala.toubiloubabdou") + def test_non_existing_persistence_file(): for function in [gd.plot_persistence_barcode, gd.plot_persistence_diagram, gd.plot_persistence_density]: _non_existing_persistence_file(function) -- cgit v1.2.3 From 87da488d24c70cbd470ad1c2dae762af68cd227e Mon Sep 17 00:00:00 2001 From: ROUVREAU Vincent Date: Tue, 24 Aug 2021 14:50:12 +0200 Subject: code review: isinstance can take several instances types as a list --- src/python/gudhi/persistence_graphical_tools.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/python/gudhi/persistence_graphical_tools.py b/src/python/gudhi/persistence_graphical_tools.py index 837218ca..70d550ab 100644 --- a/src/python/gudhi/persistence_graphical_tools.py +++ b/src/python/gudhi/persistence_graphical_tools.py @@ -60,7 +60,7 @@ def _array_handler(a): persistence-compatible list (padding with 0), so that the plot can be performed seamlessly. """ - if isinstance(a[0][1], np.floating) or isinstance(a[0][1], float): + if isinstance(a[0][1], (np.floating, float)): return [[0, x] for x in a] else: return a -- cgit v1.2.3 From 55b15a7c8617b770b51f61861951005a3e989327 Mon Sep 17 00:00:00 2001 From: Vincent Rouvreau Date: Wed, 6 Apr 2022 10:54:23 +0200 Subject: code review: Rewrite warnings in case of import errors --- src/python/gudhi/persistence_graphical_tools.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/python/gudhi/persistence_graphical_tools.py b/src/python/gudhi/persistence_graphical_tools.py index 70d550ab..3c166a56 100644 --- a/src/python/gudhi/persistence_graphical_tools.py +++ b/src/python/gudhi/persistence_graphical_tools.py @@ -97,8 +97,8 @@ def _matplotlib_can_use_tex(): from matplotlib import checkdep_usetex return checkdep_usetex(True) - except ImportError: - warnings.warn("This function is not available, you may be missing matplotlib.") + except ImportError as import_error: + warnings.warn(f"This function is not available.\nModuleNotFoundError: No module named '{import_error.name}'.") def plot_persistence_barcode( @@ -233,8 +233,8 @@ def plot_persistence_barcode( axes.axis([axis_start, infinity, 0, ind]) return axes - except ImportError: - warnings.warn("This function is not available, you may be missing matplotlib.") + except ImportError as import_error: + warnings.warn(f"This function is not available.\nModuleNotFoundError: No module named '{import_error.name}'.") def plot_persistence_diagram( @@ -384,8 +384,8 @@ def plot_persistence_diagram( axes.axis([axis_start, axis_end, axis_start, infinity + delta / 2]) return axes - except ImportError: - warnings.warn("This function is not available, you may be missing matplotlib.") + except ImportError as import_error: + warnings.warn(f"This function is not available.\nModuleNotFoundError: No module named '{import_error.name}'.") def plot_persistence_density( @@ -549,5 +549,5 @@ def plot_persistence_density( return axes - except ImportError: - warnings.warn("This function is not available, you may be missing matplotlib and/or scipy.") + except ImportError as import_error: + warnings.warn(f"This function is not available.\nModuleNotFoundError: No module named '{import_error.name}'.") -- cgit v1.2.3 From 79278cfc0aecbfdbf8a66e79ccef44534abb2399 Mon Sep 17 00:00:00 2001 From: Vincent Rouvreau Date: Fri, 29 Apr 2022 17:48:19 +0200 Subject: plot_persistence_diagram and plot_persistence_barcode improvements --- src/python/gudhi/persistence_graphical_tools.py | 68 ++++++------------------- 1 file changed, 16 insertions(+), 52 deletions(-) (limited to 'src') diff --git a/src/python/gudhi/persistence_graphical_tools.py b/src/python/gudhi/persistence_graphical_tools.py index 3c166a56..604018d1 100644 --- a/src/python/gudhi/persistence_graphical_tools.py +++ b/src/python/gudhi/persistence_graphical_tools.py @@ -105,7 +105,7 @@ def plot_persistence_barcode( persistence=[], persistence_file="", alpha=0.6, - max_intervals=1000, + max_intervals=20000, inf_delta=0.1, legend=False, colormap=None, @@ -127,7 +127,7 @@ def plot_persistence_barcode( :type alpha: float. :param max_intervals: maximal number of intervals to display. Selected intervals are those with the longest life time. Set it - to 0 to see all. Default value is 1000. + to 0 to see all. Default value is 20000. :type max_intervals: int. :param inf_delta: Infinity is placed at :code:`((max_death - min_birth) x inf_delta)` above :code:`max_death` value. A reasonable value is @@ -189,36 +189,11 @@ def plot_persistence_barcode( _, axes = plt.subplots(1, 1) if colormap == None: colormap = plt.cm.Set1.colors - ind = 0 - - # Draw horizontal bars in loop - for interval in reversed(persistence): - try: - if float(interval[1][1]) != float("inf"): - # Finite death case - axes.barh( - ind, - (interval[1][1] - interval[1][0]), - height=0.8, - left=interval[1][0], - alpha=alpha, - color=colormap[interval[0]], - linewidth=0, - ) - else: - # Infinite death case for diagram to be nicer - axes.barh( - ind, - (infinity - interval[1][0]), - height=0.8, - left=interval[1][0], - alpha=alpha, - color=colormap[interval[0]], - linewidth=0, - ) - ind = ind + 1 - except IndexError: - pass + + x=[birth for (dim,(birth,death)) in persistence] + y=[(death - birth) if death != float("inf") else (infinity - birth) for (dim,(birth,death)) in persistence] + c=[colormap[dim] for (dim,(birth,death)) in persistence] + axes.barh(list(reversed(range(len(x)))), y, height=0.8, left=x, alpha=alpha, color=c, linewidth=0) if legend: dimensions = list(set(item[0] for item in persistence)) @@ -229,8 +204,8 @@ def plot_persistence_barcode( axes.set_title("Persistence barcode", fontsize=fontsize) # Ends plot on infinity value and starts a little bit before min_birth - if ind != 0: - axes.axis([axis_start, infinity, 0, ind]) + if len(x) != 0: + axes.axis([axis_start, infinity, 0, len(x)]) return axes except ImportError as import_error: @@ -242,7 +217,7 @@ def plot_persistence_diagram( persistence_file="", alpha=0.6, band=0.0, - max_intervals=1000, + max_intervals=1000000, inf_delta=0.1, legend=False, colormap=None, @@ -266,7 +241,7 @@ def plot_persistence_diagram( :type band: float. :param max_intervals: maximal number of intervals to display. Selected intervals are those with the longest life time. Set it - to 0 to see all. Default value is 1000. + to 0 to see all. Default value is 1000000. :type max_intervals: int. :param inf_delta: Infinity is placed at :code:`((max_death - min_birth) x inf_delta)` above :code:`max_death` value. A reasonable value is @@ -346,22 +321,11 @@ def plot_persistence_diagram( # line display of equation : birth = death axes.plot([axis_start, axis_end], [axis_start, axis_end], linewidth=1.0, color="k") - # Draw points in loop - pts_at_infty = False # Records presence of pts at infty - for interval in reversed(persistence): - try: - if float(interval[1][1]) != float("inf"): - # Finite death case - axes.scatter( - interval[1][0], interval[1][1], alpha=alpha, color=colormap[interval[0]], - ) - else: - pts_at_infty = True - # Infinite death case for diagram to be nicer - axes.scatter(interval[1][0], infinity, alpha=alpha, color=colormap[interval[0]]) - except IndexError: - pass - if pts_at_infty: + x=[birth for (dim,(birth,death)) in persistence] + y=[death if death != float("inf") else infinity for (dim,(birth,death)) in persistence] + c=[colormap[dim] for (dim,(birth,death)) in persistence] + axes.scatter(x,y,alpha=alpha,color=c) + if float("inf") in (death for (dim,(birth,death)) in persistence): # infinity line and text axes.plot([axis_start, axis_end], [infinity, infinity], linewidth=1.0, color="k", alpha=alpha) # Infinity label -- cgit v1.2.3