0
# Cubical Complexes
1
2
Specialized functionality for working with cubical complexes, particularly useful for image analysis, structured grid data, and applications where the data naturally lives on a regular lattice structure.
3
4
## Capabilities
5
6
### CubicalComplex
7
8
Main class for constructing and analyzing cubical complexes from bitmap/image data with support for various boundary conditions.
9
10
```python { .api }
11
class CubicalComplex:
12
def __init__(self, dimensions, top_dimensional_cells, periodic_dimensions=None):
13
"""
14
Initialize cubical complex from grid data.
15
16
Parameters:
17
- dimensions: List of dimensions for each axis
18
- top_dimensional_cells: Flattened array of cell values
19
- periodic_dimensions: List of dimensions with periodic boundary conditions
20
"""
21
22
def persistence(self, homology_coeff_field: int = 11, min_persistence: float = 0.0):
23
"""
24
Compute persistent homology of the cubical complex.
25
26
Parameters:
27
- homology_coeff_field: Coefficient field for homology computation
28
- min_persistence: Minimum persistence value to return
29
30
Returns:
31
list: Persistence pairs as (dimension, (birth, death)) tuples
32
"""
33
34
def cofaces_of_persistence_pairs(self):
35
"""
36
Get representative cofaces for persistence pairs.
37
38
Returns:
39
list: Coface representatives for each persistence pair
40
"""
41
42
def vertices_of_persistence_pairs(self):
43
"""
44
Get vertex representatives for persistence pairs.
45
46
Returns:
47
list: Vertex representatives for each persistence pair
48
"""
49
50
def num_simplices(self):
51
"""
52
Get total number of cubes in the complex.
53
54
Returns:
55
int: Number of cubes
56
"""
57
58
def dimension(self):
59
"""
60
Get dimension of the cubical complex.
61
62
Returns:
63
int: Complex dimension
64
"""
65
66
def betti_numbers(self):
67
"""
68
Compute Betti numbers.
69
70
Returns:
71
list: Betti numbers for each dimension
72
"""
73
74
def persistent_betti_numbers(self, from_value: float, to_value: float):
75
"""
76
Compute persistent Betti numbers within filtration range.
77
78
Parameters:
79
- from_value: Start of filtration range
80
- to_value: End of filtration range
81
82
Returns:
83
list: Persistent Betti numbers
84
"""
85
```
86
87
### PeriodicCubicalComplex
88
89
Cubical complexes with periodic boundary conditions, useful for analyzing data on tori and other periodic domains.
90
91
```python { .api }
92
class PeriodicCubicalComplex:
93
def __init__(self, dimensions, top_dimensional_cells):
94
"""
95
Initialize periodic cubical complex.
96
97
Parameters:
98
- dimensions: List of dimensions for each axis
99
- top_dimensional_cells: Flattened array of cell values
100
"""
101
102
def persistence(self, homology_coeff_field: int = 11, min_persistence: float = 0.0):
103
"""
104
Compute persistent homology with periodic boundary conditions.
105
106
Parameters:
107
- homology_coeff_field: Coefficient field for homology computation
108
- min_persistence: Minimum persistence value to return
109
110
Returns:
111
list: Persistence pairs
112
"""
113
114
def cofaces_of_persistence_pairs(self):
115
"""Get coface representatives for persistence pairs."""
116
117
def vertices_of_persistence_pairs(self):
118
"""Get vertex representatives for persistence pairs."""
119
120
def num_simplices(self):
121
"""Get number of cubes in the complex."""
122
123
def dimension(self):
124
"""Get complex dimension."""
125
```
126
127
### File I/O for Cubical Complexes
128
129
Utilities for reading and writing cubical complex data in various formats.
130
131
```python { .api }
132
def read_cubical_complex_from_perseus_file(filename: str):
133
"""
134
Read cubical complex from Perseus file format.
135
136
Parameters:
137
- filename: Path to Perseus file
138
139
Returns:
140
CubicalComplex: Loaded cubical complex
141
"""
142
143
def write_cubical_complex_to_perseus_file(complex, filename: str):
144
"""
145
Write cubical complex to Perseus file format.
146
147
Parameters:
148
- complex: CubicalComplex to save
149
- filename: Output file path
150
"""
151
```
152
153
## Usage Examples
154
155
### Image Analysis with Cubical Complexes
156
157
```python
158
import gudhi
159
import numpy as np
160
from PIL import Image
161
162
# Load and process image
163
img = Image.open('example.png').convert('L') # Convert to grayscale
164
img_array = np.array(img)
165
166
# Create cubical complex from image
167
dimensions = list(img_array.shape)
168
top_cells = img_array.flatten().astype(float)
169
170
cubical_complex = gudhi.CubicalComplex(
171
dimensions=dimensions,
172
top_dimensional_cells=top_cells
173
)
174
175
# Compute persistence
176
persistence = cubical_complex.persistence()
177
178
# Visualize results
179
gudhi.plot_persistence_diagram(persistence)
180
```
181
182
### 3D Volume Analysis
183
184
```python
185
import gudhi
186
import numpy as np
187
188
# Create 3D volume data (e.g., from medical imaging)
189
volume = np.random.random((50, 50, 50)) # Example random volume
190
191
# Create 3D cubical complex
192
dimensions = [50, 50, 50]
193
top_cells = volume.flatten()
194
195
cubical_complex = gudhi.CubicalComplex(
196
dimensions=dimensions,
197
top_dimensional_cells=top_cells
198
)
199
200
# Compute persistence
201
persistence = cubical_complex.persistence()
202
203
# Get representative cofaces
204
cofaces = cubical_complex.cofaces_of_persistence_pairs()
205
206
print(f"Found {len(persistence)} persistence pairs")
207
print(f"Complex dimension: {cubical_complex.dimension()}")
208
print(f"Number of cubes: {cubical_complex.num_simplices()}")
209
```
210
211
### Periodic Boundary Conditions
212
213
```python
214
import gudhi
215
import numpy as np
216
217
# Create data with periodic structure (e.g., wrapping texture)
218
size = 64
219
data = np.sin(np.linspace(0, 4*np.pi, size))
220
data_2d = np.outer(data, data) # Create 2D periodic pattern
221
222
# Analyze with periodic cubical complex
223
periodic_complex = gudhi.PeriodicCubicalComplex(
224
dimensions=[size, size],
225
top_dimensional_cells=data_2d.flatten()
226
)
227
228
# Compute persistence with periodic boundaries
229
periodic_persistence = periodic_complex.persistence()
230
231
# Compare with non-periodic analysis
232
regular_complex = gudhi.CubicalComplex(
233
dimensions=[size, size],
234
top_dimensional_cells=data_2d.flatten()
235
)
236
regular_persistence = regular_complex.persistence()
237
238
print(f"Periodic persistence pairs: {len(periodic_persistence)}")
239
print(f"Regular persistence pairs: {len(regular_persistence)}")
240
```
241
242
### Multi-scale Image Filtering
243
244
```python
245
import gudhi
246
import numpy as np
247
from scipy import ndimage
248
249
# Load image and create multi-scale representation
250
img = np.random.random((100, 100)) # Example image
251
252
# Apply Gaussian filtering at different scales
253
scales = [1.0, 2.0, 4.0, 8.0]
254
persistence_at_scales = []
255
256
for scale in scales:
257
# Filter image
258
filtered_img = ndimage.gaussian_filter(img, sigma=scale)
259
260
# Create cubical complex
261
cubical = gudhi.CubicalComplex(
262
dimensions=list(filtered_img.shape),
263
top_dimensional_cells=filtered_img.flatten()
264
)
265
266
# Compute persistence
267
persistence = cubical.persistence()
268
persistence_at_scales.append(persistence)
269
270
print(f"Scale {scale}: {len(persistence)} persistence pairs")
271
272
# Analyze how persistence changes across scales
273
for i, (scale, pers) in enumerate(zip(scales, persistence_at_scales)):
274
# Extract 1D persistence intervals
275
intervals_1d = [interval for dim, interval in pers if dim == 1]
276
if intervals_1d:
277
avg_persistence = np.mean([death - birth for birth, death in intervals_1d if death != float('inf')])
278
print(f"Scale {scale}: Average 1D persistence = {avg_persistence:.3f}")
279
```