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

exception homcloud.interface.HomCloudError(message, code)[source]

Bases: Exception

Base exception class of all exceptions in homcloud.interface and homcloud.paraview_interface module.

exception homcloud.interface.VolumeNotFound(message, code)[source]

Bases: homcloud.interface.exceptions.HomCloudError

Exception class for Pair.optimal_volume() and Pair.stable_volume().

class homcloud.interface.PDList(file, filetype=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:
  • file (string or file) – The pathname to a diagram file
  • type (enum PDList.FileType) – Type of diagram file. One of the following: idiagram, pdgm, or None (autodetected)
  • cache (bool) – Ignored (for backward compatibility)
  • negate (bool) – Ignored (for backward compatibility)
class FileType[source]

Bases: enum.Enum

An enumeration.

__getitem__(d, load_indexed_pairs=True)

Return d-th persistence diagram from PDList.

Parameters:
  • d (int) – the degree of the diagram
  • load_indexed_pairs (bool) – index information is loaded if True. Otherwise, the information is not loaded. This parameter will be helpful to reduce the loading time.
Returns:

The PD object.

bitmap_phtrees(degree)[source]

Read a BitmapPHTrees object computed by BitmapPHTrees.for_bitmap_levelset().

Parameters:degree (int) – The PD degree. 0 or (n-1).
Returns:A BitmapPHTrees object
dth_diagram(d, load_indexed_pairs=True)[source]

Return d-th persistence diagram from PDList.

Parameters:
  • d (int) – the degree of the diagram
  • load_indexed_pairs (bool) – index information is loaded if True. Otherwise, the information is not loaded. This parameter will be helpful to reduce the loading time.
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_suppl_info=True, save_boundary_map=False, periodicity=None, save_phtrees=False, output_filetype=None)[source]

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

Parameters:
  • pointcloud (numpy.ndarray) – Point cloud data. Each row represents a single 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_suppl_info (bool) – Various supplimentary information is saved to the file save_to. The default is True. This information is required to show birth and death pixels and optimal volumes. If you do not use such HomCloud’s functionality and you want to reduce the size of the file, please set the argument False. If False, only birth and death times are stored to the file.
  • 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.
  • periodicity (tuple[tuple[float, float], tuple[float, float], tuple[float, float]] or None) – Periodic boundary condition.
  • save_phtrees (bool) – The PH-trees for (n-1)st PH is saved if True. Use meth:PD.load_phtrees to load the PH trees.
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_suppl_info=True, save_boundary_map=False, output_filetype=None)[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.

    • optimal volume/volume optimal cycle
    • dependency check for a field
  • 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:

    • ”homccubes-0”, “homccubes-1”, “homccubes-2”
    • ”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_suppl_info=True, save_boundary_map=False, output_filetype=None)[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” and the computation for “bitmap” is faster than “cubical”.
  • algorithm (string, None) –

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

    The following algorithms are available:

    • ”homccubes-0”, “homccubes-1”, “homccubes-2”
    • ”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. For example, if your array is 2D and you want to make the array periodic only in 0-axis, you should give [True, False]. 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.
  • indexed (bool) – Always must be True.
  • save_suppl_info (bool) – Various supplimentary information is saved to the file save_to. The default is True. This information is required to show birth and death pixels and optimal_1_cycles. If you do not use such HomCloud’s functionality and you want to reduce the size of the file, please set the argument False. If False, only birth and death times are stored to the file.
  • 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. This parameter is only available if the type is “cubical”.
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_boundary_information(boundary, levels, symbols=None, algorithm=None, parallels=1, save_to=None, save_boundary_map=False)[source]

Compute a PDList from a boundary map and level information for abstract combinatorial complex.

Parameters:
  • boundary (list of (int, list of int, list of int)) – list of cells and their boundary information. (dim of cell, list of indices of, list of coefs)
  • levels (numpy.ndarray) – level of each cell. Cells should be ordered in level-increasing order.
  • symbols (list of string, None) – The names of each cell.
  • algorithm (string, nil) – The name of the algorithm. An appropriate algorithm is automatically selected if None is given.
  • 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.
  • 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 computed from the boundary map.

Return type:

PDList

Examples

>>> import homcloud.interface as hc
>>>
>>> hc.PDList.from_boundary_information([
>>>     [0, [], []], [0, [], []], [0, [], []],  # theee 0-simplices
>>>     [1, [0, 1], [1, -1]], [1, [1, 2], [1, -1]], [1, [0, 2], [1, -1]],  # three 1-simplices
>>>     [2, [3, 4, 5], [1, 1, -1]],  # a 2-simplex
>>> ], [
>>>     -0.02, 0.01, 0.01,  # levels of 0-simplices
>>>     0.1, 0.2, 0.3,  # levels of 1-simplices
>>>     0.6  # level of the 2-simplex
>>> ], save_to="pd.pdgm"
>>> )
>>> pd1 = hc.PDList("pd.pdgm").dth_diagram(1)
>>> print(pd1.births)  # => [0.3]
>>> print(pd1.deaths)  # => [0.6]
static from_rips_filtration(distance_matrix, maxdim, maxvalue=inf, simplicial=False, vertex_symbols=None, algorithm=None, parallels=1, save_boundary_map=False, save_graph=False, save_cocycles=False, 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.
  • simplicial (bool) – If True, construct a simplicial complex for Pair.optimal_volume() (slow)
  • 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. An appropriate algorithm is automatically selected if None is given.

    If simplicial is False, “dipha” and “ripser” are available. If simpliclal is True, “dipha”, “phat-twist”, “phat-chunk-parallel” are availbale.

  • paralles – The number of threads for computation. This value is used only if algorith is “dipha”.
  • save_boundary_map (bool) – The boundary map constructed by the given distance matrix is saved if this parameter is True. The boundary map is used to compute volume optimal cycles. This option is only available if simplicial is True.
  • save_graph (bool) – The graph structure of rips filtration is saved in .pdgm file.
  • 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.
Returns:

The PDList object computed from the distance matrix.

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.
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 essential birth-death pairs (birth-death pairs with infinite death time)

Type:numpy.ndarray[num_of_ess_pairs]
essential_birth_positions

Birth positions for essential 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
static from_birth_death(degree, births, deaths, ess_births=array([], dtype=float64), sign_flipped=False)[source]

Returns a persistence diagram which birth and death times are given lists.

Parameters:
  • degree (int) – The degree of the returned diagram
  • births (numpy.ndarray) – The birth times
  • deaths (numpy.ndarray) – The death times
  • ess_births (numpy.ndarray) – The birth times of essential pairs
  • sign_flipped (bool) – The sign is flipped if True
Returns:

A PD object

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 HistoSpec.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.
Returns:

The Histogram object.

load_phtrees()[source]

Load a PH trees from the diagram.

This method is available only for the (n-1)th diagram of an alpha filtration of n-dimensional pointcloud.

You should compute the PH trees by PDList.from_alpha_filtration() with save_phtrees=True before using this method.

Returns:The PHTrees object of the (n-1)th PH.
nearest_pair_to(x, y)[source]

Returns a pair closest to (x, y).

Parameters:
  • x (float) – X (birth) coordinate.
  • y (float) – Y (death) 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

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.Pair(diagram, nth)[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

Alias of birth_position

birth_position

Birth position for the birth-death pair

birth_position_symbols

Birth simplex for the birth-death pair by symbols. Only available for alpha filtrations.

Type:list of string
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

Alias of death_position

death_position

Death position for the birth-death pair

death_position_symbols

Death simplex for the birth-death pair by symbols. Only available for alpha filtrations.

Type:list of string
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(weighted=False, torelance=None)[source]

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

You can calculate similar infomormation using optimal_volume(), but optimal_volume optimal_volume may be expensive, especiall for Vietoris-Rips filtration. optimal_1_cycle can be computed at a lower cost than optimal_volume. In general, an optimal volume gives better information about the birth-death pair, and an optimal 1-cycle gives an approximation of the optimal volume.

This method is available only when degree == 1.

If you want to compute optimal 1-cycle. You need to pass the following argument when computing persistence diagrams.

Parameters:
  • weighted (bool) – Use graph weight to find shortest loop. Only available for Vietoris-Rips filtration
  • torelance (None or float) – Noise bandwidth parameter for Reconstructed Shortest Cycles. Only available for Vietoris-Rips filtration
Returns:

The optimal 1-cycle.

Return type:

BitmapOptimal1Cycle | GraphOptimal1Cycle | Optimal1Cycle

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, solver_options=[], 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

Raises:

VolumeNotFound – Raised if the volume is not fould.

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

Returns the stable volume of the pair.

Parameters:
  • threshold (float) – The noise bandwidth.
  • 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.
  • solver_options (list of string) – Options for LP sovlers. The options are forwarded to Pulp program.
  • constrain_birth (bool) – Ignored
  • num_retry (int) – The number of retry. The cutoff_radius is doubled at every retrial.
  • integer_programming (bool) – Ignored.
Returns:

The stable volume.

Return type:

StableVolume

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

Returns the stable volume of the pair.

Parameters:
  • threshold (float) – The noise bandwidth.
  • 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.
  • solver_options (list of string) – Options for LP sovlers. The options are forwarded to Pulp program.
  • constrain_birth (bool) – Ignored
  • num_retry (int) – The number of retry. The cutoff_radius is doubled at every retrial.
  • integer_programming (bool) – Ignored.
Returns:

The stable volume.

Return type:

StableVolume

class homcloud.interface.HistoSpec(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)
>>> histospec = hc.HistoSpec((0, 20), 128)
>>> histogram = histospec.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
homcloud.interface.Mesh

alias of homcloud.interface.histogram.HistoSpec

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

Bases: homcloud.interface.histogram.HistoSpec

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 atan(c * (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 (Pair or tuple[double, double]) – A birth-death pair
Returns:The vectorized diagram.
Return type:numpy.ndarray
homcloud.interface.PIVectorizerMesh

alias of homcloud.interface.histogram.PIVectorizeSpec

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, plot_ess=False)[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.
    • ”colormap” - matplotlib’s colormap name
  • 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”.
  • plot_ess (bool) – Essential pairs are plotted if True.

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.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:HistoSpec.mask_from_vector and meth:HistoSpec.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.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
edges

The histogram bin edges.

Type:nump.ndarray
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.Volume(pair, result)[source]

Bases: object

This class represents a volume. This is the superclass of OptimalVolume, StableVolume and StableSubvolume.

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 {0, 1}],
  • ssimplex: list of string
birth_time()[source]
Returns:The birth time.
Return type:float
boundary()[source]
Returns:All cells in the volume optimal cycle.
Return type:list of cells
boundary_points()[source]
Returns:All vertices in the volume optimal cycle.
Return type:list of point
boundary_points_symbols()[source]
Returns:All vertices in the volume optimal cycle in the form of the symbolic representation.
Return type:list of string
boundary_symbols()[source]
Returns:All simplices in the volume optimal cycle in the form of the symbolic representation.
Return type:list of ssimplex
cells()[source]
Returns:All cells in volume optimal cycles.
Return type:list of cell
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_position()[source]
Returns:The death simplex.
Return type:simplex
death_time()[source]
Returns:The death time.
Return type:float
lifetime()[source]
Returns:The lifetime of the pair.
Return type:float
points()[source]
Returns:All vertices in the optimal volume.
Return type:list of point
points_symbols()[source]
Returns:All vertices in the optimal volume in the form of the symbolic representation.
Return type:list of string
simplices()[source]
Returns:All simplices in volume optimal cycles.
Return type:list of simplex
simplices_symbols()[source]
Returns:All simplices in volume optimal cycles in the form of the symbolic representation.
Return type:list of ssimplex
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_plotly3d(color='green', width=1, name='')

Constructs a plotly’s trace object to visualize the optimal volume

Parameters:
  • color (string or None) – The name of the color
  • width (int) – The width of the line
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Scatter3d

to_plotly3d_mesh(color='green', name='')[source]

Constructs a plotly’s trace object to visualize the face of an optimal volume

Parameters:
  • color (string or None) – The name of the color
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Mesh3d

to_plotly3d_trace(color='green', width=1, name='')[source]

Constructs a plotly’s trace object to visualize the optimal volume

Parameters:
  • color (string or None) – The name of the color
  • width (int) – The width of the line
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Scatter3d

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
volume_simplices_symbols()
Returns:All simplices in volume optimal cycles in the form of the symbolic representation.
Return type:list of ssimplex
class homcloud.interface.OptimalVolume(pair, result)[source]

Bases: homcloud.interface.optimal_volume.Volume

This class represents an optimal volume.

birth_pos()

The alias of birth_position().

birth_position()[source]
Returns:The birth simplex.
Return type:simplex
stable_subvolume(threshold, solver=None, solver_options=[])[source]

Returns the stable subvolume of the optimal volume.

Parameters:threshold (float) – The noise bandwidth.
Returns:The stable subvolume.
Return type:StableSubvolume
tightened_subvolume(threshold, solver=None, solver_options=[])

Returns the stable subvolume of the optimal volume.

Parameters:threshold (float) – The noise bandwidth.
Returns:The stable subvolume.
Return type:StableSubvolume
class homcloud.interface.EigenVolume(pair, result, threshold)[source]

Bases: homcloud.interface.optimal_volume.Volume

This class represents an “eigenvolume”. It is the superclass of StableVolume and StableSubvolume.

threshold

The threshold used for the computation of the eigenvolume.

Type:float
class homcloud.interface.StableVolume(pair, result, threshold)[source]

Bases: homcloud.interface.optimal_volume.EigenVolume

This class represents a stable volume.

The instance is given by Pair.stable_volume().

class homcloud.interface.StableSubvolume(pair, result, threshold)[source]

Bases: homcloud.interface.optimal_volume.EigenVolume

This class represents a stable subvolume.

The instance is given by OptimalVolume.stable_subvolume().

class homcloud.interface.PHTrees(orig, spatial_searcher)[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 PDList.from_alpha_filtration() with save_boundary_map=True and save_phtrees=True arguments.

Example

>>> import homcloud.interface as hc
>>> pointcloud = hc.example_data("tetrahedron")
>>> # Compute PDs and PHTrees
>>> pdlist = hc.PDList.from_alpha_filtration(pointcloud, save_boundary_map=True, save_phtrees=True)
>>> # Load phtrees
>>> phtrees = pdlist.dth_diagram(2).load_phtrees()
>>> # Query the node whose birth-death pair is nearest to (19, 21).
>>> node = phtrees.pair_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(birth_index, death_index, parent_death, trees=None)[source]

Bases: homcloud.interface.phtrees.Volume, homcloud.phtrees.Node

The class represents a tree node of PHTrees.

living_descendants()[source]
Returns:All descendant nodes with positive lifetime
Return type:list of PHTrees.Node
stable_volume(epsilon)[source]
Parameters:epsilon (float) – Duration noise strength
Returns:The stable volume
Return type:PHTrees.StableVolume
class StableVolume(root, children)[source]

Bases: homcloud.interface.phtrees.Volume, homcloud.phtrees.StableVolume

The class represents a stable volume in PHTrees.

class Volume[source]

Bases: object

The superclass of PHTrees.Node and PHTrees.StableVolume.

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
simplices()
Returns:The simplices in the optimal volume.
Return type:list of list of list of float, a.k.a list of simplex
boundary()
Returns:Points in the volume optimal cycle.
Return type:list of list of float, a.k.a. list of points
birth_simplex()

Returns the birth simplex.

death_simplex()

Returns the death simplex.

ancestors()
Returns:The ancestors of the tree node include itself.
Return type:list of PHTrees.Node
boundary_points()[source]
Returns:Points in the volume optimal cycle.
Return type:list of list of float, a.k.a list of points
boundary_points_symbols()[source]
Returns:All vertices in the volume optimal cycle in the form of the symbolic representation.
Return type:list of string
boundary_symbols()[source]
Returns:All simplices in the volume optimal cycle in the form of the symbolic representation.
Return type:list of list of string
living()[source]
Returns:True if the birth time and death time of the node are different.
Return type:bool
points()[source]
Returns:Points in the optimal volume.
Return type:list of list of float, a.k.a list of points
points_symbols()[source]
Returns:All vertices in the optimal volume in the form of the symbolic representation.
Return type:list of string
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_plotly3d(color='green', width=1, name='')

Constructs a plotly’s trace object to visualize the optimal volume

Parameters:
  • color (string or None) – The name of the color
  • width (int) – The width of the line
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Scatter3d

to_plotly3d_mesh(color='green', name='')[source]

Constructs a plotly’s trace object to visualize the face of an optimal volume

Parameters:
  • color (string or None) – The name of the color
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Mesh3d

to_plotly3d_trace(color='green', width=1, name='')[source]

Constructs a plotly’s trace object to visualize the optimal volume

Parameters:
  • color (string or None) – The name of the color
  • width (int) – The width of the line
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Scatter3d

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
volume_simplices_symbols()[source]
Returns:All simplices in volume optimal cycles in the form of the symbolic representation.
Return type:list of list of string
all_nodes

Return all nodes.

Returns:The nodes.
Return type:list of PHTrees.Node
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

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.BitmapPHTrees(treedict, is_superlevel)[source]

Bases: object

This class represents PH trees computed from a bitmap filtration.

You can create an instance of this class by PDList.bitmap_phtrees().

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_pixel()

Returns the birth pixel.

Returns:The coordinate of the birth pixel.
Return type:list of int
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_pixel()

Returns the death pixel.

Returns:The coordinate of the death pixel.
Return type:list of int
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
stable_volume(epsilon)[source]

Returns the stable volume of the optimal volume.

Parameters:epsilon (float) – Duration noise strength
Returns:The stable volume
Return type:BitmapPHTrees.StableVolume
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_plotly3d(color=None, name='')

Constructs a plotly’s trace object to visualize the volume

Parameters:
  • color (string or None) – The name of the color
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Mesh3d

to_plotly3d_trace(color=None, name='')[source]

Constructs a plotly’s trace object to visualize the volume

Parameters:
  • color (string or None) – The name of the color
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Mesh3d

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
class StableVolume(node, epsilon)[source]

Bases: object

This class represents a stable volume in BitmapPHTrees.

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_plotly3d(color=None, name='')

Constructs a plotly’s trace object to visualize the stable volume

Parameters:
  • color (string or None) – The name of the color
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Mesh3d

to_plotly3d_trace(color=None, name='')[source]

Constructs a plotly’s trace object to visualize the stable volume

Parameters:
  • color (string or None) – The name of the color
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Mesh3d

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 pixels of the stable volume.

Returns:The coordinates of all pixels.
Return type:set of tuple(int,..)
degree()[source]
Returns:The degree of the persistent homology.
Return type:int
static for_bitmap_levelset(array, mode='sublevel', save_to=None)[source]

Computes a PH trees from 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 0th and (n-1)st PDs with PH-trees.

Return type:

PDList

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

static to_paraview_node_from_nodes(nodes, gui_name=None)[source]

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

Parameters:
  • nodes (list of BitmapPHTrees.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

static to_pvnode_from_nodes(nodes, gui_name=None)

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

Parameters:
  • nodes (list of BitmapPHTrees.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

homcloud.interface.distance_transform(pict, signed=False, metric='manhattan', periodicity=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”
  • periodicity (None or list of bool) – Periodic boundary condition
  • obstacle (None or numpy.ndarray) – 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.
class homcloud.interface.BitmapOptimal1Cycle(orig)[source]

Bases: object

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

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_plotly3d(color=None, name='')

Constructs a plotly’s trace object to visualize the optimal 1-cycle

Parameters:
  • color (string or None) – The name of the color
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Mesh3d

to_plotly3d_trace(color=None, name='')[source]

Constructs a plotly’s trace object to visualize the optimal 1-cycle

Parameters:
  • color (string or None) – The name of the color
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Mesh3d

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.GraphOptimal1Cycle(pair, path_vertices)[source]

Bases: object

The class represents an optimal (not volume-optimal) 1-cycle computed from graph information.

You can aquaire an optimal one cycle by Pair.optimal_1_cycle().

Examples

>>> import numpy as np
>>> import homcloud.interface as hc
>>> distance_matrix = np.loadtxt("distance_matrix.txt")
>>> pdlist = hc.PDList.from_rips_filtration(distance_matrix, maxdim=1, save_graph=True)
>>> pd1 = pdlist.dth_diagram(1)
>>> pair = pd1.nearest_pair_to(1.2, 1.5)
>>> optimal_1_cycle = pair.optimal_1_cycle()
>>> optimal_1_cycle.boundary_points()
=> [0, 2, 41, 17, 9]
birth_time()[source]

Returns the birth time of the pair.

Returns:The birth time
Return type:float
boundary_points()[source]

Returns the points on the 1-cycle.

Returns:The list of points on the cycle. Each point is represented by a number, which is assigned in 0-origin.
Return type:list of int
death_time()[source]

Returns the death time of the pair.

Returns:The death time
Return type:float
class homcloud.interface.Optimal1Cycle(pair, path)[source]

Bases: object

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

This class is available only for alpha, cubical, rips, and abstract filtration with boundary map information.

You can aquaire an optimal one cycle by Pair.optimal_1_cycle().

birth_position()[source]

Birth position of the birth-death pair

birth_time()[source]

Returns the birth time of the pair.

Returns:The birth time
Return type:float
boundary_points()[source]
Returns:All vertices in the optimal 1-cycle.
Return type:list of point
boundary_points_symbols()[source]
Returns:All vertices in the optimal 1-cycle in the form of the symbolic representation.
Return type:list of string
death_time()[source]

Returns the death time of the pair.

Returns:The death time
Return type:float
path()[source]
Returns:All edges in the optimal 1-cycle.
Return type:list of cell
path_symbols()[source]
Returns:All edges in the optimal 1-cycle in the form of the symbolic representation.
Return type:list of ssimplex
to_plotly3d(color=None, width=1, name='')

Constructs a plotly’s trace object to visualize the optimal 1-cycle

Parameters:
  • color (string or None) – The name of the color
  • width (int) – The width of the lines
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Scatter3d

to_plotly3d_trace(color=None, width=1, name='')[source]

Constructs a plotly’s trace object to visualize the optimal 1-cycle

Parameters:
  • color (string or None) – The name of the color
  • width (int) – The width of the lines
  • name (string) – The name of the object
Returns:

Plotly’s trace object

Return type:

plotly.graph_objects.Scatter3d

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.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.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.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.
homcloud.interface.distance.bottleneck(pd1, pd2, delta=1e-06)[source]

Compute the bottleneck distance between two diagrams.

The parameter delta determines the acceptable relative error. If delta is zero, the return value is exact but slower. If delta is positive, the return value is not exact but faster.

Notes

This function uses hera library <https://bitbucket.org/grey_narn/hera>. See the following paper for theoretical details: Michael Kerber, Dmitriy Morozov, and Arnur Nigmetov, “Geometry Helps to Compare Persistence Diagrams.”, Journal of Experimental Algorithmics, vol. 22, 2017, pp. 1–20. (conference version: ALENEX 2016).

Parameters:
  • pd1 (PD) – A persistence diagram
  • pd2 (PD) – Another persistence diagram
  • delta (float) – Acceptable relative error, must be zero or positive
Returns:

the bottleneck distance betweeen two diagrams

Return type:

float

homcloud.interface.distance.wasserstein(pd1, pd2, power=2, internal_p=inf, delta=1e-06)[source]

Compute the Wasserstein distance between two diagrams.

Example

>>> import homcloud.interface as hc
>>> hc.distance.wasserstein(pd1, pd2, delta=0.01)
Returns 2-Wasserstein distance with relative error <= 0.01

Notes

This function uses hera library <https://bitbucket.org/grey_narn/hera>. See the following paper for theoretical details: Michael Kerber, Dmitriy Morozov, and Arnur Nigmetov, “Geometry Helps to Compare Persistence Diagrams.”, Journal of Experimental Algorithmics, vol. 22, 2017, pp. 1–20. (conference version: ALENEX 2016).

Parameters:
  • pd1 (PD) – A persistence diagram
  • pd2 (PD) – Another persistence diagram
  • power (float) – Wasserstein degree, must be larger than or equal to 1
  • internal_p (float) – The internal norm in Wasserstein distance, must be larger than or equal to 1 including infinity
  • delta (float) – Acceptable relative error, must be zero or positive
Returns:

the Wasserstein distance betweeen two diagrams

Return type:

float