File size: 6,051 Bytes
9f50319 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | import numpy as np
from scipy.sparse.csgraph import connected_components
import gudhi as gd
from persim import wasserstein
import bisect
def count_connected_components(edge_index, num_nodes):
"""Count the number of connected components in a graph"""
# Create adjacency matrix
adj_matrix = np.zeros((num_nodes, num_nodes))
for i in range(edge_index.shape[1]):
src, dst = edge_index[0, i], edge_index[1, i]
adj_matrix[src, dst] = 1
adj_matrix[dst, src] = 1
# Calculate connected components using scipy
n_components, _ = connected_components(adj_matrix)
return n_components
def Filtration(edge_index, edge_attr,filt,filt_value):
def filt_edge(edges,filt_value):
upper_bounds = filt_value
filted_edges = []
for edge in edges:
src, tgt, w = edge
index = bisect.bisect_left(upper_bounds, w)
if index < len(upper_bounds):
assigned_upper = upper_bounds[index]
else:
assigned_upper = upper_bounds[-1]
filted_edges.append((src, tgt, assigned_upper))
return filted_edges
edge_index = np.array(edge_index).reshape(2, -1)
original_edges = []
for i in range(edge_index.shape[1]):
source = edge_index[0, i].item()
target = edge_index[1, i].item()
weight = edge_attr[i].item()
original_edges.append((source, target, weight))
if filt:
original_edges = filt_edge(original_edges,filt_value)
sorted_edges = sorted(original_edges, key=lambda x: x[2])
simplices = gd.SimplexTree()
for u, v, weight in sorted_edges:
simplices.insert([u, v], filtration=weight)
simplices.expansion(2)
filtration = simplices.get_filtration()
simplex_list = []
for simplex in filtration:
simplex_list.append(simplex)
simplices.persistence()
barcode = []
for i in range(2):
intervals = simplices.persistence_intervals_in_dimension(i)
barcode.append(intervals)
vr_e_pd = {}
for dim, intervals in enumerate(barcode):
if intervals.size > 0 and dim<=2:
intervals = intervals.tolist()
intervals.sort(key=lambda x: x[0])
vr_e_pd[f'{dim}dim'] = intervals
else:
vr_e_pd[f'{dim}dim'] = []
return sorted_edges, simplex_list, vr_e_pd
def add_vr_ORI(dataset,filt,filt_value=None):
for i in range(len(dataset)):
edge_index = dataset[i]['edge_index']
edge_attr = dataset[i]['edge_attr']
sorted_edges,simplex_list, vr_e_pd = Filtration(edge_index, edge_attr,filt,filt_value)
for dim in vr_e_pd:
vr_e_pd[dim].sort(key=lambda interval: interval[0])
# dataset[i].sorted_edges = sorted_edges
# dataset[i].simplex = simplex_list
# dataset[i].vr_e_pd = vr_e_pd
if filt:
dataset[i]['selected_vr_e_pd'] = vr_e_pd
else:
dataset[i]['vr_e_pd'] = vr_e_pd
def PD_to_diagram(PD):
"""
Convert persistence diagram dictionary to numpy array format.
"""
diagram = []
for dim, intervals in PD.items():
dim_int = int(dim[0])
for interval in intervals:
birth, death = interval
diagram.append([birth, death, dim_int])
return np.array(diagram)
def compute_wasserstein_distance(PD1, PD2):
"""
Compute Wasserstein distance between two persistence diagrams.
"""
diagram1 = PD_to_diagram(PD1)
diagram2 = PD_to_diagram(PD2)
# Handle infinite death times
diagram1[~np.isfinite(diagram1[:, 1]), 1] = 1.1
diagram2[~np.isfinite(diagram2[:, 1]), 1] = 1.1
return wasserstein(diagram1, diagram2)
def check_graph_group(graphs, method='weight', pre_calculate=True, filt_value=None):
"""
Check if four graphs satisfy the separation condition:
1. Both distances within same class are smaller than all four distances between different classes
2. Four graphs must be arranged in [1,1,-1,-1] order
Args:
graphs: List of 4 graphs arranged in [1,1,-1,-1] order
method: Persistent homology calculation method
pre_calculate: Whether persistence diagrams are pre-calculated
filt_value: Filtration value for calculation
Returns:
tuple: (bool, list) - Whether separation condition is satisfied and list of distances
"""
if len(graphs) != 4:
raise ValueError("Must provide exactly 4 graphs")
# Verify graph label order
if not (graphs[0]['y'] == graphs[1]['y'] and graphs[2]['y'] == graphs[3]['y'] and graphs[0]['y'] != graphs[2]['y']):
raise ValueError("Graphs must be ordered as [1,1,-1,-1]")
if not pre_calculate:
add_vr_ORI(graphs, filt=True, filt_value=filt_value)
# Calculate distances between all graph pairs
distances = []
for i in range(4):
for j in range(i+1, 4):
if method == 'weight':
if pre_calculate:
dist = compute_wasserstein_distance(graphs[i]['vr_e_pd'], graphs[j]['vr_e_pd'])
else:
dist = compute_wasserstein_distance(graphs[i]['selected_vr_e_pd'], graphs[j]['selected_vr_e_pd'])
else:
dist = compute_wasserstein_distance(
getattr(graphs[i], f'vr_{method}_pd'),
getattr(graphs[j], f'vr_{method}_pd')
)
distances.append((i, j, dist))
# Distances within same class
same_class_distances = [dist for i, j, dist in distances
if (i < 2 and j < 2) or (i >= 2 and j >= 2)]
# Distances between different classes
diff_class_distances = [dist for i, j, dist in distances
if (i < 2 and j >= 2) or (i >= 2 and j < 2)]
max_same = max(same_class_distances)
min_diff = min(diff_class_distances)
return max_same < min_diff, distances |