homcloud.interface module

HomCloud python interface

This module provides the interface to HomCloud from python program.

The API document is written by sphinx with Napolen. http://www.sphinx-doc.org/ja/stable/ext/napoleon.html

class homcloud.interface.BitmapPHTrees(treespair, dic)[source]

Bases: object

This class represents PH trees computed from a bitmap filtration.

You can create an instance of this class by BitmapPHTreesPair.dim_0_trees() or BitmapPHTreesPair.codim_1_trees().

nodes

All nodes

Type:list of BitmapPHTrees.Node
essential_nodes

All essential nodes

Type:list of BitmapPHTrees.Node
nonessential_nodes

All nonessential nodes

Type:list of BitmapPHTrees.Node
class Node(mt, dic)[source]

Bases: object

This class represents a tree node of PH trees for a bitmap filtration.

You can draw the optimal volume corresponding to the node on an image by draw_volumes_on_2d_image().

birth_position()[source]

Returns the birth pixel.

Returns:The coordinate of the birth pixel.
Return type:list of int
birth_time()[source]
Returns:The birth time.
Return type:float
children()[source]
Returns:All children nodes.
Return type:list of BitmapPHTrees.Node
death_position()[source]

Returns the death pixel.

Returns:The coordinate of the death pixel.
Return type:list of int
death_time()[source]
Returns:The death time. May be infinity.
Return type:float
essential()[source]
Returns:True if the death time is infinity.
Return type:bool
lifetime()[source]
Returns:The lifetime of the pair.
Return type:float
parent()[source]
Returns:The parent node of the node in the PH tree.
Return type:BitmapPHTrees.Node
to_paraview_node(gui_name=None)[source]

Construct a homcloud.paraview_interface.PipelineNode object to visulize volume().

You can show the volume by homcloud.paraview_interface.show(). You can also adjust the visual by the methods of homcloud.paraview_interface.PipelineNode.

Parameters:gui_name (string or None) – The name shown in Pipeline Browser in paraview’s GUI.
Returns:A PipelineNode object.
Return type:homcloud.paraview_interface.PipelineNode
to_pvnode(gui_name=None)

Construct a homcloud.paraview_interface.PipelineNode object to visulize volume().

You can show the volume by homcloud.paraview_interface.show(). You can also adjust the visual by the methods of homcloud.paraview_interface.PipelineNode.

Parameters:gui_name (string or None) – The name shown in Pipeline Browser in paraview’s GUI.
Returns:A PipelineNode object.
Return type:homcloud.paraview_interface.PipelineNode
volume()[source]

Returns the optimal volume.

In fact, for degree 0 node, this method returns optimal 0-cohomological volume (this means maximal connected conponents in the filtration) and for degree (n-1), this method returns optimal (n-1)-homological volume. This fact is quite mathematical problem, so if you feel that it is too difficult to understand, you can ignore the fact. You can understand the volume information without the understanding of such mathematical background.

Returns:The coordinates of all pixels in the optimal volume.
Return type:list of list of int
degree()[source]
Returns:The degree of the persistent homology.
Return type:int
nearest_pair_node(x, y)[source]

Searches a tree node corresponding the birth-death pair nearest to (x, y).

Parameters:
  • x (float) – The x-coordinate.
  • y (float) – The y-coordinate.
Returns:

The node.

Return type:

BitmapPHTrees.Node

pair_nodes_in_rectangle(xmin, xmax, ymin, ymax)[source]

Searches tree nodes corresponding the birth-death pairs which the given rectangle contains.

Parameters:
  • xmin (float) – The left side of the rectangle.
  • xmax (float) – The right side of the rectangle.
  • ymin (float) – The bottom side of the rectangle.
  • ymax (float) – The top side of the rectangle.
Returns:

The nodes.

Return type:

list of BitmapPHTrees.Node

class homcloud.interface.BitmapPHTreesPair(path)[source]

Bases: object

This class represents PH trees (or a merge trees) computed from a bitmap data.

You can compute the PH trees for 0-th and (n-1)-st persistence homology from n-dimensional bitmap data.

This class is named “Pair” because the instance stores PH trees for both 0-th and (n-1)-st persistent homology.

You can compute PH trees by from_bitmap_levelset() and from_bitmap_distance_function(). The computed data can be loaded from a file by the constructor

Parameters:path (string) – The filepath of the data file which PH trees are stored in.
PDList()[source]
Returns:PDList: The persistence diagrams corresponding to the PH trees.
Return type:class
codim_1_trees()[source]
Returns:BitmapPHTrees: The PH tress for (n-1)-st persistent homology.
Return type:class
dim_0_trees()[source]
Returns:BitmapPHTrees: The PH tress for 0-th persistent homology.
Return type:class
static from_bitmap_distance_function(array, signed=False, metric='manhattan', mask=None, save_to=None)[source]

Computes a PH trees fro 0-th and (n-1)-st persistent homology from the erosion-dilation filtration (the filtration by (signed) distance function) of the bitmap.

This method is obsolete. Please use the combination of BitmapPHTreesPair.from_bitmap_levelset() and distance_transform() instead.

Parameters:
  • array (numpy.ndarray) – The binary bitmap data. The dtype should be bool.
  • signed (bool) – The signed distance function is used if True. The normal distance function is used if False.
  • metric (string) –

    The metric used to compute a filtration. You can choose one of the followings:

    • ”manhattan”
    • ”chebyshev”
    • ”euclidean”
  • mask (numpy.ndarray or None) – The mask bitmap.
  • save_to (string or None) – The filepath which the PH trees is stored in.
Returns:

The PH trees pair of 0-th and (n-1)-st

persistent homology.

Return type:

BitmapPHTreesPair

static from_bitmap_levelset(array, mode='sublevel', save_to=None)[source]

Computes a PH trees fro 0-th and (n-1)-st persistent homology from levelset filtration of the bitmap.

Parameters:
  • array (numpy.ndarray) – The bitmap data.
  • mode (string) – “superlevel” or “sublevel”.
  • save_to (string or None) – The filepath which the PH trees is stored in.
Returns:

The PH trees pair of 0-th and (n-1)-st

persistent homology.

Return type:

BitmapPHTreesPair

sign()[source]

Returns -1 if superlevel filtration. Otherwise returns 1.

class homcloud.interface.EigenVolume(diagram, optimal_volume)[source]

Bases: homcloud.interface.Volume

This class represents an “eigenvolume”. It is the superclass of TightenedVolume, TightenedSubvolume and OnwedVolume.

threshold

The threshold used for the computation of the eigenvolume.

Type:float
class homcloud.interface.Histogram(orig)[source]

Bases: object

The class represents a histogram on birth-death plane.

x_range()
Returns:The lower and upper range of x-axis.
Return type:(tuple[int, int])
x_bins()
Returns:The number of bins on x-axis.
Return type:(int)
y_range()
Returns:The lower and upper range of y-axis.
Return type:(tuple[int, int])
y_bins()
Returns:The number of bins on y-axis.
Return type:(int)
xedges

The edges of bins on x-axis in ascending order.

Type:numpy.ndarray[x_bins + 1]
yedges

The edges of bins on y-axis in ascending order.

Type:numpy.ndarray[y_bins + 1]
plot(colorbar={}, style='colorhistogram', title='', unit_name=None, font_size=None, aspect='equal', ax=None, levels=None)[source]

Plot a histogram by matplotlib.

Parameters:
  • colorbar (dict) –

    The specification of the histogram colors and the colorbar.

    The following fields are available for this dictionary.

    • ”type” - The name of colorbar type. One of the followings is available. The default type is “linear”.
      • ”linear” - linear scale
      • ”log” - log scale
      • ”loglog” - log(log(n+1)+1)
      • ”linear-midpoint” - linear scale with midpoint. You should specify the value of midpoint by the “midpoint” field.
      • ”power” - n^p. You should specify p by “p” field.
    • ”min” - The minimum of the colorbar. If this value is not specified, the value is determined by the minimum of histogram values.
    • ”max” - The maximum of the colorbar. If this value is not specified, the value is determined by the maximum of histogram values.
  • style (string) – The plotting style. “colorhistogram” or “contour” is available.
  • title (string) – The title of the output figure.
  • unit_name (string or None) – The unit name of the x-axis and y-axis.
  • font_size (float or None) – The font size. The font size is automatically determined if None is given.
  • aspect (string) – The X-Y aspect. “equal” or “auto” is available.
  • ax (matplotlib.axes.Axes or None) – The axes to be plotted on. By default (if None), matplotlib.pyplot.subplot() is used.
  • levels (list of floats or None) – The levels for coutour plotting. This argument is used only if style is “contour”.

Example

>>> import matplotlib.pyplot as plt
>>>    :
>>> histogram.plot(colorbar={"type": "log", "max": 100},
>>>                title="Title string")
>>> plt.show()  # To show the histogram on your display
>>> plt.savefig("histogram.png")  # To save the histogram figure.
values

2-dimensional array of values in the bins.

Type:(numpy.ndarary, shape (x_bins, y_bins))
class homcloud.interface.MaskHistogram(orig)[source]

Bases: homcloud.interface.Histogram

The class represents a histogram on birth-death plane whose values are booleans.

This class is helpful to pick up all birth-death pairs in an area. meth:Mesh.mask_from_vector and meth:Mesh.mask_from_2darray is available for this purpose.

filter_pairs(pairs)[source]

Returns all pairs in the area of bins whose values are True.

Parameters:pairs (sequence of Pair) – Pairs to be filtered.
Returns:The filtered pairs.
Return type:list of Pair

Notes

In fact, this method can filter the list of OptimalVolume by their birth and death times.

filter_pd(pd)[source]

Returns all pairs of the persistence diagram in the area of bins whose values are True.

Parameters:pd (PD) – A persistence diagram which has pairs to be filtered.
Returns:The filtered pairs.
Return type:list of Pair
class homcloud.interface.Mesh(x_range, xbins, y_range=None, ybins=None, pd=None, superlevel=False)[source]

Bases: object

This class represents a 2D mesh on the plane of birth-death pairs.

This class is useful to compute histograms from many diagrams with the same setting.

Parameters:
  • x_range (tuple(float, float) or None) – The lower and upper range of the bins on x-axis.
  • y_range (tuple(float, float) or None) – The number of bins on x-axis.
  • y_range – The lower and upper range of the bins on y-axis. Same as x_range if None is given.
  • y_bins (int or None) – The number of bins on y-axis. Same as x_bins if None is given.
  • superlevel (bool) – This should be True if your PDs come from superlevel filtrations, otherwise this should be False.

Examples

>>> import homcloud.interface as hc
>>> import matplotlib.pyplot as plt
>>> pc = np.array([[0, 0, 0], [8, 0, 0], [5, 6, 0], [4, 2, 6],])
>>> pd = hc.PDList.from_alpha_filtration(pc).dth_diagram(1)
>>> mesh = hc.Mesh((0, 20), 128)
>>> histogram = mesh.pd_histogram(pd)
>>> histogram.plot(colorbar={"type": "log"}, title="1st PD")
>>> plt.show()
-> The histogram is displayed.
histogram_from_vector(vector)[source]

Construct a histogram from a vector.

The histogram is constructed by the rule of persistence image method.

Parameters:vector (numpy.ndarray) – A vector.
Returns:The histogram.
Return type:Histogram
mask_from_vector(vector)[source]

Construct a mask histogram from a boolean vector.

The histogram is constructed by the rule of persistence image method.

Parameters:vector (numpy.ndarray) – A boolean vector.
Returns:
The “histogram” whose values in bins are
True or False.
Return type:MaskHistogram
pd_histogram(pd)[source]

Constructs a 2D histogram of pd.

Parameters:pd (PD) – The diagram.
Returns:The histogram.
Return type:Histogram
vector_size()[source]

Return the size of the vector generated by self.

Returns:The size of the vector
Return type:int
class homcloud.interface.Optimal1CycleForBitmap(orig)[source]

Bases: object

The class represents an optimal (not volume-optimal) 1-cycle.

Computing volume-optimal cycle is very expensive for 3-D and higher dimensional cubical filtration. To fight against such a huge filtration, Pair.optimal_1_cycle() is available. This method returns an instance of this class.

birth_position()[source]
Returns:The coordinate of birth position. (N: dimension)
Return type:tuple of float*N
birth_time()[source]
Returns:The birth time.
Return type:float
boundary_points()[source]
Returns:
The list of vertices in the loop. Any vertex
in the list is unique.
Return type:list of coord
death_time()[source]
Returns:The death time.
Return type:float
path()[source]

Returns the path (loop) of the optimal 1-cycle.

The first item and the last item is the same as birth_position().

Returns:The list of vertices of the loop ordered by the path
Return type:list of coord
to_paraview_node(gui_name=None)[source]

Construct a homcloud.paraview_interface.PipelineNode object to visulize an optimal 1-cycle.

You can show the optimal 1-cycle by homcloud.paraview_interface.show(). You can also adjust the visual by the methods of homcloud.paraview_interface.PipelineNode.

Parameters:gui_name (string or None) – The name shown in Pipeline Browser in paraview’s GUI.
Returns:A PipelineNode object.
Return type:homcloud.paraview_interface.PipelineNode
static to_paraview_node_for_1cycles(cycles, gui_name=None)[source]

Construct a homcloud.paraview_interface.PipelineNode object to visulize multiple optimal 1-cycles.

Parameters:
  • cycles (list of Optimal1CycleForBitmap) – The optimal 1-cycles to be visualized.
  • gui_name (string or None) – The name shown in Pipeline Browser in paraview’s GUI.
Returns:

A PipelineNode object.

Return type:

homcloud.paraview_interface.PipelineNode

to_pvnode(gui_name=None)

Construct a homcloud.paraview_interface.PipelineNode object to visulize an optimal 1-cycle.

You can show the optimal 1-cycle by homcloud.paraview_interface.show(). You can also adjust the visual by the methods of homcloud.paraview_interface.PipelineNode.

Parameters:gui_name (string or None) – The name shown in Pipeline Browser in paraview’s GUI.
Returns:A PipelineNode object.
Return type:homcloud.paraview_interface.PipelineNode
static to_pvnode_for_1cycle(cycles, gui_name=None)

Construct a homcloud.paraview_interface.PipelineNode object to visulize multiple optimal 1-cycles.

Parameters:
  • cycles (list of Optimal1CycleForBitmap) – The optimal 1-cycles to be visualized.
  • gui_name (string or None) – The name shown in Pipeline Browser in paraview’s GUI.
Returns:

A PipelineNode object.

Return type:

homcloud.paraview_interface.PipelineNode

class homcloud.interface.OptimalVolume(diagram, optimal_volume, query)[source]

Bases: homcloud.interface.Volume

This class represents an optimal volume.

birth_position()
Returns:The birth simplex.
Return type:simplex
birth_pos

The alias of birth_position().

owned_volume(threshold, connected)[source]

Returns the owned volume of the optimal volume.

Parameters:threshold (float) – The threshold of the owned volume.
Returns:The owned volume.
Return type:OwnedVolume
tightened_subvolume(threshold)[source]

Returns the tightened subvolume of the optimal volume.

Parameters:threshold (float) – The threshold of the tightened subvolume.
Returns:The tightened subvolume.
Return type:TightenedSubvolume
class homcloud.interface.OwnedVolume(diagram, optimal_volume)[source]

Bases: homcloud.interface.EigenVolume

This class represents an onwned volume.

The instance is given by OptimalVolume.owned_volume().

class homcloud.interface.PD(path, pd)[source]

Bases: object

The class for a single persistence diagram.

You can get the object of this class by PDList.dth_diagram() or PDList.__getitem__().

path

File path

Type:str
degree

Degree of the PD

Type:int
births

Birth times

Type:numpy.ndarray[num_of_pairs]
deaths

Death times

Type:numpy.ndarray[num_of_pairs]
birth_positions

Birth positions for birth-death pairs

death_positions

Death positions for birth-death pairs

essential_births

Birth times of essenatila birth-death pairs (birth-death pairs with infinite death time)

Type:numpy.ndarray[num_of_ess_pairs]
essential_birth_positions

Birth positions for essenatial birth-death pairs

birth_death_times()[source]

Returns the birth times and death times.

Returns:The pair of birth times and death times
Return type:tuple[numpy.ndarray, numpy.ndarray]
static empty()[source]

Returns a persistence diagram which has no birth-death pairs.

Returns:A PD object with no birth-death pair.
Return type:PD
histogram(x_range=None, x_bins=128, y_range=None, y_bins=None)[source]

Returns the histogram of the PD.

This is the shortcut method of Mesh.pd_histogram()

Parameters:
  • x_range (tuple[float, float] or None) – The lower and upper range of the bins on x-axis. If None is given, the range is determined from the minimum and maximum of the birth times and death times of all pairs.
  • y_range (tuple[float, float] or None) – The number of bins on x-axis.
  • y_range – The lower and upper range of the bins on y-axis. Same as x_range if None is given.
  • y_bins (int or None) – The number of bins on y-axis. Same as x_bins if None is given.
nearest_pair_to(x, y)[source]

Returns a pair closest to (x, y).

Parameters:
  • x (float) – X-coordinate.
  • y (float) – Y-coordinate.
Returns:

The cleosest pair.

Return type:

Pair

pair(nth)[source]

Returns nth birth-death pairs.

Parameters:nth (int) – Index of the pair.
Returns:The nth pair.
Return type:Pair
pairs()[source]

Returns all pairs of the PD.

Returns:All birth-death pairs.
Return type:list of Pair
pairs_in_rectangle(xmin, xmax, ymin, ymax)[source]

Returns all pairs in the rectangle.

Returns all birth-death pairs whose birth time is in the interval [xmin, xmax] and whose death time is in [ymin, ymax].

Parameters:
  • xmin (float) – The lower range of birth time.
  • xmax (float) – The upper range of birth time.
  • ymin (float) – The lower range of death time.
  • ymax (float) – The upper range of death time.
Returns:

All birth-death pairs in the rectangle.

Return type:

list of Pair

phtrees(save_to=None)[source]

Computes a PH trees from an alpha filtration.

Parameters:save_to (string or None) – The filepath of the file which the PH trees information is saved in. You can load the PHTrees information from the file by using the constructor of PHTrees.
Returns:PHTrees object.
Return type:PHTrees
slice_histogram(x1, y1, x2, y2, width, bins=100)[source]

Returns 1D histogram of birth-death pairs in a thin strip.

This method computes a 1D hitogram of birth-death pairs in the thin strip whose center line is (x1, y1) - (x2, y2) and whose width is width.

Parameters:
  • x1 (float) – The x(birth)-coordinate of the starting point.
  • y1 (float) – The y(death)-coordinate of the starting point.
  • x2 (float) – The x(birth)-coordinate of the ending point.
  • y2 (float) – The y(death)-coordinate of the ending point.
  • width (float) – Width of the strip.
  • bins (int) – The number of bins.
Returns:

The histogram.

Return type:

SliceHistogram

class homcloud.interface.PDList(path, type=None, cache=False, negate=False)[source]

Bases: object

Collection of 0th,1st,..,and q-th persitence diagrams.

In HomCloud, diagrams for all degrees coming from a filtration are combined into a single file. This class is the interface to the file.

Parameters:
  • path (string) – The pathname to a diagram file
  • type (string) – Type of diagram file. One of the following: “diagram”, “idiagram”, or None (autodetected)
  • cache (bool) – dth_diagram() is cached if True.
  • negate (bool) – If true all birth/death time sholud be negated. This value is true only if you use a diagram which is not indexed.
__getitem__(d)

Return d-th persistence diagram from PDList.

Parameters:d (int) – the degree of the diagram
Returns:The PD object.
dth_diagram(d)[source]

Return d-th persistence diagram from PDList.

Parameters:d (int) – the degree of the diagram
Returns:The PD object.
static from_alpha_filtration(pointcloud, weight=False, no_squared=False, subsets=False, check_acyclicity=False, algorithm=None, parallels=1, vertex_symbols=None, save_to=None, indexed=True, save_boundary_map=False)[source]

Compute PDList by using an alpha filtration from a point cloud.

Parameters:
  • pointcloud (numpy.ndarray) – Point cloud data. Each row represents a sigle point.
  • weight (bool) – If False, the pointcloud has no weight. If True, the last column of the pointcloud ndarray is regarded as weights. Please note that the weight paramters of points should be the square of their own radii.
  • no_squared (bool) – By default, all birth/death times are squared. If no_squared is True, all computed birth/death times are not squared.
  • subsets (list[int] or bool or None) –

    This parameter is used to compute relative homology. This parameter allows you to analyze the interspace structures between two or more objects in your pointcloud.

    If subsets is None, normal persistent homology is computed.

    If subsets is a list of integers whose length is the same as the number of points, the points are grouped by the integers and the gaps in the points in the same group is filled. The integer -1 in this list means that the point does not belong to any group.

    If subsets is True, the last column of pointcloud is regarded as the list of group id.

  • check_acyclicity (bool) – Checks the acyclicity of each grouped points in subsets if True. This parameter is used only if subsets parameter is used.
  • algorithm (string or None) –

    The name of the algorithm. An appropriate algorithm is automatically selected if None is given.

    The following algorithms are available:

    • ”phat-twist”
    • ”phat-chunk-parallel”
    • ”dipha”

    In many cases, the parameter should be None.

  • vertex_symbols (list[string] or None) –

    The names of vertices. The names are used to represent some simplices, such as birth/death simplices or optimal volumes.

    If None is given, vertices are automatically named by “0”, “1”, “2”, …

  • parallels (int) – The number of threads used for the computation. This parameter is used only if “dipha” algorithm is used.
  • save_to (string) – The file path which the computation result is saved into. You can load the saved data by homcloud.interface.PDList(FILE_PATH). Saving the result is recommended since the computation cost is often expensive.
  • save_boundary_map (bool) – The boundary map constructed by the given pointcloud is saved if this parameter is True. The boundary map is used to compute volume optimal cycles.
Returns:

The PDList object computed from the pointcloud.

Examples

>>> import homcloud.interface as hc
>>> pointcloud = hc.example_data("tetrahedron")
>>> hc.PDList.from_alpha_filtration(pointcloud)
-> Returns a new PDList
static from_bitmap_distance_function(binary_pict, signed=False, metric='manhattan', type='bitmap', mask=None, algorithm=None, parallels=1, save_to=None, indexed=True, save_boundary_map=False)[source]

This method is obsolete. Please use the combination of PDList.from_bitmap_levelset() and distance_transform() instead.

Computes erosion/dilation PDList from an n-dimensional bitmap.

In other words, this method computes the sublevel filtration whose level function is the distance function.

Parameters:
  • binary_pict (numpy.ndarray) – An n-dimensional boolean array.
  • signed (bool) – The signed distance function is used instead of the normal distance function if True.
  • metric (string) –

    The metric. One of the followings:

    • ”manhattan”
    • ”chebyshev”
    • ”euclidean”
  • type (string) – An internal filtration type. “bitmap” or “cubical”. You can change the internal file format by this parameter. The file size of “bitmap” format is much smaller than “cubical”. However, if you want to use the following functionality, you must use “cubical” format.
  • mask (numpy.ndarray or None) – The mask bitmap.
  • algorithm (string, None) –

    The name of the algorithm. An appropriate algorithm is automatically selected if None is given.

    The following algorithms are available:

    • ”phat-twist”
    • ”phat-chunk-parallel”
    • ”dipha”

    In many cases, the parameter should be None.

  • parallels (int) – The number of threads used for the computation. This parameter is used only if “dipha” algorithm is used.
  • save_to (string) – The file path which the computation result is saved into. You can load the saved data by homcloud.interface.PDList(FILE_PATH). Saving the result is recommended since the computation cost is often expensive.
  • save_boundary_map (bool) – The boundary map constructed by the given pointcloud is saved if this parameter is True. The boundary map is used to compute volume optimal cycles.
Returns:

The PDList object computed from the bitmap.

static from_bitmap_levelset(array, mode='sublevel', type='bitmap', algorithm=None, parallels=1, periodicity=None, save_to=None, indexed=True, save_boundary_map=False)[source]

Computes superlevel/sublevel PDList from an n-dimensional bitmap.

Parameters:
  • array (numpy.ndarray) – An n-dimensional array.
  • mode (string) – The direction of the filtration. “superlevel” or “sublevel”.
  • type (string) –

    An internal filtration type. “bitmap” or “cubical”. You can change the internal file format by this parameter. The file size of “bitmap” format is much smaller than “cubical”. However, if you want to use the following functionality, you must use “cubical” format.

    • Periodic bitmaps (cylinder, torus, etc.)
    • Volume optimal cycles
  • algorithm (string, None) –

    The name of the algorithm. An appropriate algorithm is automatically selected if None is given.

    The following algorithms are available:

    • ”phat-twist”
    • ”phat-chunk-parallel”
    • ”dipha”

    In many cases, the parameter should be None.

  • parallels (int) – The number of threads used for the computation. This parameter is used only if “dipha” algorithm is used.
  • periodicity (None, list of bool) – The list of booleans to specify the periodicity. Any periodic structure is not used if None.
  • save_to (string) – The file path which the computation result is saved into. You can load the saved data by homcloud.interface.PDList(FILE_PATH). Saving the result is recommended since the computation cost is often expensive.
  • save_boundary_map (bool) – The boundary map constructed by the given pointcloud is saved if this parameter is True. The boundary map is used to compute volume optimal cycles.
Returns:

The PDList object computed from the bitmap.

Examples

>>> import numpy as np
>>> import homcloud.interface as hc
>>> bitmap = np.array([[1.5, 2.0, 0.5],
>>>                    [0.8, 4.1, 0.9],
>>>                    [1.3, 1.8, 1.3]])
>>> hc.PDList.from_bitmap_levelset(bitmap, "sublevel")
-> Returns PDList object for sublevel persistence diagrams
>>> hc.PDList.from_bitmap_levelset(bitmap, "superlevel",
>>>                             periodicity=[True, True])
-> Returns PDList object for superlevel PDList on a 2-torus
static from_rips_filtration(distance_matrix, maxdim, maxvalue=inf, indexed=False, vertex_symbols=None, algorithm=None, parallels=1, save_to=None)[source]

Compute a PDList from a distance matrix by using Vietoris-Rips filtrations.

Parameters:
  • distance_matrix (numpy.ndarary) – KxK distance matrix.
  • maxdim (int) – Maximal homology degree computed.
  • maxvalue (float) – Maximal distance for constructing a filtration. All longer edges do not apper in the constructed filtration.
  • indexed (bool) – TODO
  • vertex_symbols (list[string] or None) –

    The names of vertices. The names are used to represent some simplices, such as birth/death simplices or optimal volumes.

    If None is given, vertices are automatically named by “0”, “1”, “2”, …

  • algorithm – The name of the algorithm, “dipha” and “ripser” are available.
  • paralles – The number of threads for computation. This value is used only if algorith is “dipha”.
  • save_to (string or None) – The file path which the computation result is saved into. You can load the saved data by homcloud.interface.PDList(FILE_PATH). Saving the result is recommended since the computation cost is often expensive.
invoke_gui_plotter(d, x_range=None, xbins=None, y_range=None, ybins=None, colorbar={'type': 'linear'}, title=None, unit_name=None, aspect='equal', optimal_volume=False, optimal_volume_options=None)[source]

Invoke the GUI plotter.

Parameters:d (int) – The degree of the PD.
save(dest)[source]

Save the PDList into dest.

Parameters:dest (string) – The filepath which the diagram data is saved into.
homcloud.interface.PDs

Obsolete, for backward compatibility

alias of homcloud.interface.PDList

class homcloud.interface.PHTrees(path)[source]

Bases: object

This class represents PH trees computed from an alpha filtration.

Please see https://arxiv.org/abs/1712.05103 if you want to know the details of optimal volumes and volume optimal cycles.

You can compute the PH trees by PD.phtrees().

Parameters:path (string) – The filepath.

Example

>>> import homcloud.interface as hc
>>> pointcloud = hc.example_data("tetrahedron")
>>> pdlist = hc.PDList.from_alpha_filtration(pointcloud)
>>> # Computes PH trees and save them in "tetrahedron.pht"
>>> pdlist.dth_diagram(2).phtrees(save_to="tetrahedron.pht")
>>> # Load the file.
>>> phtrees = hc.PHTrees("tetrahedron.pht")
>>> # Query the node whose birth-death pair is nearest to (19, 21).
>>> node = phtrees.node_nearest_to(19, 21)
>>> # Show birth time and death time
>>> node.birth_time()
19.600000000000005
>>> node.death_time()
21.069444444444443
>>> node.boundary_points()
[[0.0, 0.0, 0.0], [8.0, 0.0, 0.0], [5.0, 6.0, 0.0], [4.0, 2.0, 6.0]]
>>> node.boundary()
[[[0.0, 0.0, 0.0], [5.0, 6.0, 0.0], [4.0, 2.0, 6.0]],
 [[0.0, 0.0, 0.0], [8.0, 0.0, 0.0], [5.0, 6.0, 0.0]],
 [[8.0, 0.0, 0.0], [5.0, 6.0, 0.0], [4.0, 2.0, 6.0]],
 [[0.0, 0.0, 0.0], [8.0, 0.0, 0.0], [4.0, 2.0, 6.0]]]
class Node(index, birth_index, parent_index, index_map)[source]

Bases: homcloud.full_ph_tree.Node

The class represents a tree node of PHTrees.

birth_time()
Returns:The birth time of the corresponding birth-death pair.
Return type:float
death_time()
Returns:The death time of the corresponding birth-death pair.
Return type:float
lifetime()
Returns:The lifetime of the corresponding birth-death pair.
Return type:float
points()
Returns:Points in the optimal volume.
Return type:list of list of float, a.k.a list of points
simplices()
Returns:The simplices in the optimal volume.
Return type:list of list of list of float, a.k.a list of simplex
boundary()[source]
Returns:Points in the volume optimal cycle.
Return type:list of list of float, a.k.a. list of points
boundary_points()
Returns:Points in the volume optimal cycle.
Return type:list of list of float, a.k.a list of points
points_symbols()
Returns:All vertices in the optimal volume in the form of the symbolic representation.
Return type:list of string
volume_simplices_symbols()
Returns:All simplices in volume optimal cycles in the form of the symbolic representation.
Return type:list of list of string
boundary_points_symbols()
Returns:All vertices in the volume optimal cycle in the form of the symbolic representation.
Return type:list of string
boundary_symbols()
Returns:All simplices in the volume optimal cycle in the form of the symbolic representation.
Return type:list of list of string
birth_position()

Returns the birth simplex.

death_position()

Returns the death simplex.

ancestors()
Returns:The ancestors of the tree node include itself.
Return type:list of PHTrees.Node
to_paraview_node(gui_name=None)[source]

Construct a homcloud.paraview_interface.PipelineNode object to visulize an optimal volume of the node.

gui_name (string or None): The name shown in Pipeline Browser
in paraview’s GUI.
Returns:Paraview Pipeline node object.
Return type:homcloud.paraview_interface.VTK
to_pvnode(gui_name=None)

Construct a homcloud.paraview_interface.PipelineNode object to visulize an optimal volume of the node.

gui_name (string or None): The name shown in Pipeline Browser
in paraview’s GUI.
Returns:Paraview Pipeline node object.
Return type:homcloud.paraview_interface.VTK
nodes_of(pairs)[source]

Returns the nodes of trees corresponding to birth-death pairs in pairs.

Parameters:pairs (list of Pair) – The list of pairs.
Returns:The nodes.
Return type:list of PHTrees.Node
pair_node_nearest_to(x, y)[source]

Return the node corresponding the pair which is nearest to (x, y).

Parameters:
  • x (float) – The birth-axis coordinate.
  • y (float) – The death-axis coordinate.
Returns:

The nearest node.

Return type:

PHTrees.Node

pair_nodes_in_rectangle(xmin, xmax, ymin, ymax)[source]

Returns the list of nodes corresponding to the birth-death pairs in the given rectangle.

Parameters:
  • xmin (float) – The minimum of the birth-axis of the rectangle.
  • xmax (float) – The maximum of the birth-axis of the rectangle.
  • ymin (float) – The minimum of the death-axis of the rectangle.
  • ymax (float) – The maximum of the death-axis of the rectangle.
Returns:

The nodes in the rectangle.

Return type:

list of PHTrees.Node

save(dest)[source]

Saves the data file to dest.

Parameters:dest (string) – The filepath.
to_paraview_node_from_nodes(nodes, gui_name=None)[source]

Construct a homcloud.paraview_interface.PipelineNode object to visulize optimal volumes of the nodes.

Parameters:
  • nodes (list of PHTrees.Node) – The list of nodes to be visualized.
  • gui_name (string or None) – The name shown in Pipeline Browser in paraview’s GUI.
Returns:

Paraview Pipeline node object.

Return type:

homcloud.paraview_interface.VTK

Notes

All nodes should be nodes of self PHTrees.

to_pvnode_from_nodes(nodes, gui_name=None)

Construct a homcloud.paraview_interface.PipelineNode object to visulize optimal volumes of the nodes.

Parameters:
  • nodes (list of PHTrees.Node) – The list of nodes to be visualized.
  • gui_name (string or None) – The name shown in Pipeline Browser in paraview’s GUI.
Returns:

Paraview Pipeline node object.

Return type:

homcloud.paraview_interface.VTK

Notes

All nodes should be nodes of self PHTrees.

class homcloud.interface.PIVectorizerMesh(x_range, xbins, y_range=None, ybins=None, weight=None, sigma=None, superlevel=False)[source]

Bases: homcloud.interface.Mesh

This class represents a 2D mesh on the plane of birth-death pairs with information about vectorization by persistence image (PI) method.

You can construct PI vectors from diagrams.

Parameters:
  • x_range (tuple[float, float] or None) – The lower and upper range of the bins on x-axis.
  • xbins (int) – The number of bins on x-axis.
  • y_range (tuple[float, float] or None) – The lower and upper range of the bins on y-axis. Same as x_range if None is given.
  • ybins (int or None) – The number of bins on y-axis. Same as x_bins if None is given.
  • weight (tuple or string) –

    The information of the weight function. You can use one of the followings:

    • ”none”: A constant weight function
    • (“atan”, c, p): An arctangent weight function, c and p should be floats. The weight function is c*atan((death - birth)**p) .
    • (“linear”, a): A linear weight function. a should be a float. The weight function is a*(death - birth) .
  • sigma (float) – The standard deviation for the Gaussian distribution used by PI.
  • superlevel (bool) – This should be True if your PDs come from superlevel filtrations, otherwise this should be False. Internally, This parameter should be True if the PD has birth-death pairs with birth > death, and otherwise the parameter should be False.
vectorize(pd)[source]

Vectroize pd.

Parameters:pd (PD) – A persistence diagram.
Returns:The vectorized diagram.
Return type:numpy.ndarray
vectorize_pair(pair)[source]

Vectorize a PD with a signle pair.

Parameters:pd (PD or tuple[double, double]) – A birth-death pair
Returns:The vectorized diagram.
Return type:numpy.ndarray
class homcloud.interface.Pair(diagram, birth_index, death_index, birth_position, death_position)[source]

Bases: object

A class representing a birth-death pair.

diagram

The diagram which the birth-death pair belongs to.

Type:PD
birth

The birth time

Type:float
birth_pos

The birth position

birth_time()[source]

Returns the birth time of the pair.

Returns:The birth time
Return type:float
death

The death time

Type:float
death_pos

The death position

death_time()[source]

Returns the death time of the pair.

Returns:The death time
Return type:float
degree

The degree of the pair.

lifetime()[source]

The lifetime of the pair.

Returns:The lifetime (death - birth) of the pair.
Return type:float
optimal_1_cycle()[source]

Returns the optimal (not volume-optimal) 1-cycle corresponding to the birth-death pair.

This method is available only for a bitmap filtration.

Returns:The optimal 1-cycle.
Return type:Optimal1CycleForBitmap
Raises:AssertionError – Raised if the filtration is not a bitmap filtration or the degree of the pair is not 1.
optimal_volume(cutoff_radius=None, solver=None, constrain_birth=False, num_retry=4, integer_programming=False)[source]

Return the optimal volume of the pair.

Parameters:
  • cutoff_radius (float or None) – The cutoff radius. Simplices which are further from the center of birth and death simplices than cutoff_radius are ignored for the computation of an optimal volume. You can reduce the computation time if you set the cutoff_radius properly. Too small cutoff_radius causes the failure of the computation. If this argument is None, all simplices are not ignored.
  • solver (string or None) – The name of the LP solver. The default solver (coinor Clp) is selected if None is given.
  • constrain_birth (bool) – Now this value is not used.
  • num_retry (int) – The number of retry. The cutoff_radius is doubled at every retrial.
  • integer_programming (bool) – Integer constrains are used if True. Integer constrains make the computation slower, but possibly you get a better result.
Returns:

The optimal volume.

Return type:

OptimalVolume

tightened_volume(threshold, cutoff_radius=None, solver=None, constrain_birth=False, num_retry=4, integer_programming=False)[source]

Returns the tightend volume of the pair.

Parameters:
  • threshold (float) – Positive float for tightening.
  • cutoff_radius (float or None) – The cutoff radius. Simplices which are further from the center of birth and death simplices than cutoff_radius are ignored for the computation of an optimal volume. You can reduce the computation time if you set the cutoff_radius properly. Too small cutoff_radius causes the failure of the computation. If this argument is None, all simplices are not ignored.
  • solver (string or None) – The name of the LP solver. The default solver (coinor Clp) is selected if None is given.
  • constrain_birth (bool) – Now this value is not used.
  • num_retry (int) – The number of retry. The cutoff_radius is doubled at every retrial.
  • integer_programming (bool) – Integer constrains are used if True. Integer constrains make the computation slower, but possibly you get a better result.
Returns:

The tightened volume.

Return type:

TightenedVolume

class homcloud.interface.SliceHistogram(values, edges, x1, y1, x2, y2)[source]

Bases: object

This class represents a 1D histogram of birth-death pairs in the thin strip on a persistence diagram.

You can create an instance by PD.slice_histogram().

values

The histogram values.

Type:numpy.ndarary
x1

The x-coordinate of the one end of the strip.

Type:float
y1

The y-coordinate of the one end of the strip.

Type:float
x2

The x-coordinate of the another end of the strip.

Type:float
y2

The y-coordinate of the another end of the strip.

Type:float
plot(left_label=None, right_label=None, logscale=False, ax=None)[source]

Plots the historam.

Parameters:
  • left_label (string) – The label text at (x1, y1)
  • right_label (string) – The label text at (x2, y2)
  • logscale (bool) – Linear scale is used if False, and Log scale is used if True.
  • ax (matplotlib.axes.Axes or None) – The axes to be plotted on. By default (if None), matplotlib.pyplot.gca() is used.
class homcloud.interface.TightenedSubvolume(diagram, optimal_volume)[source]

Bases: homcloud.interface.EigenVolume

This class represents a tightened subvolume.

The instance is given by OptimalVolume.tightened_subvolume().

class homcloud.interface.TightenedVolume(diagram, optimal_volume)[source]

Bases: homcloud.interface.EigenVolume

This class represents a tightened volume.

The instance is given by Pair.tightened_volume().

class homcloud.interface.Volume(diagram, optimal_volume)[source]

Bases: object

This class represents a volume. This is the superclass of OptimalVolume, TightendVolume, TightedSubvolume, and OwnedVolume.

Notes

  • point: list of float
  • cell: simplex or cube, simplex is used if the filtration is simplicial (alpha filtration) and cube is used if the filtration is cubical.
  • simplex: list of point
  • cube: tuple[point, list of bool],
  • ssimplex: list of string
birth_time()[source]
Returns:The birth time.
Return type:float
death_time()[source]
Returns:The death time.
Return type:float
points()
Returns:All vertices in the optimal volume.
Return type:list of point
boundary_points()
Returns:All vertices in the volume optimal cycle.
Return type:list of point
boundary()
Returns:All cells in the volume optimal cycle.
Return type:list of cells
death_position()
Returns:The death simplex.
Return type:simplex
points_symbols()
Returns:All vertices in the optimal volume in the form of the symbolic representation.
Return type:list of string
volume_simplices_symbols()
Returns:All simplices in volume optimal cycles in the form of the symbolic representation.
Return type:list of ssimplex
boundary_points_symbols()
Returns:All vertices in the volume optimal cycle in the form of the symbolic representation.
Return type:list of string
boundary_symbols()
Returns:All simplices in the volume optimal cycle in the form of the symbolic representation.
Return type:list of ssimplex
birth_time()[source]

Returns the birth time.

children()[source]
Returns:All children pairs.
Return type:list of Pair
cubes()[source]
Returns:All cubes in volume optimal cycles.
Return type:list of cube
death_pos

The alias of death_position().

death_time()[source]

Returns the death time.

lifetime()[source]
Returns:The lifetime of the pair.
Return type:float
pair()[source]

Returns the corresponding birth-death pair by Pair.

simplices()[source]
Returns:All simplices in volume optimal cycles.
Return type:list of simplex
to_dict()[source]
Returns:The information about the optimal volume.
Return type:dict
to_paraview_node(gui_name=None)[source]

Construct a homcloud.paraview_interface.PipelineNode object to visulize an optimal volume.

You can show the optimal volume by homcloud.paraview_interface.show(). You can also adjust the visual by the methods of homcloud.paraview_interface.PipelineNode.

Parameters:gui_name (string or None) – The name shown in Pipeline Browser in paraview’s GUI.
Returns:A PipelineNode object.
Return type:homcloud.paraview_interface.PipelineNode
static to_paraview_node_for_volumes(volumes, gui_name=None)[source]

Construct a homcloud.paraview_interface.PipelineNode object to visulize multiple optimal volumes.

All optimal volumes should come from the same PD object.

Parameters:
  • volumes (list of OptimalVolume) – The optimal volumes to be visualized.
  • gui_name (string or None) – The name shown in Pipeline Browser in paraview’s GUI.
Returns:

A PipelineNode object.

Return type:

homcloud.paraview_interface.PipelineNode

to_pvnode(gui_name=None)

Construct a homcloud.paraview_interface.PipelineNode object to visulize an optimal volume.

You can show the optimal volume by homcloud.paraview_interface.show(). You can also adjust the visual by the methods of homcloud.paraview_interface.PipelineNode.

Parameters:gui_name (string or None) – The name shown in Pipeline Browser in paraview’s GUI.
Returns:A PipelineNode object.
Return type:homcloud.paraview_interface.PipelineNode
homcloud.interface.distance_transform(pict, signed=False, metric='manhattan', periodic=None, obstacle=None, VI=None, V=None)[source]

Distance transform.

Parameters:
  • pict (numpy.ndarray) – A binary picture. dtype must be bool.
  • signed (bool) – True for signed distance transform
  • metric (string) – Metric. The following metrics are available: “manhattan”, “chebyshev”, “euclidean”, “mahalanobis”
  • periodic (None or list of bool) – Periodic boundary condition
  • obstacle (None or numpy.ndarra) – Obstacle bitmap
  • VI (None or numpy.ndarray) – Inverse matrix for Mahalanobis metric
  • V (None or numpy.ndarray) – Matrix for Mahalanobis metric
Returns:

An ndarray object.

Example

>>> import homcloud.interface as hc
>>> import numpy as np
>>> bitmap = np.array([[0, 1, 0, 0], [1, 1, 0, 1]], dtype=bool)
>>> hc.PDList.from_bitmap_levelset(hc.distance_transform(bitmap, True))
-> Returns a new PDList
Remarks:
The current implementation for periodic BC is a simple periodic image copy method. Hence the performance is not so good. The developers of HomCloud plan to implove the efficiency in the future.
homcloud.interface.draw_birthdeath_pixels_2d(pairs, image, draw_birth=False, draw_death=False, draw_line=False, scale=1, marker_type='filled-diamond', marker_size=1, with_label=False, birth_color=(255, 0, 0), death_color=(0, 0, 255), line_color=(0, 255, 0))[source]

Draw birth/death pixels on the given image.

This function returns PIL.Image.Image object. Please see the document of pillow to know how to treat this object.

Parameters:
  • pairs (list of Pair) – The birth-death pairs.
  • image (string or numpy.ndarray or PIL.Image.Image) –

    The image data.

    • string: The image file whose name is image is used.
    • numpy.ndarray: 2D array is treated as grayscale image.
    • PIL.Image.Image: The image data
  • draw_birth (bool) – Birth pixels are drawn if True.
  • draw_death (bool) – Death pixels are drawn if True.
  • draw_line (bool) – The lines connecting each birth pixels and death pixels are drawn.
  • scale (int) – Image scaling factor.
  • marker_type (string) –

    The type of the markers. You can choose one of the followings:

    • ”filled-diamond”
    • ”point”
    • ”square”
    • ”filled-square”
    • ”circle”
    • ”filled-circle”
  • marker_size (int) – The size of the marker.
  • with_label (bool) – Show birth and death times beside each birth/death pixel marker.
  • birth_color (tuple[int, int, int]) – The color of birth pixel markers.
  • death_color (tuple[int, int, int]) – The color of death pixel markers.
  • line_color (tuple[int, int, int]) – The color of lines.
Returns:

The image data which birth/death pixels are drawn.

Return type:

PIL.Image.Image

homcloud.interface.draw_volumes_on_2d_image(nodes, image, color, alpha=1.0, birth_position=None, death_position=None, marker_size=1)[source]

Draws optimal volumes for bitmap filtration on an image.

Parameters:
  • nodes (list of BitmapPHTrees.Node) – The tree nodes to be drawn.
  • image (string or numpy.ndarray or PIL.Image.Image) –

    The base image data.

    • string: The image file whose name is image is used.
    • numpy.ndarray: 2D array is treated as grayscale image.
    • PIL.Image.Image: The image data

    If PIL.Image.Image object is given, the object is overwrited.

  • color (tuple[int, int, int]) – The color (RGB) of the volumes.
  • alpha (float) – The alpha value. The volume is drawn by using alpha blending.
  • birth_position (tuple[int, int, int] or None) – If not None, birth positions are drawn by the given color
  • death_position (tuple[int, int, int] or None) – If not None, death positions are drawn by the given color
  • marker_size (int) – The marker size of birth positions and death positions. 1, 3, 5, … are available.
Returns:

The image data which optimal volumes are drawn.

Return type:

PIL.Image.Image

homcloud.interface.example_data(name)[source]

Returns example data.

Returns the tetrahedron 3D pointcloud for name == “tetrahedron”.

Parameters:name – Name of the data

Examples

>>> import homcloud.interface as hc
>>> hc.example_data("tetrahedron")
array([[ 0.,  0.,  0.],
       [ 8.,  0.,  0.],
       [ 5.,  6.,  0.],
       [ 4.,  2.,  6.]])
homcloud.interface.loadtxt_nd(path)[source]

Load a n-dimensional data from text.

The format of the text file is as follows.

  • First line represents the shape of data. For example, if the shape of your d ata is 200x230x250, first line should be 200 230 250.
  • The following lines are floating point number values in x-fastest direction
  • A line starting with # is skipped as a comment
  • An empty line is also skipped.

The following is an example:

# 4x3x2 3D voxel data
4 3 2

1 2 3 4
5 6 7 8
9 10 11 12

13 14 15 16
17 18 19 20
21 22 23 24
Parameters:path (string) – The path of the text file.
homcloud.interface.show_slice3d(volumes, slice=0, spacer=0, range=None, image_viewer='eog -n')[source]

Display slices of 3D bitmap data.

Parameters:
  • volumes (list of numpy.ndarray) – multiple 3D bitmap data. These data are aligned horizontally.
  • slice (int) – The direction of slicing: 0, 1, or 2 for z, y, x direction.
  • spacer (int) – The number of pixels between horizontally aligned slices.
  • range (None or tuple[int, int]) – The range of the slices.
  • image_viewer (str) – Command line of the image viewer to see slices.