from typing import Tuple, Dict from evaluate_code.ph_utils import count_connected_components from evaluate_code.ph_utils import check_graph_group import statistics import numpy as np import json class Evaluator: def __init__(self, task_name): self.task_name = task_name def evaluate(self, graph_data, extracted_answers): """ Call the corresponding evaluation function based on the task type Args: graph_data: List of graph data objects extracted_answers: List of dicts with number_of_features task_type: Task type Returns: accuracy: accuracy evaluation_results: dict containing detailed evaluation results and statistics """ task_evaluators = { "S_0D": self.evaluate_S_0D, "S_1D": self.evaluate_S_1D, "S_Modification": self.evaluate_S_Modification, "M_Merge": self.evaluate_M_Merge, "M_Birth": self.evaluate_M_Birth, "M_Filtration": self.evaluate_M_Filtration, "H_Selection": self.evaluate_H_Selection, "H_Generation": self.evaluate_H_Generation, "R_Selection": self.evaluate_R_Selection, "R_Generation": self.evaluate_R_Generation, "R_Classification": self.evaluate_R_Classification, } if self.task_name not in task_evaluators: raise ValueError(f"Unsupported task type: {self.task_name}") return task_evaluators[self.task_name](graph_data, extracted_answers) def evaluate_S_0D(self, graph_data, extracted_answers): """ Evaluate the accuracy of the structure_0dim_identification task Args: graph_data: List of graph data objects extracted_answers: List of dicts with number_of_features Returns: accuracy: accuracy evaluation_results: dict containing detailed evaluation results and statistics """ correct_count = 0 total_count = len(extracted_answers) evaluation_results = [] for i, answer in enumerate(extracted_answers): if i >= len(graph_data): break correct_answer = graph_data[i]["num_components"] predicted_answer = answer.get("connected_components") is_correct = predicted_answer == correct_answer if is_correct: correct_count += 1 evaluation_result = { "is_correct": is_correct, "predicted_answer": predicted_answer, "correct_answer": correct_answer } evaluation_results.append(evaluation_result) accuracy = correct_count / total_count if total_count > 0 else 0 stats = { "total_samples": total_count, "correct_count": correct_count, "wrong_count": total_count - correct_count, "accuracy": accuracy } return accuracy, { "statistics": stats, "detailed_results": evaluation_results } def evaluate_S_1D(self, graph_data, extracted_answers): """ Evaluate the accuracy of the structure_1dim_identification task, including two sets of metrics: 1. Whether the existence of 1-dimensional features is correctly judged (through the has_feature field) 2. For graphs with 1-dimensional features, whether the barcodes match completely Args: graph_data: List of graph data objects extracted_answers: List of dicts with has_feature and persistence_pairs Returns: accuracy: accuracy of existence judgment evaluation_results: dict containing detailed evaluation results and statistics """ correct_count = 0 total_count = len(extracted_answers) evaluation_results = [] for i, answer in enumerate(extracted_answers): if i >= len(graph_data): break correct_answer = graph_data[i]["num_holes"] predicted_answer = answer.get("cycle_holes") if predicted_answer is None: evaluation_results.append({ "index": i, "correct": correct_answer, "predicted": None, "match": False, "error": "Missing 'cycle_holes'" }) continue is_correct = predicted_answer == correct_answer if is_correct: correct_count += 1 evaluation_result = { "is_correct": is_correct, "predicted_answer": predicted_answer, "correct_answer": correct_answer } evaluation_results.append(evaluation_result) accuracy = correct_count / total_count if total_count > 0 else 0 stats = { "total_samples": total_count, "correct_count": correct_count, "wrong_count": total_count - correct_count, "accuracy": accuracy } return accuracy, { "statistics": stats, "detailed_results": evaluation_results } def evaluate_S_Modification(self, graph_data, extracted_answers): """ Evaluate graph_0dim_modification accuracy Args: graph_data: List of graph data objects extracted_answers: List of dicts with edge_to_add Returns: accuracy: accuracy evaluation_results: dict containing detailed evaluation results and statistics """ correct_count = 0 total_count = len(graph_data) evaluation_results = [] for i, (graph, answer) in enumerate(zip(graph_data, extracted_answers)): # Check answer format if "error" in answer: evaluation_results.append({ "is_correct": False, "error": answer["error"] }) continue if "edge_to_add" not in answer: evaluation_results.append({ "is_correct": False, "error": "Missing edge_to_add in answer" }) continue # Get edge to add edge_to_add = answer["edge_to_add"] if len(edge_to_add) != 2: evaluation_results.append({ "is_correct": False, "error": f"Invalid edge format: {edge_to_add}" }) continue # Get original edge index and node count original_edge_index = graph["edge_index"] # Shape [2,N] num_nodes = graph["num_nodes"] # Ensure original_edge_index is 2D array if len(original_edge_index.shape) == 1: original_edge_index = original_edge_index.reshape(2, -1) # Validate node index range if edge_to_add[0] >= num_nodes or edge_to_add[1] >= num_nodes: evaluation_results.append({ "is_correct": False, "error": f"Node indices out of range: {edge_to_add}, max index is {num_nodes-1}" }) continue # Calculate original number of connected components original_components = graph["num_components"] # Add new edge, maintaining [2,N] shape new_edge = np.array([[edge_to_add[0]], [edge_to_add[1]]], dtype=np.int64) new_edge_index = np.concatenate([original_edge_index, new_edge], axis=1) # Calculate new number of connected components new_components = count_connected_components(new_edge_index, num_nodes) # Check if correct (number of connected components should decrease) is_correct = new_components < original_components if is_correct: correct_count += 1 evaluation_results.append({ "is_correct": is_correct, "edge_added": edge_to_add, "original_components": original_components, "new_components": new_components }) # Calculate accuracy accuracy = correct_count / total_count if total_count > 0 else 0 # Add statistics stats = { "total_samples": total_count, "correct_count": correct_count, "wrong_count": total_count - correct_count, "accuracy": accuracy } return accuracy, { "statistics": stats, "detailed_results": evaluation_results } def evaluate_filtration_edge_construction(self, graph_data, extracted_answers): """ Evaluate filtration edge construction accuracy Args: graph_data: List of graph data objects extracted_answers: List of dicts with sorted_edges Returns: accuracy: accuracy evaluation_results: dict containing detailed evaluation results and statistics """ correct_count = 0 total_count = len(extracted_answers) evaluation_results = [] for i, answer in enumerate(extracted_answers): if i >= len(graph_data): break # get correct answer (sorted_edges) correct_edges = graph_data[i]["sorted_edges"] # get predicted answer (filtration dictionary) predicted_filtration = answer["filtration"] # convert predicted filtration to edge list format predicted_edges = [] for value, edges in predicted_filtration.items(): for u, v in edges: predicted_edges.append((u, v, float(value))) # sort edges by weight (ascending) predicted_edges.sort(key=lambda x: x[2]) # check if correct is_correct = len(predicted_edges) == len(correct_edges) if is_correct: for pred, corr in zip(predicted_edges, correct_edges): if pred != corr: is_correct = False break if is_correct: correct_count += 1 # record detailed evaluation results evaluation_result = { "is_correct": is_correct, "predicted_edges": predicted_edges, "correct_edges": correct_edges, "edge_count_match": len(predicted_edges) == len(correct_edges), "edge_order_match": is_correct } evaluation_results.append(evaluation_result) # calculate accuracy accuracy = correct_count / total_count if total_count > 0 else 0 # prepare statistics stats = { "total_samples": total_count, "correct_count": correct_count, "wrong_count": total_count - correct_count, "accuracy": accuracy } return accuracy, { "statistics": stats, "detailed_results": evaluation_results } def evaluate_simplicial_complex_construction(self, graph_data, extracted_answers): """ Evaluate simplicial complex construction accuracy Args: graph_data: List of graph data objects extracted_answers: List of dicts with simplicial_complexes Returns: accuracy: accuracy evaluation_results: dict containing detailed evaluation results and statistics """ correct_count = 0 total_count = len(extracted_answers) evaluation_results = [] for i, answer in enumerate(extracted_answers): if i >= len(graph_data): break # get correct answer (2-dimensional simplices) correct_simplices = {} for simplex, value in graph_data[i]["simplex"]: if len(simplex) == 3: # only process 2-dimensional simplices if value not in correct_simplices: correct_simplices[value] = [] correct_simplices[value].append(sorted(simplex)) # get predicted answer predicted_simplices = answer.get("simplicial_complexes", {}) is_correct = True # check all filtration values all_values = set(list(correct_simplices.keys()) + list(predicted_simplices.keys())) for value in all_values: correct = sorted([sorted(s) for s in correct_simplices.get(value, [])]) predicted = sorted([sorted(s) for s in predicted_simplices.get(value, [])]) if correct != predicted: is_correct = False break if is_correct: correct_count += 1 # record detailed evaluation results evaluation_result = { "is_correct": is_correct, "predicted_simplices": predicted_simplices, "correct_simplices": correct_simplices, "value_match": is_correct } evaluation_results.append(evaluation_result) # calculate accuracy accuracy = correct_count / total_count if total_count > 0 else 0 stats = { "total_samples": total_count, "correct_count": correct_count, "wrong_count": total_count - correct_count, "accuracy": accuracy } return accuracy, { "statistics": stats, "detailed_results": evaluation_results } def evaluate_M_Merge(self, graph_data, extracted_answers): """ Evaluate 0-dimensional persistent homology calculation accuracy Args: graph_data: List of graph data objects extracted_answers: List of dictionaries containing death time of feature Returns: accuracy: accuracy evaluation_results: dict containing detailed evaluation results and statistics """ correct_count = 0 total_count = len(extracted_answers) evaluation_results = [] for i, answer in enumerate(extracted_answers): if i >= len(graph_data): break # get correct answer correct_time = graph_data[i]["death_value"] # get predicted answer if "error" in answer: is_correct = False predicted_time = None else: predicted_time = answer.get("death_time", [None])[0] # Get first value from death_time list is_correct = predicted_time == correct_time if is_correct: correct_count += 1 evaluation_result = { "is_correct": is_correct, "predicted_time": predicted_time, "correct_time": correct_time } evaluation_results.append(evaluation_result) accuracy = correct_count / total_count if total_count > 0 else 0 stats = { "total_samples": total_count, "correct_count": correct_count, "wrong_count": total_count - correct_count, "accuracy": accuracy } return accuracy, { "statistics": stats, "detailed_results": evaluation_results } def evaluate_M_Birth(self, graph_data, extracted_answers): """ Evaluate 1-dimensional persistent homology calculation accuracy Args: graph_data: List of graph data objects extracted_answers: List of dicts with persistent_features Returns: accuracy: accuracy evaluation_results: dict containing detailed evaluation results and statistics """ correct_count = 0 total_count = len(extracted_answers) evaluation_results = [] for i, answer in enumerate(extracted_answers): if i >= len(graph_data): break # get correct answer correct_time = graph_data[i]["birth_value"] # get predicted answer if "error" in answer: is_correct = False predicted_time = None else: predicted_time = answer.get("birth_time", [None])[0] # Get first value from death_time list is_correct = predicted_time == correct_time if is_correct: correct_count += 1 evaluation_result = { "is_correct": is_correct, "predicted_time": predicted_time, "correct_time": correct_time } evaluation_results.append(evaluation_result) accuracy = correct_count / total_count if total_count > 0 else 0 stats = { "total_samples": total_count, "correct_count": correct_count, "wrong_count": total_count - correct_count, "accuracy": accuracy } return accuracy, { "statistics": stats, "detailed_results": evaluation_results } def evaluate_M_Filtration(self, graph_data, extracted_answers): """ Evaluate filtration_features_count accuracy Args: graph_data: List of graph data objects extracted_answers: filtration_features_count number Returns: accuracy: accuracy evaluation_results: dict containing detailed evaluation results and statistics """ correct_count = 0 total_count = len(extracted_answers) evaluation_results = [] for i, answer in enumerate(extracted_answers): if i >= len(graph_data): break # get correct answer correct_n = graph_data[i]["t3_0dim"] # get predicted answer if "error" in answer: is_correct = False predicted_count = None else: predicted_count = answer.get("connected_components", [None])[0] # Get first value from death_time list is_correct = predicted_count == correct_n if is_correct: correct_count += 1 evaluation_result = { "is_correct": is_correct, "predicted_count": predicted_count, "correct_count": correct_n } evaluation_results.append(evaluation_result) accuracy = correct_count / total_count if total_count > 0 else 0 stats = { "total_samples": total_count, "correct_count": correct_count, "wrong_count": total_count - correct_count, "accuracy": accuracy } return accuracy, { "statistics": stats, "detailed_results": evaluation_results } def _check_edge_sorting(self, edge_sorting, graph_data): """Check if edge sorting is correct""" try: if not edge_sorting: return False for i in range(1, len(edge_sorting)): if edge_sorting[i][2] < edge_sorting[i-1][2]: return False return True except: return False def evaluate_H_Selection(self, graph_data, extracted_answers) -> Tuple[float, Dict]: """ Evaluate filtration method selection ranking statistics Args: graph_data: List of graph data objects, where graph_data[2i].better_filter contains correct answer extracted_answers: List of dicts with selected_method Returns: Tuple of (accuracy, detailed results dict) """ detailed_results = [] all_ranks = [] top1_count = 0 top2_count = 0 top3_count = 0 for i, answer in enumerate(extracted_answers): if answer is None or answer.get("selected_method") is None: detailed_results.append({ "reason": "No valid answer extracted" }) continue graph_idx = i if graph_idx >= len(graph_data): break predicted_method = answer["selected_method"] if predicted_method == 'weight': predicted_method = 'e' if predicted_method == "k-shell": predicted_method = "k_shell" dist_features = {'dist_k_shell': graph_data[graph_idx][0]['dist_k_shell'], 'dist_closeness': graph_data[graph_idx][0]['dist_closeness'], 'dist_e': graph_data[graph_idx][0]['dist_e'], 'dist_betweenness': graph_data[graph_idx][0]['dist_betweenness'], 'dist_degree': graph_data[graph_idx][0]['dist_degree'], 'dist_eigenvector': graph_data[graph_idx][0]['dist_eigenvector']} predicted_rank = None current_rank = 1 current_distance = None same_rank_count = 0 for method, distance in dist_features.items(): if current_distance is not None and distance != current_distance: current_rank += same_rank_count same_rank_count = 0 current_distance = distance elif current_distance is None: current_distance = distance if method.replace('dist_', '') == predicted_method: predicted_rank = current_rank all_ranks.append(current_rank) if current_rank == 1: top1_count += 1 if current_rank <= 2: top2_count += 1 if current_rank <= 3: top3_count += 1 break same_rank_count += 1 detailed_results.append({ "predicted": predicted_method, "predicted_rank": predicted_rank, "method_rankings": dict(dist_features) }) ranking_stats = { 'mean_rank': sum(all_ranks) / len(all_ranks) if all_ranks else float('inf'), 'min_rank': min(all_ranks) if all_ranks else float('inf'), 'max_rank': max(all_ranks) if all_ranks else float('inf'), 'std_rank': statistics.stdev(all_ranks) if len(all_ranks) > 1 else 0, 'total_predictions': len(all_ranks), 'top1_count': top1_count, 'top2_count': top2_count, 'top3_count': top3_count, 'top1_ratio': top1_count / len(all_ranks) if all_ranks else 0, 'top2_ratio': top2_count / len(all_ranks) if all_ranks else 0, 'top3_ratio': top3_count / len(all_ranks) if all_ranks else 0 } return 0.0, { "statistics": { **ranking_stats }, "detailed_results": detailed_results } def evaluate_H_Generation(self, graph_data, extracted_answers) -> Tuple[float, Dict]: """ 评估过滤序列选择的排名统计 Args: graph_data: List of graph data objects extracted_answers: List of dicts with selected_filtration_values field Returns: Tuple (accuracy, detailed_results_dict) """ total = 0 detailed_results = [] for i, answer in enumerate(extracted_answers): if i >= len(graph_data): break if answer is None or "selected_filtration_values" not in answer: detailed_results.append({ "reason": "No valid answer extracted" }) continue graph1 = graph_data[i][0] selected_values = answer["selected_filtration_values"] if isinstance(selected_values, (int, float)): selected_values = [[selected_values]] elif isinstance(selected_values, (list, tuple)) and not any(isinstance(x, (list, tuple)) for x in selected_values): selected_values = [selected_values] selected_distances = [] selected_ranks = [] for seq in selected_values: if not isinstance(seq, (list, tuple)): seq = [seq] seq_tuple = tuple(sorted(float(x) if isinstance(x, (int, float)) else x for x in seq)) found_match = False current_rank = 1 current_distance = None same_rank_count = 0 sorted_distances = json.loads(graph1['sorted_distances']) for item in sorted_distances: curr_seq = item['nodes'] distance = item['distance'] curr_seq_tuple = tuple(sorted(float(x) if isinstance(x, (int, float)) else x for x in curr_seq)) if current_distance is not None and distance != current_distance: current_rank += same_rank_count same_rank_count = 0 current_distance = distance elif current_distance is None: current_distance = distance if curr_seq_tuple == seq_tuple: selected_distances.append(float(distance)) selected_ranks.append(current_rank) found_match = True break same_rank_count += 1 if not found_match: selected_distances.append(float('inf')) selected_ranks.append(len(graph1.sorted_distances) + 1) rank = sum(selected_ranks) / len(selected_ranks) if selected_ranks else float('inf') in_top3 = sum(1 for rank in selected_ranks if rank <= 3) in_top10 = sum(1 for rank in selected_ranks if rank <= 10) top3 = in_top3 / len(selected_ranks) if selected_ranks else 0 top10 = in_top10 / len(selected_ranks) if selected_ranks else 0 total += 1 detailed_results.append({ "selected_ranks": selected_ranks, "selected_distances": selected_distances, "rank": float(rank), "top3": float(top3), "top10": float(top10), "original_values": selected_values }) valid_results = [r for r in detailed_results if "rank" in r] rank_list = [r["rank"] for r in valid_results] avg_stats = { "mean_rank": float(sum(rank_list) / len(rank_list)) if rank_list else float('inf'), "top3": float(sum(r["top3"] for r in valid_results) / len(valid_results)) if valid_results else 0.0, "top10": float(sum(r["top10"] for r in valid_results) / len(valid_results)) if valid_results else 0.0, "std_rank": float(statistics.stdev(rank_list)) if len(rank_list) > 1 else 0.0 } return 0.0, { "statistics": { "total": int(total), **avg_stats }, "detailed_results": detailed_results } def evaluate_R_Classification(self, graph_data, extracted_answers): correct_count = 0 total_count = len(extracted_answers) evaluation_results = [] ground_truth_sorted = sorted([sorted([1, 2]), sorted([3, 4])]) for i, answer in enumerate(extracted_answers): if "error" in answer or "categories" not in answer: evaluation_results.append({ "index": i, "is_correct": False, "reason": "Missing or invalid 'categories' field", "predicted": None, "expected": ground_truth_sorted }) continue predicted = answer["categories"] try: predicted_sorted = sorted([sorted(group) for group in predicted]) is_correct = predicted_sorted == ground_truth_sorted except Exception as e: is_correct = False predicted_sorted = None if is_correct: correct_count += 1 evaluation_results.append({ "index": i, "is_correct": is_correct, "predicted": predicted, "expected": ground_truth_sorted }) accuracy = correct_count / total_count if total_count > 0 else 0.0 stats = { "total_samples": total_count, "correct_count": correct_count, "wrong_count": total_count - correct_count, "accuracy": accuracy } return accuracy, { "statistics": stats, "detailed_results": evaluation_results } def evaluate_R_Selection(self, graph_data, extracted_answers): """ Evaluate whether the selected filtration method is correct based on method_dict. Args: graph_data: List of graph data entries, where each entry is a tuple (graph, ...) and graph.method_dict is a dict extracted_answers: List of dicts with key 'selected_method' Returns: accuracy: float result_summary: dict with statistics and detailed evaluation results """ correct_count = 0 total_count = len(extracted_answers) evaluation_results = [] for i, answer in enumerate(extracted_answers): if i >= len(graph_data): break method_dict = { 'weight': graph_data[i][0]['method_weight'], 'degree': graph_data[i][0]['method_degree'], 'betweenness': graph_data[i][0]['method_betweenness'], 'k_shell': graph_data[i][0]['method_k_shell'], 'closeness': graph_data[i][0]['method_closeness'], 'eigenvector': graph_data[i][0]['method_eigenvector'] } if "error" in answer or "selected_method" not in answer: evaluation_results.append({ "index": i, "is_correct": False, "predicted_method": answer.get("selected_method", None), "expected_methods": [k for k, v in method_dict.items() if v], "reason": "No valid method extracted" }) continue predicted_method = answer.get("selected_method") if predicted_method not in method_dict: return {"error": f"Invalid method selected: {predicted_method}"} is_correct = bool(method_dict[predicted_method]) if is_correct: correct_count += 1 evaluation_results.append({ "index": i, "is_correct": is_correct, "predicted_method": predicted_method, "expected_methods": [k for k, v in method_dict.items() if v] }) accuracy = correct_count / total_count if total_count > 0 else 0.0 stats = { "total_samples": total_count, "correct_count": correct_count, "wrong_count": total_count - correct_count, "accuracy": accuracy } return accuracy, { "statistics": stats, "detailed_results": evaluation_results } def evaluate_R_Generation(self, graph_data, extracted_answers): """ Evaluate predictions based on filtration_values using check_filt_value(). Args: graph_data: List of graph data objects extracted_answers: List of dicts with key 'filtration_values' Returns: accuracy: float result_summary: dict with statistics and detailed evaluation results """ correct_count = 0 total_count = len(extracted_answers) evaluation_results = [] for i, answer in enumerate(extracted_answers): if i >= len(graph_data): break if "error" in answer or "filtration_values" not in answer: evaluation_results.append({ "index": i, "is_correct": False, "predicted_values": answer.get("filtration_values", None), "reason": "No valid filtration_values extracted" }) continue filtration_values = answer["filtration_values"] is_correct,distances = check_graph_group(graph_data[i], method='weight',pre_calculate=False,filt_value=filtration_values) if is_correct: correct_count += 1 correct = "True" else: correct = "False" evaluation_results.append({ "index": i, "is_correct": correct, "predicted_values": filtration_values, "correct": correct }) accuracy = correct_count / total_count if total_count > 0 else 0.0 stats = { "total_samples": total_count, "correct_count": correct_count, "wrong_count": total_count - correct_count, "accuracy": accuracy } return accuracy, { "statistics": stats, "detailed_results": evaluation_results }