Download evaluate_code/ph_utils.py from Antislab/LLM4PH: direct link, hf CLI and curl.
- Browser
- Download file 6.05 kB
-
https://huggingface.co/datasets/Antislab/LLM4PH/resolve/main/evaluate_code/ph_utils.py
- Command line
-
hf download hf://datasets/Antislab/LLM4PH/evaluate_code/ph_utils.py
-
curl -L -o ph_utils.py https://huggingface.co/datasets/Antislab/LLM4PH/resolve/main/evaluate_code/ph_utils.py
6.05 kB
| 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 |