Upload 12 files
Browse files- README.md +78 -0
- config.py +10 -0
- evaluate_code/evaluate.py +951 -0
- evaluate_code/extract.py +633 -0
- evaluate_code/graph_embed.py +583 -0
- evaluate_code/llm_api.py +126 -0
- evaluate_code/llm_evaluator.py +192 -0
- evaluate_code/load_datasets.py +57 -0
- evaluate_code/ph_utils.py +171 -0
- llm4ph.png +3 -0
- main.py +77 -0
- requirements.txt +22 -0
README.md
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLM4PH: Large Language Models as Topological Thinkers
|
| 2 |
+
|
| 3 |
+
This repository contains the benchmark code for our NeurIPS paper: "Large Language Models as Topological Thinkers: A Benchmark on Graph Persistent Homology".
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
LLM4PH is a comprehensive benchmark designed to evaluate the capabilities of Large Language Models (LLMs) in understanding and reasoning about topological concepts, specifically focusing on graph persistent homology.
|
| 8 |
+
|
| 9 |
+
## Dataset
|
| 10 |
+
|
| 11 |
+
The benchmark consists of four difficulty levels of tasks:
|
| 12 |
+
|
| 13 |
+

|
| 14 |
+
|
| 15 |
+
Each level is designed to progressively challenge the model's understanding of topological concepts.
|
| 16 |
+
|
| 17 |
+
## Code Structure
|
| 18 |
+
|
| 19 |
+
The codebase is organized as follows:
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
LLM4PH/
|
| 23 |
+
├── config.py # Configuration settings for tasks and models
|
| 24 |
+
├── main.py # Main entry point for running the benchmark
|
| 25 |
+
├── datasets/ # Dataset files for different difficulty levels
|
| 26 |
+
├── evaluate_code/ # Evaluation scripts and metrics
|
| 27 |
+
├── results/ # Directory for storing evaluation results
|
| 28 |
+
└── .env # Environment variables for API keys (create if needed)
|
| 29 |
+
```
|
| 30 |
+
Key components:
|
| 31 |
+
- `config.py`: Configure task parameters and model settings
|
| 32 |
+
- `main.py`: Run the benchmark with specified configurations
|
| 33 |
+
- `evaluate_code/`: Contains evaluation logic and scoring metrics
|
| 34 |
+
- `datasets/`: Stores the benchmark datasets
|
| 35 |
+
- `results/`: Output directory for evaluation results
|
| 36 |
+
|
| 37 |
+
## Installation
|
| 38 |
+
|
| 39 |
+
Install dependencies:
|
| 40 |
+
```bash
|
| 41 |
+
pip install -r requirements.txt
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
## Configuration
|
| 45 |
+
|
| 46 |
+
The benchmark can be configured through `config.py`:
|
| 47 |
+
|
| 48 |
+
- Task configuration: Set difficulty levels and evaluation parameters
|
| 49 |
+
- Model configuration: Choose between local and API-based models
|
| 50 |
+
|
| 51 |
+
### API Key Setup
|
| 52 |
+
|
| 53 |
+
For closed-source models, create a `.env` file in the root directory:
|
| 54 |
+
|
| 55 |
+
```bash
|
| 56 |
+
touch .env
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
Add your API keys to the `.env` file:
|
| 60 |
+
```
|
| 61 |
+
OPENAI_API_KEY=your_key_here
|
| 62 |
+
ANTHROPIC_API_KEY=your_key_here
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
## Usage
|
| 66 |
+
|
| 67 |
+
1. Configure your desired task and model in `config.py`
|
| 68 |
+
2. Run the benchmark:
|
| 69 |
+
```bash
|
| 70 |
+
python main.py
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
## Citation
|
| 74 |
+
|
| 75 |
+
If you use this benchmark in your research, please cite our paper:
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
```
|
config.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# List of tasks to be processed
|
| 2 |
+
TASKS = [
|
| 3 |
+
"R_Generation",
|
| 4 |
+
# Add more tasks as needed
|
| 5 |
+
]
|
| 6 |
+
|
| 7 |
+
# Model configuration
|
| 8 |
+
MODEL_NAMES = [
|
| 9 |
+
"gpt-4o", # You can change this to other model names if needed
|
| 10 |
+
]
|
evaluate_code/evaluate.py
ADDED
|
@@ -0,0 +1,951 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Tuple, Dict
|
| 2 |
+
from evaluate_code.ph_utils import count_connected_components
|
| 3 |
+
from evaluate_code.ph_utils import check_graph_group
|
| 4 |
+
import statistics
|
| 5 |
+
import numpy as np
|
| 6 |
+
import json
|
| 7 |
+
class Evaluator:
|
| 8 |
+
def __init__(self, task_name):
|
| 9 |
+
self.task_name = task_name
|
| 10 |
+
def evaluate(self, graph_data, extracted_answers):
|
| 11 |
+
"""
|
| 12 |
+
Call the corresponding evaluation function based on the task type
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
graph_data: List of graph data objects
|
| 16 |
+
extracted_answers: List of dicts with number_of_features
|
| 17 |
+
task_type: Task type
|
| 18 |
+
|
| 19 |
+
Returns:
|
| 20 |
+
accuracy: accuracy
|
| 21 |
+
evaluation_results: dict containing detailed evaluation results and statistics
|
| 22 |
+
"""
|
| 23 |
+
task_evaluators = {
|
| 24 |
+
"S_0D": self.evaluate_S_0D,
|
| 25 |
+
"S_1D": self.evaluate_S_1D,
|
| 26 |
+
"S_Modification": self.evaluate_S_Modification,
|
| 27 |
+
"M_Merge": self.evaluate_M_Merge,
|
| 28 |
+
"M_Birth": self.evaluate_M_Birth,
|
| 29 |
+
"M_Filtration": self.evaluate_M_Filtration,
|
| 30 |
+
"H_Selection": self.evaluate_H_Selection,
|
| 31 |
+
"H_Generation": self.evaluate_H_Generation,
|
| 32 |
+
"R_Selection": self.evaluate_R_Selection,
|
| 33 |
+
"R_Generation": self.evaluate_R_Generation,
|
| 34 |
+
"R_Classification": self.evaluate_R_Classification,
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
if self.task_name not in task_evaluators:
|
| 38 |
+
raise ValueError(f"Unsupported task type: {self.task_name}")
|
| 39 |
+
|
| 40 |
+
return task_evaluators[self.task_name](graph_data, extracted_answers)
|
| 41 |
+
|
| 42 |
+
def evaluate_S_0D(self, graph_data, extracted_answers):
|
| 43 |
+
"""
|
| 44 |
+
Evaluate the accuracy of the structure_0dim_identification task
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
graph_data: List of graph data objects
|
| 48 |
+
extracted_answers: List of dicts with number_of_features
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
accuracy: accuracy
|
| 52 |
+
evaluation_results: dict containing detailed evaluation results and statistics
|
| 53 |
+
"""
|
| 54 |
+
correct_count = 0
|
| 55 |
+
total_count = len(extracted_answers)
|
| 56 |
+
evaluation_results = []
|
| 57 |
+
|
| 58 |
+
for i, answer in enumerate(extracted_answers):
|
| 59 |
+
if i >= len(graph_data):
|
| 60 |
+
break
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
correct_answer = graph_data[i]["num_components"]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
predicted_answer = answer.get("connected_components")
|
| 67 |
+
|
| 68 |
+
is_correct = predicted_answer == correct_answer
|
| 69 |
+
if is_correct:
|
| 70 |
+
correct_count += 1
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
evaluation_result = {
|
| 74 |
+
"is_correct": is_correct,
|
| 75 |
+
"predicted_answer": predicted_answer,
|
| 76 |
+
"correct_answer": correct_answer
|
| 77 |
+
}
|
| 78 |
+
evaluation_results.append(evaluation_result)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
accuracy = correct_count / total_count if total_count > 0 else 0
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
stats = {
|
| 85 |
+
"total_samples": total_count,
|
| 86 |
+
"correct_count": correct_count,
|
| 87 |
+
"wrong_count": total_count - correct_count,
|
| 88 |
+
"accuracy": accuracy
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
return accuracy, {
|
| 92 |
+
"statistics": stats,
|
| 93 |
+
"detailed_results": evaluation_results
|
| 94 |
+
}
|
| 95 |
+
def evaluate_S_1D(self, graph_data, extracted_answers):
|
| 96 |
+
"""
|
| 97 |
+
Evaluate the accuracy of the structure_1dim_identification task, including two sets of metrics:
|
| 98 |
+
1. Whether the existence of 1-dimensional features is correctly judged (through the has_feature field)
|
| 99 |
+
2. For graphs with 1-dimensional features, whether the barcodes match completely
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
graph_data: List of graph data objects
|
| 103 |
+
extracted_answers: List of dicts with has_feature and persistence_pairs
|
| 104 |
+
|
| 105 |
+
Returns:
|
| 106 |
+
accuracy: accuracy of existence judgment
|
| 107 |
+
evaluation_results: dict containing detailed evaluation results and statistics
|
| 108 |
+
"""
|
| 109 |
+
correct_count = 0
|
| 110 |
+
total_count = len(extracted_answers)
|
| 111 |
+
evaluation_results = []
|
| 112 |
+
|
| 113 |
+
for i, answer in enumerate(extracted_answers):
|
| 114 |
+
if i >= len(graph_data):
|
| 115 |
+
break
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
correct_answer = graph_data[i]["num_holes"]
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
predicted_answer = answer.get("cycle_holes")
|
| 122 |
+
if predicted_answer is None:
|
| 123 |
+
evaluation_results.append({
|
| 124 |
+
"index": i,
|
| 125 |
+
"correct": correct_answer,
|
| 126 |
+
"predicted": None,
|
| 127 |
+
"match": False,
|
| 128 |
+
"error": "Missing 'cycle_holes'"
|
| 129 |
+
})
|
| 130 |
+
continue
|
| 131 |
+
is_correct = predicted_answer == correct_answer
|
| 132 |
+
if is_correct:
|
| 133 |
+
correct_count += 1
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
evaluation_result = {
|
| 137 |
+
"is_correct": is_correct,
|
| 138 |
+
"predicted_answer": predicted_answer,
|
| 139 |
+
"correct_answer": correct_answer
|
| 140 |
+
}
|
| 141 |
+
evaluation_results.append(evaluation_result)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
accuracy = correct_count / total_count if total_count > 0 else 0
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
stats = {
|
| 148 |
+
"total_samples": total_count,
|
| 149 |
+
"correct_count": correct_count,
|
| 150 |
+
"wrong_count": total_count - correct_count,
|
| 151 |
+
"accuracy": accuracy
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
return accuracy, {
|
| 155 |
+
"statistics": stats,
|
| 156 |
+
"detailed_results": evaluation_results
|
| 157 |
+
}
|
| 158 |
+
def evaluate_S_Modification(self, graph_data, extracted_answers):
|
| 159 |
+
"""
|
| 160 |
+
Evaluate graph_0dim_modification accuracy
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
graph_data: List of graph data objects
|
| 164 |
+
extracted_answers: List of dicts with edge_to_add
|
| 165 |
+
|
| 166 |
+
Returns:
|
| 167 |
+
accuracy: accuracy
|
| 168 |
+
evaluation_results: dict containing detailed evaluation results and statistics
|
| 169 |
+
"""
|
| 170 |
+
correct_count = 0
|
| 171 |
+
total_count = len(graph_data)
|
| 172 |
+
evaluation_results = []
|
| 173 |
+
|
| 174 |
+
for i, (graph, answer) in enumerate(zip(graph_data, extracted_answers)):
|
| 175 |
+
# Check answer format
|
| 176 |
+
if "error" in answer:
|
| 177 |
+
evaluation_results.append({
|
| 178 |
+
"is_correct": False,
|
| 179 |
+
"error": answer["error"]
|
| 180 |
+
})
|
| 181 |
+
continue
|
| 182 |
+
|
| 183 |
+
if "edge_to_add" not in answer:
|
| 184 |
+
evaluation_results.append({
|
| 185 |
+
"is_correct": False,
|
| 186 |
+
"error": "Missing edge_to_add in answer"
|
| 187 |
+
})
|
| 188 |
+
continue
|
| 189 |
+
|
| 190 |
+
# Get edge to add
|
| 191 |
+
edge_to_add = answer["edge_to_add"]
|
| 192 |
+
if len(edge_to_add) != 2:
|
| 193 |
+
evaluation_results.append({
|
| 194 |
+
"is_correct": False,
|
| 195 |
+
"error": f"Invalid edge format: {edge_to_add}"
|
| 196 |
+
})
|
| 197 |
+
continue
|
| 198 |
+
|
| 199 |
+
# Get original edge index and node count
|
| 200 |
+
original_edge_index = graph["edge_index"] # Shape [2,N]
|
| 201 |
+
num_nodes = graph["num_nodes"]
|
| 202 |
+
|
| 203 |
+
# Ensure original_edge_index is 2D array
|
| 204 |
+
if len(original_edge_index.shape) == 1:
|
| 205 |
+
original_edge_index = original_edge_index.reshape(2, -1)
|
| 206 |
+
|
| 207 |
+
# Validate node index range
|
| 208 |
+
if edge_to_add[0] >= num_nodes or edge_to_add[1] >= num_nodes:
|
| 209 |
+
evaluation_results.append({
|
| 210 |
+
"is_correct": False,
|
| 211 |
+
"error": f"Node indices out of range: {edge_to_add}, max index is {num_nodes-1}"
|
| 212 |
+
})
|
| 213 |
+
continue
|
| 214 |
+
|
| 215 |
+
# Calculate original number of connected components
|
| 216 |
+
original_components = graph["num_components"]
|
| 217 |
+
|
| 218 |
+
# Add new edge, maintaining [2,N] shape
|
| 219 |
+
new_edge = np.array([[edge_to_add[0]], [edge_to_add[1]]], dtype=np.int64)
|
| 220 |
+
new_edge_index = np.concatenate([original_edge_index, new_edge], axis=1)
|
| 221 |
+
|
| 222 |
+
# Calculate new number of connected components
|
| 223 |
+
new_components = count_connected_components(new_edge_index, num_nodes)
|
| 224 |
+
|
| 225 |
+
# Check if correct (number of connected components should decrease)
|
| 226 |
+
is_correct = new_components < original_components
|
| 227 |
+
|
| 228 |
+
if is_correct:
|
| 229 |
+
correct_count += 1
|
| 230 |
+
|
| 231 |
+
evaluation_results.append({
|
| 232 |
+
"is_correct": is_correct,
|
| 233 |
+
"edge_added": edge_to_add,
|
| 234 |
+
"original_components": original_components,
|
| 235 |
+
"new_components": new_components
|
| 236 |
+
})
|
| 237 |
+
|
| 238 |
+
# Calculate accuracy
|
| 239 |
+
accuracy = correct_count / total_count if total_count > 0 else 0
|
| 240 |
+
|
| 241 |
+
# Add statistics
|
| 242 |
+
stats = {
|
| 243 |
+
"total_samples": total_count,
|
| 244 |
+
"correct_count": correct_count,
|
| 245 |
+
"wrong_count": total_count - correct_count,
|
| 246 |
+
"accuracy": accuracy
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
return accuracy, {
|
| 250 |
+
"statistics": stats,
|
| 251 |
+
"detailed_results": evaluation_results
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
def evaluate_filtration_edge_construction(self, graph_data, extracted_answers):
|
| 255 |
+
"""
|
| 256 |
+
Evaluate filtration edge construction accuracy
|
| 257 |
+
|
| 258 |
+
Args:
|
| 259 |
+
graph_data: List of graph data objects
|
| 260 |
+
extracted_answers: List of dicts with sorted_edges
|
| 261 |
+
|
| 262 |
+
Returns:
|
| 263 |
+
accuracy: accuracy
|
| 264 |
+
evaluation_results: dict containing detailed evaluation results and statistics
|
| 265 |
+
"""
|
| 266 |
+
correct_count = 0
|
| 267 |
+
total_count = len(extracted_answers)
|
| 268 |
+
evaluation_results = []
|
| 269 |
+
|
| 270 |
+
for i, answer in enumerate(extracted_answers):
|
| 271 |
+
if i >= len(graph_data):
|
| 272 |
+
break
|
| 273 |
+
|
| 274 |
+
# get correct answer (sorted_edges)
|
| 275 |
+
correct_edges = graph_data[i]["sorted_edges"]
|
| 276 |
+
|
| 277 |
+
# get predicted answer (filtration dictionary)
|
| 278 |
+
predicted_filtration = answer["filtration"]
|
| 279 |
+
|
| 280 |
+
# convert predicted filtration to edge list format
|
| 281 |
+
predicted_edges = []
|
| 282 |
+
for value, edges in predicted_filtration.items():
|
| 283 |
+
for u, v in edges:
|
| 284 |
+
predicted_edges.append((u, v, float(value)))
|
| 285 |
+
|
| 286 |
+
# sort edges by weight (ascending)
|
| 287 |
+
predicted_edges.sort(key=lambda x: x[2])
|
| 288 |
+
|
| 289 |
+
# check if correct
|
| 290 |
+
is_correct = len(predicted_edges) == len(correct_edges)
|
| 291 |
+
if is_correct:
|
| 292 |
+
for pred, corr in zip(predicted_edges, correct_edges):
|
| 293 |
+
if pred != corr:
|
| 294 |
+
is_correct = False
|
| 295 |
+
break
|
| 296 |
+
|
| 297 |
+
if is_correct:
|
| 298 |
+
correct_count += 1
|
| 299 |
+
|
| 300 |
+
# record detailed evaluation results
|
| 301 |
+
evaluation_result = {
|
| 302 |
+
"is_correct": is_correct,
|
| 303 |
+
"predicted_edges": predicted_edges,
|
| 304 |
+
"correct_edges": correct_edges,
|
| 305 |
+
"edge_count_match": len(predicted_edges) == len(correct_edges),
|
| 306 |
+
"edge_order_match": is_correct
|
| 307 |
+
}
|
| 308 |
+
evaluation_results.append(evaluation_result)
|
| 309 |
+
|
| 310 |
+
# calculate accuracy
|
| 311 |
+
accuracy = correct_count / total_count if total_count > 0 else 0
|
| 312 |
+
|
| 313 |
+
# prepare statistics
|
| 314 |
+
stats = {
|
| 315 |
+
"total_samples": total_count,
|
| 316 |
+
"correct_count": correct_count,
|
| 317 |
+
"wrong_count": total_count - correct_count,
|
| 318 |
+
"accuracy": accuracy
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
return accuracy, {
|
| 322 |
+
"statistics": stats,
|
| 323 |
+
"detailed_results": evaluation_results
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
def evaluate_simplicial_complex_construction(self, graph_data, extracted_answers):
|
| 327 |
+
"""
|
| 328 |
+
Evaluate simplicial complex construction accuracy
|
| 329 |
+
|
| 330 |
+
Args:
|
| 331 |
+
graph_data: List of graph data objects
|
| 332 |
+
extracted_answers: List of dicts with simplicial_complexes
|
| 333 |
+
|
| 334 |
+
Returns:
|
| 335 |
+
accuracy: accuracy
|
| 336 |
+
evaluation_results: dict containing detailed evaluation results and statistics
|
| 337 |
+
"""
|
| 338 |
+
correct_count = 0
|
| 339 |
+
total_count = len(extracted_answers)
|
| 340 |
+
evaluation_results = []
|
| 341 |
+
|
| 342 |
+
for i, answer in enumerate(extracted_answers):
|
| 343 |
+
if i >= len(graph_data):
|
| 344 |
+
break
|
| 345 |
+
|
| 346 |
+
# get correct answer (2-dimensional simplices)
|
| 347 |
+
correct_simplices = {}
|
| 348 |
+
for simplex, value in graph_data[i]["simplex"]:
|
| 349 |
+
if len(simplex) == 3: # only process 2-dimensional simplices
|
| 350 |
+
if value not in correct_simplices:
|
| 351 |
+
correct_simplices[value] = []
|
| 352 |
+
correct_simplices[value].append(sorted(simplex))
|
| 353 |
+
|
| 354 |
+
# get predicted answer
|
| 355 |
+
predicted_simplices = answer.get("simplicial_complexes", {})
|
| 356 |
+
|
| 357 |
+
is_correct = True
|
| 358 |
+
|
| 359 |
+
# check all filtration values
|
| 360 |
+
all_values = set(list(correct_simplices.keys()) + list(predicted_simplices.keys()))
|
| 361 |
+
for value in all_values:
|
| 362 |
+
correct = sorted([sorted(s) for s in correct_simplices.get(value, [])])
|
| 363 |
+
predicted = sorted([sorted(s) for s in predicted_simplices.get(value, [])])
|
| 364 |
+
|
| 365 |
+
if correct != predicted:
|
| 366 |
+
is_correct = False
|
| 367 |
+
break
|
| 368 |
+
|
| 369 |
+
if is_correct:
|
| 370 |
+
correct_count += 1
|
| 371 |
+
|
| 372 |
+
# record detailed evaluation results
|
| 373 |
+
evaluation_result = {
|
| 374 |
+
"is_correct": is_correct,
|
| 375 |
+
"predicted_simplices": predicted_simplices,
|
| 376 |
+
"correct_simplices": correct_simplices,
|
| 377 |
+
"value_match": is_correct
|
| 378 |
+
}
|
| 379 |
+
evaluation_results.append(evaluation_result)
|
| 380 |
+
|
| 381 |
+
# calculate accuracy
|
| 382 |
+
accuracy = correct_count / total_count if total_count > 0 else 0
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
stats = {
|
| 386 |
+
"total_samples": total_count,
|
| 387 |
+
"correct_count": correct_count,
|
| 388 |
+
"wrong_count": total_count - correct_count,
|
| 389 |
+
"accuracy": accuracy
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
return accuracy, {
|
| 393 |
+
"statistics": stats,
|
| 394 |
+
"detailed_results": evaluation_results
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
def evaluate_M_Merge(self, graph_data, extracted_answers):
|
| 398 |
+
"""
|
| 399 |
+
Evaluate 0-dimensional persistent homology calculation accuracy
|
| 400 |
+
|
| 401 |
+
Args:
|
| 402 |
+
graph_data: List of graph data objects
|
| 403 |
+
extracted_answers: List of dictionaries containing death time of feature
|
| 404 |
+
|
| 405 |
+
Returns:
|
| 406 |
+
accuracy: accuracy
|
| 407 |
+
evaluation_results: dict containing detailed evaluation results and statistics
|
| 408 |
+
"""
|
| 409 |
+
correct_count = 0
|
| 410 |
+
total_count = len(extracted_answers)
|
| 411 |
+
evaluation_results = []
|
| 412 |
+
|
| 413 |
+
for i, answer in enumerate(extracted_answers):
|
| 414 |
+
if i >= len(graph_data):
|
| 415 |
+
break
|
| 416 |
+
|
| 417 |
+
# get correct answer
|
| 418 |
+
correct_time = graph_data[i]["death_value"]
|
| 419 |
+
|
| 420 |
+
# get predicted answer
|
| 421 |
+
if "error" in answer:
|
| 422 |
+
is_correct = False
|
| 423 |
+
predicted_time = None
|
| 424 |
+
else:
|
| 425 |
+
predicted_time = answer.get("death_time", [None])[0] # Get first value from death_time list
|
| 426 |
+
is_correct = predicted_time == correct_time
|
| 427 |
+
|
| 428 |
+
if is_correct:
|
| 429 |
+
correct_count += 1
|
| 430 |
+
|
| 431 |
+
evaluation_result = {
|
| 432 |
+
"is_correct": is_correct,
|
| 433 |
+
"predicted_time": predicted_time,
|
| 434 |
+
"correct_time": correct_time
|
| 435 |
+
}
|
| 436 |
+
evaluation_results.append(evaluation_result)
|
| 437 |
+
|
| 438 |
+
accuracy = correct_count / total_count if total_count > 0 else 0
|
| 439 |
+
|
| 440 |
+
stats = {
|
| 441 |
+
"total_samples": total_count,
|
| 442 |
+
"correct_count": correct_count,
|
| 443 |
+
"wrong_count": total_count - correct_count,
|
| 444 |
+
"accuracy": accuracy
|
| 445 |
+
}
|
| 446 |
+
|
| 447 |
+
return accuracy, {
|
| 448 |
+
"statistics": stats,
|
| 449 |
+
"detailed_results": evaluation_results
|
| 450 |
+
}
|
| 451 |
+
|
| 452 |
+
def evaluate_M_Birth(self, graph_data, extracted_answers):
|
| 453 |
+
"""
|
| 454 |
+
Evaluate 1-dimensional persistent homology calculation accuracy
|
| 455 |
+
|
| 456 |
+
Args:
|
| 457 |
+
graph_data: List of graph data objects
|
| 458 |
+
extracted_answers: List of dicts with persistent_features
|
| 459 |
+
|
| 460 |
+
Returns:
|
| 461 |
+
accuracy: accuracy
|
| 462 |
+
evaluation_results: dict containing detailed evaluation results and statistics
|
| 463 |
+
"""
|
| 464 |
+
correct_count = 0
|
| 465 |
+
total_count = len(extracted_answers)
|
| 466 |
+
evaluation_results = []
|
| 467 |
+
|
| 468 |
+
for i, answer in enumerate(extracted_answers):
|
| 469 |
+
if i >= len(graph_data):
|
| 470 |
+
break
|
| 471 |
+
|
| 472 |
+
# get correct answer
|
| 473 |
+
correct_time = graph_data[i]["birth_value"]
|
| 474 |
+
|
| 475 |
+
# get predicted answer
|
| 476 |
+
if "error" in answer:
|
| 477 |
+
is_correct = False
|
| 478 |
+
predicted_time = None
|
| 479 |
+
else:
|
| 480 |
+
predicted_time = answer.get("birth_time", [None])[0] # Get first value from death_time list
|
| 481 |
+
is_correct = predicted_time == correct_time
|
| 482 |
+
|
| 483 |
+
if is_correct:
|
| 484 |
+
correct_count += 1
|
| 485 |
+
|
| 486 |
+
evaluation_result = {
|
| 487 |
+
"is_correct": is_correct,
|
| 488 |
+
"predicted_time": predicted_time,
|
| 489 |
+
"correct_time": correct_time
|
| 490 |
+
}
|
| 491 |
+
evaluation_results.append(evaluation_result)
|
| 492 |
+
|
| 493 |
+
accuracy = correct_count / total_count if total_count > 0 else 0
|
| 494 |
+
|
| 495 |
+
stats = {
|
| 496 |
+
"total_samples": total_count,
|
| 497 |
+
"correct_count": correct_count,
|
| 498 |
+
"wrong_count": total_count - correct_count,
|
| 499 |
+
"accuracy": accuracy
|
| 500 |
+
}
|
| 501 |
+
|
| 502 |
+
return accuracy, {
|
| 503 |
+
"statistics": stats,
|
| 504 |
+
"detailed_results": evaluation_results
|
| 505 |
+
}
|
| 506 |
+
def evaluate_M_Filtration(self, graph_data, extracted_answers):
|
| 507 |
+
"""
|
| 508 |
+
Evaluate filtration_features_count accuracy
|
| 509 |
+
|
| 510 |
+
Args:
|
| 511 |
+
graph_data: List of graph data objects
|
| 512 |
+
extracted_answers: filtration_features_count number
|
| 513 |
+
|
| 514 |
+
Returns:
|
| 515 |
+
accuracy: accuracy
|
| 516 |
+
evaluation_results: dict containing detailed evaluation results and statistics
|
| 517 |
+
"""
|
| 518 |
+
correct_count = 0
|
| 519 |
+
total_count = len(extracted_answers)
|
| 520 |
+
evaluation_results = []
|
| 521 |
+
|
| 522 |
+
for i, answer in enumerate(extracted_answers):
|
| 523 |
+
if i >= len(graph_data):
|
| 524 |
+
break
|
| 525 |
+
|
| 526 |
+
# get correct answer
|
| 527 |
+
correct_n = graph_data[i]["t3_0dim"]
|
| 528 |
+
|
| 529 |
+
# get predicted answer
|
| 530 |
+
if "error" in answer:
|
| 531 |
+
is_correct = False
|
| 532 |
+
predicted_count = None
|
| 533 |
+
else:
|
| 534 |
+
predicted_count = answer.get("connected_components", [None])[0] # Get first value from death_time list
|
| 535 |
+
is_correct = predicted_count == correct_n
|
| 536 |
+
|
| 537 |
+
if is_correct:
|
| 538 |
+
correct_count += 1
|
| 539 |
+
|
| 540 |
+
evaluation_result = {
|
| 541 |
+
"is_correct": is_correct,
|
| 542 |
+
"predicted_count": predicted_count,
|
| 543 |
+
"correct_count": correct_n
|
| 544 |
+
}
|
| 545 |
+
evaluation_results.append(evaluation_result)
|
| 546 |
+
|
| 547 |
+
accuracy = correct_count / total_count if total_count > 0 else 0
|
| 548 |
+
|
| 549 |
+
stats = {
|
| 550 |
+
"total_samples": total_count,
|
| 551 |
+
"correct_count": correct_count,
|
| 552 |
+
"wrong_count": total_count - correct_count,
|
| 553 |
+
"accuracy": accuracy
|
| 554 |
+
}
|
| 555 |
+
|
| 556 |
+
return accuracy, {
|
| 557 |
+
"statistics": stats,
|
| 558 |
+
"detailed_results": evaluation_results
|
| 559 |
+
}
|
| 560 |
+
def _check_edge_sorting(self, edge_sorting, graph_data):
|
| 561 |
+
"""Check if edge sorting is correct"""
|
| 562 |
+
|
| 563 |
+
try:
|
| 564 |
+
|
| 565 |
+
if not edge_sorting:
|
| 566 |
+
return False
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
for i in range(1, len(edge_sorting)):
|
| 570 |
+
if edge_sorting[i][2] < edge_sorting[i-1][2]:
|
| 571 |
+
return False
|
| 572 |
+
|
| 573 |
+
return True
|
| 574 |
+
except:
|
| 575 |
+
return False
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def evaluate_H_Selection(self, graph_data, extracted_answers) -> Tuple[float, Dict]:
|
| 580 |
+
"""
|
| 581 |
+
Evaluate filtration method selection ranking statistics
|
| 582 |
+
|
| 583 |
+
Args:
|
| 584 |
+
graph_data: List of graph data objects, where graph_data[2i].better_filter contains correct answer
|
| 585 |
+
extracted_answers: List of dicts with selected_method
|
| 586 |
+
|
| 587 |
+
Returns:
|
| 588 |
+
Tuple of (accuracy, detailed results dict)
|
| 589 |
+
"""
|
| 590 |
+
detailed_results = []
|
| 591 |
+
|
| 592 |
+
all_ranks = []
|
| 593 |
+
top1_count = 0
|
| 594 |
+
top2_count = 0
|
| 595 |
+
top3_count = 0
|
| 596 |
+
|
| 597 |
+
for i, answer in enumerate(extracted_answers):
|
| 598 |
+
if answer is None or answer.get("selected_method") is None:
|
| 599 |
+
detailed_results.append({
|
| 600 |
+
"reason": "No valid answer extracted"
|
| 601 |
+
})
|
| 602 |
+
continue
|
| 603 |
+
|
| 604 |
+
graph_idx = i
|
| 605 |
+
if graph_idx >= len(graph_data):
|
| 606 |
+
break
|
| 607 |
+
|
| 608 |
+
predicted_method = answer["selected_method"]
|
| 609 |
+
if predicted_method == 'weight':
|
| 610 |
+
predicted_method = 'e'
|
| 611 |
+
if predicted_method == "k-shell":
|
| 612 |
+
predicted_method = "k_shell"
|
| 613 |
+
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']}
|
| 614 |
+
|
| 615 |
+
predicted_rank = None
|
| 616 |
+
current_rank = 1
|
| 617 |
+
current_distance = None
|
| 618 |
+
same_rank_count = 0
|
| 619 |
+
|
| 620 |
+
for method, distance in dist_features.items():
|
| 621 |
+
if current_distance is not None and distance != current_distance:
|
| 622 |
+
current_rank += same_rank_count
|
| 623 |
+
same_rank_count = 0
|
| 624 |
+
current_distance = distance
|
| 625 |
+
elif current_distance is None:
|
| 626 |
+
current_distance = distance
|
| 627 |
+
|
| 628 |
+
if method.replace('dist_', '') == predicted_method:
|
| 629 |
+
predicted_rank = current_rank
|
| 630 |
+
all_ranks.append(current_rank)
|
| 631 |
+
if current_rank == 1:
|
| 632 |
+
top1_count += 1
|
| 633 |
+
if current_rank <= 2:
|
| 634 |
+
top2_count += 1
|
| 635 |
+
if current_rank <= 3:
|
| 636 |
+
top3_count += 1
|
| 637 |
+
break
|
| 638 |
+
|
| 639 |
+
same_rank_count += 1
|
| 640 |
+
|
| 641 |
+
detailed_results.append({
|
| 642 |
+
"predicted": predicted_method,
|
| 643 |
+
"predicted_rank": predicted_rank,
|
| 644 |
+
"method_rankings": dict(dist_features)
|
| 645 |
+
})
|
| 646 |
+
|
| 647 |
+
ranking_stats = {
|
| 648 |
+
'mean_rank': sum(all_ranks) / len(all_ranks) if all_ranks else float('inf'),
|
| 649 |
+
'min_rank': min(all_ranks) if all_ranks else float('inf'),
|
| 650 |
+
'max_rank': max(all_ranks) if all_ranks else float('inf'),
|
| 651 |
+
'std_rank': statistics.stdev(all_ranks) if len(all_ranks) > 1 else 0,
|
| 652 |
+
'total_predictions': len(all_ranks),
|
| 653 |
+
'top1_count': top1_count,
|
| 654 |
+
'top2_count': top2_count,
|
| 655 |
+
'top3_count': top3_count,
|
| 656 |
+
'top1_ratio': top1_count / len(all_ranks) if all_ranks else 0,
|
| 657 |
+
'top2_ratio': top2_count / len(all_ranks) if all_ranks else 0,
|
| 658 |
+
'top3_ratio': top3_count / len(all_ranks) if all_ranks else 0
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
return 0.0, {
|
| 662 |
+
"statistics": {
|
| 663 |
+
**ranking_stats
|
| 664 |
+
},
|
| 665 |
+
"detailed_results": detailed_results
|
| 666 |
+
}
|
| 667 |
+
|
| 668 |
+
def evaluate_H_Generation(self, graph_data, extracted_answers) -> Tuple[float, Dict]:
|
| 669 |
+
"""
|
| 670 |
+
评估过滤序列选择的排名统计
|
| 671 |
+
|
| 672 |
+
Args:
|
| 673 |
+
graph_data: List of graph data objects
|
| 674 |
+
extracted_answers: List of dicts with selected_filtration_values field
|
| 675 |
+
|
| 676 |
+
Returns:
|
| 677 |
+
Tuple (accuracy, detailed_results_dict)
|
| 678 |
+
"""
|
| 679 |
+
total = 0
|
| 680 |
+
detailed_results = []
|
| 681 |
+
|
| 682 |
+
for i, answer in enumerate(extracted_answers):
|
| 683 |
+
if i >= len(graph_data):
|
| 684 |
+
break
|
| 685 |
+
|
| 686 |
+
if answer is None or "selected_filtration_values" not in answer:
|
| 687 |
+
detailed_results.append({
|
| 688 |
+
"reason": "No valid answer extracted"
|
| 689 |
+
})
|
| 690 |
+
continue
|
| 691 |
+
|
| 692 |
+
graph1 = graph_data[i][0]
|
| 693 |
+
|
| 694 |
+
selected_values = answer["selected_filtration_values"]
|
| 695 |
+
if isinstance(selected_values, (int, float)):
|
| 696 |
+
selected_values = [[selected_values]]
|
| 697 |
+
elif isinstance(selected_values, (list, tuple)) and not any(isinstance(x, (list, tuple)) for x in selected_values):
|
| 698 |
+
selected_values = [selected_values]
|
| 699 |
+
|
| 700 |
+
selected_distances = []
|
| 701 |
+
selected_ranks = []
|
| 702 |
+
|
| 703 |
+
for seq in selected_values:
|
| 704 |
+
if not isinstance(seq, (list, tuple)):
|
| 705 |
+
seq = [seq]
|
| 706 |
+
seq_tuple = tuple(sorted(float(x) if isinstance(x, (int, float)) else x for x in seq))
|
| 707 |
+
|
| 708 |
+
found_match = False
|
| 709 |
+
current_rank = 1
|
| 710 |
+
current_distance = None
|
| 711 |
+
same_rank_count = 0
|
| 712 |
+
sorted_distances = json.loads(graph1['sorted_distances'])
|
| 713 |
+
for item in sorted_distances:
|
| 714 |
+
curr_seq = item['nodes']
|
| 715 |
+
distance = item['distance']
|
| 716 |
+
curr_seq_tuple = tuple(sorted(float(x) if isinstance(x, (int, float)) else x for x in curr_seq))
|
| 717 |
+
|
| 718 |
+
if current_distance is not None and distance != current_distance:
|
| 719 |
+
current_rank += same_rank_count
|
| 720 |
+
same_rank_count = 0
|
| 721 |
+
current_distance = distance
|
| 722 |
+
elif current_distance is None:
|
| 723 |
+
current_distance = distance
|
| 724 |
+
|
| 725 |
+
if curr_seq_tuple == seq_tuple:
|
| 726 |
+
selected_distances.append(float(distance))
|
| 727 |
+
selected_ranks.append(current_rank)
|
| 728 |
+
found_match = True
|
| 729 |
+
break
|
| 730 |
+
|
| 731 |
+
same_rank_count += 1
|
| 732 |
+
|
| 733 |
+
if not found_match:
|
| 734 |
+
selected_distances.append(float('inf'))
|
| 735 |
+
selected_ranks.append(len(graph1.sorted_distances) + 1)
|
| 736 |
+
|
| 737 |
+
rank = sum(selected_ranks) / len(selected_ranks) if selected_ranks else float('inf')
|
| 738 |
+
|
| 739 |
+
in_top3 = sum(1 for rank in selected_ranks if rank <= 3)
|
| 740 |
+
in_top10 = sum(1 for rank in selected_ranks if rank <= 10)
|
| 741 |
+
top3 = in_top3 / len(selected_ranks) if selected_ranks else 0
|
| 742 |
+
top10 = in_top10 / len(selected_ranks) if selected_ranks else 0
|
| 743 |
+
|
| 744 |
+
total += 1
|
| 745 |
+
|
| 746 |
+
detailed_results.append({
|
| 747 |
+
"selected_ranks": selected_ranks,
|
| 748 |
+
"selected_distances": selected_distances,
|
| 749 |
+
"rank": float(rank),
|
| 750 |
+
"top3": float(top3),
|
| 751 |
+
"top10": float(top10),
|
| 752 |
+
"original_values": selected_values
|
| 753 |
+
})
|
| 754 |
+
|
| 755 |
+
valid_results = [r for r in detailed_results if "rank" in r]
|
| 756 |
+
rank_list = [r["rank"] for r in valid_results]
|
| 757 |
+
|
| 758 |
+
avg_stats = {
|
| 759 |
+
"mean_rank": float(sum(rank_list) / len(rank_list)) if rank_list else float('inf'),
|
| 760 |
+
"top3": float(sum(r["top3"] for r in valid_results) / len(valid_results)) if valid_results else 0.0,
|
| 761 |
+
"top10": float(sum(r["top10"] for r in valid_results) / len(valid_results)) if valid_results else 0.0,
|
| 762 |
+
"std_rank": float(statistics.stdev(rank_list)) if len(rank_list) > 1 else 0.0
|
| 763 |
+
}
|
| 764 |
+
|
| 765 |
+
return 0.0, {
|
| 766 |
+
"statistics": {
|
| 767 |
+
"total": int(total),
|
| 768 |
+
**avg_stats
|
| 769 |
+
},
|
| 770 |
+
"detailed_results": detailed_results
|
| 771 |
+
}
|
| 772 |
+
|
| 773 |
+
def evaluate_R_Classification(self, graph_data, extracted_answers):
|
| 774 |
+
correct_count = 0
|
| 775 |
+
total_count = len(extracted_answers)
|
| 776 |
+
evaluation_results = []
|
| 777 |
+
|
| 778 |
+
ground_truth_sorted = sorted([sorted([1, 2]), sorted([3, 4])])
|
| 779 |
+
|
| 780 |
+
for i, answer in enumerate(extracted_answers):
|
| 781 |
+
if "error" in answer or "categories" not in answer:
|
| 782 |
+
evaluation_results.append({
|
| 783 |
+
"index": i,
|
| 784 |
+
"is_correct": False,
|
| 785 |
+
"reason": "Missing or invalid 'categories' field",
|
| 786 |
+
"predicted": None,
|
| 787 |
+
"expected": ground_truth_sorted
|
| 788 |
+
})
|
| 789 |
+
continue
|
| 790 |
+
|
| 791 |
+
predicted = answer["categories"]
|
| 792 |
+
|
| 793 |
+
try:
|
| 794 |
+
predicted_sorted = sorted([sorted(group) for group in predicted])
|
| 795 |
+
is_correct = predicted_sorted == ground_truth_sorted
|
| 796 |
+
except Exception as e:
|
| 797 |
+
is_correct = False
|
| 798 |
+
predicted_sorted = None
|
| 799 |
+
|
| 800 |
+
if is_correct:
|
| 801 |
+
correct_count += 1
|
| 802 |
+
|
| 803 |
+
evaluation_results.append({
|
| 804 |
+
"index": i,
|
| 805 |
+
"is_correct": is_correct,
|
| 806 |
+
"predicted": predicted,
|
| 807 |
+
"expected": ground_truth_sorted
|
| 808 |
+
})
|
| 809 |
+
|
| 810 |
+
accuracy = correct_count / total_count if total_count > 0 else 0.0
|
| 811 |
+
|
| 812 |
+
stats = {
|
| 813 |
+
"total_samples": total_count,
|
| 814 |
+
"correct_count": correct_count,
|
| 815 |
+
"wrong_count": total_count - correct_count,
|
| 816 |
+
"accuracy": accuracy
|
| 817 |
+
}
|
| 818 |
+
|
| 819 |
+
return accuracy, {
|
| 820 |
+
"statistics": stats,
|
| 821 |
+
"detailed_results": evaluation_results
|
| 822 |
+
}
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
def evaluate_R_Selection(self, graph_data, extracted_answers):
|
| 826 |
+
"""
|
| 827 |
+
Evaluate whether the selected filtration method is correct based on method_dict.
|
| 828 |
+
|
| 829 |
+
Args:
|
| 830 |
+
graph_data: List of graph data entries, where each entry is a tuple (graph, ...) and graph.method_dict is a dict
|
| 831 |
+
extracted_answers: List of dicts with key 'selected_method'
|
| 832 |
+
|
| 833 |
+
Returns:
|
| 834 |
+
accuracy: float
|
| 835 |
+
result_summary: dict with statistics and detailed evaluation results
|
| 836 |
+
"""
|
| 837 |
+
correct_count = 0
|
| 838 |
+
total_count = len(extracted_answers)
|
| 839 |
+
evaluation_results = []
|
| 840 |
+
|
| 841 |
+
for i, answer in enumerate(extracted_answers):
|
| 842 |
+
if i >= len(graph_data):
|
| 843 |
+
break
|
| 844 |
+
|
| 845 |
+
method_dict = {
|
| 846 |
+
'weight': graph_data[i][0]['method_weight'],
|
| 847 |
+
'degree': graph_data[i][0]['method_degree'],
|
| 848 |
+
'betweenness': graph_data[i][0]['method_betweenness'],
|
| 849 |
+
'k_shell': graph_data[i][0]['method_k_shell'],
|
| 850 |
+
'closeness': graph_data[i][0]['method_closeness'],
|
| 851 |
+
'eigenvector': graph_data[i][0]['method_eigenvector']
|
| 852 |
+
}
|
| 853 |
+
|
| 854 |
+
if "error" in answer or "selected_method" not in answer:
|
| 855 |
+
evaluation_results.append({
|
| 856 |
+
"index": i,
|
| 857 |
+
"is_correct": False,
|
| 858 |
+
"predicted_method": answer.get("selected_method", None),
|
| 859 |
+
"expected_methods": [k for k, v in method_dict.items() if v],
|
| 860 |
+
"reason": "No valid method extracted"
|
| 861 |
+
})
|
| 862 |
+
continue
|
| 863 |
+
predicted_method = answer.get("selected_method")
|
| 864 |
+
|
| 865 |
+
if predicted_method not in method_dict:
|
| 866 |
+
return {"error": f"Invalid method selected: {predicted_method}"}
|
| 867 |
+
|
| 868 |
+
is_correct = bool(method_dict[predicted_method])
|
| 869 |
+
|
| 870 |
+
if is_correct:
|
| 871 |
+
correct_count += 1
|
| 872 |
+
|
| 873 |
+
evaluation_results.append({
|
| 874 |
+
"index": i,
|
| 875 |
+
"is_correct": is_correct,
|
| 876 |
+
"predicted_method": predicted_method,
|
| 877 |
+
"expected_methods": [k for k, v in method_dict.items() if v]
|
| 878 |
+
})
|
| 879 |
+
|
| 880 |
+
accuracy = correct_count / total_count if total_count > 0 else 0.0
|
| 881 |
+
|
| 882 |
+
stats = {
|
| 883 |
+
"total_samples": total_count,
|
| 884 |
+
"correct_count": correct_count,
|
| 885 |
+
"wrong_count": total_count - correct_count,
|
| 886 |
+
"accuracy": accuracy
|
| 887 |
+
}
|
| 888 |
+
|
| 889 |
+
return accuracy, {
|
| 890 |
+
"statistics": stats,
|
| 891 |
+
"detailed_results": evaluation_results
|
| 892 |
+
}
|
| 893 |
+
|
| 894 |
+
def evaluate_R_Generation(self, graph_data, extracted_answers):
|
| 895 |
+
"""
|
| 896 |
+
Evaluate predictions based on filtration_values using check_filt_value().
|
| 897 |
+
|
| 898 |
+
Args:
|
| 899 |
+
graph_data: List of graph data objects
|
| 900 |
+
extracted_answers: List of dicts with key 'filtration_values'
|
| 901 |
+
|
| 902 |
+
Returns:
|
| 903 |
+
accuracy: float
|
| 904 |
+
result_summary: dict with statistics and detailed evaluation results
|
| 905 |
+
"""
|
| 906 |
+
correct_count = 0
|
| 907 |
+
total_count = len(extracted_answers)
|
| 908 |
+
evaluation_results = []
|
| 909 |
+
|
| 910 |
+
for i, answer in enumerate(extracted_answers):
|
| 911 |
+
if i >= len(graph_data):
|
| 912 |
+
break
|
| 913 |
+
|
| 914 |
+
if "error" in answer or "filtration_values" not in answer:
|
| 915 |
+
evaluation_results.append({
|
| 916 |
+
"index": i,
|
| 917 |
+
"is_correct": False,
|
| 918 |
+
"predicted_values": answer.get("filtration_values", None),
|
| 919 |
+
"reason": "No valid filtration_values extracted"
|
| 920 |
+
})
|
| 921 |
+
continue
|
| 922 |
+
|
| 923 |
+
filtration_values = answer["filtration_values"]
|
| 924 |
+
|
| 925 |
+
is_correct,distances = check_graph_group(graph_data[i], method='weight',pre_calculate=False,filt_value=filtration_values)
|
| 926 |
+
|
| 927 |
+
if is_correct:
|
| 928 |
+
correct_count += 1
|
| 929 |
+
correct = "True"
|
| 930 |
+
else:
|
| 931 |
+
correct = "False"
|
| 932 |
+
evaluation_results.append({
|
| 933 |
+
"index": i,
|
| 934 |
+
"is_correct": correct,
|
| 935 |
+
"predicted_values": filtration_values,
|
| 936 |
+
"correct": correct
|
| 937 |
+
})
|
| 938 |
+
|
| 939 |
+
accuracy = correct_count / total_count if total_count > 0 else 0.0
|
| 940 |
+
|
| 941 |
+
stats = {
|
| 942 |
+
"total_samples": total_count,
|
| 943 |
+
"correct_count": correct_count,
|
| 944 |
+
"wrong_count": total_count - correct_count,
|
| 945 |
+
"accuracy": accuracy
|
| 946 |
+
}
|
| 947 |
+
|
| 948 |
+
return accuracy, {
|
| 949 |
+
"statistics": stats,
|
| 950 |
+
"detailed_results": evaluation_results
|
| 951 |
+
}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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
def _extract_section(text: str, start_marker: str, end_marker: str) -> str:
|
| 5 |
+
"""Extract content between two markers"""
|
| 6 |
+
start = text.find(start_marker)
|
| 7 |
+
if start == -1:
|
| 8 |
+
return ""
|
| 9 |
+
start += len(start_marker)
|
| 10 |
+
end = text.find(end_marker, start)
|
| 11 |
+
if end == -1:
|
| 12 |
+
return ""
|
| 13 |
+
return text[start:end].strip()
|
| 14 |
+
|
| 15 |
+
class AnswerExtractor:
|
| 16 |
+
def __init__(self, task_name):
|
| 17 |
+
"""Initialize answer extractor"""
|
| 18 |
+
self.task_name = task_name
|
| 19 |
+
|
| 20 |
+
def extract_answers(self, response):
|
| 21 |
+
"""Extract answers based on task type"""
|
| 22 |
+
try:
|
| 23 |
+
task_extractors = {
|
| 24 |
+
"S_0D": self.extract_S_0D,
|
| 25 |
+
"S_1D": self.extract_S_1D,
|
| 26 |
+
"S_Modification": self.extract_S_Modification,
|
| 27 |
+
"M_Birth": self.extract_M_Birth,
|
| 28 |
+
"M_Merge": self.extract_M_Merge,
|
| 29 |
+
"M_Filtration": self.extract_M_Filtration,
|
| 30 |
+
"H_Selection": self.extract_H_Selection,
|
| 31 |
+
"H_Generation": self.extract_H_Generation,
|
| 32 |
+
"R_Selection": self.extract_R_Selection,
|
| 33 |
+
"R_Generation": self.extract_R_Generation,
|
| 34 |
+
"R_Directly": self.extract_R_Directly
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
answer = task_extractors.get(self.task_name)(response) if self.task_name in task_extractors else None
|
| 38 |
+
|
| 39 |
+
return answer
|
| 40 |
+
except Exception as e:
|
| 41 |
+
print(f"Error extracting answer: {str(e)}")
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def extract_S_0D(self, answer: str) -> Dict[str, Any]:
|
| 46 |
+
"""Extract information from 0-dimensional topology structure identification answer"""
|
| 47 |
+
try:
|
| 48 |
+
# Extract the answer section
|
| 49 |
+
answer_section = answer
|
| 50 |
+
if "Answer:" in answer:
|
| 51 |
+
answer_section = answer.split("Answer:")[-1].strip()
|
| 52 |
+
|
| 53 |
+
# Extract the filtration value with more flexible pattern matching
|
| 54 |
+
value_match = re.search(r'connected components:\s*(\d+)', answer_section)
|
| 55 |
+
if not value_match:
|
| 56 |
+
return {"error": "connected components not found"}
|
| 57 |
+
|
| 58 |
+
# Parse the value
|
| 59 |
+
try:
|
| 60 |
+
value = int(value_match.group(1).strip())
|
| 61 |
+
return {
|
| 62 |
+
"connected_components": value
|
| 63 |
+
}
|
| 64 |
+
except ValueError as e:
|
| 65 |
+
return {"error": f"Error parsing value: {str(e)}"}
|
| 66 |
+
|
| 67 |
+
except Exception as e:
|
| 68 |
+
return {"error": f"Error during extraction: {str(e)}"}
|
| 69 |
+
|
| 70 |
+
def extract_S_1D(self, answer: str) -> Dict[str, Any]:
|
| 71 |
+
"""Extract information from 1-dimensional topology structure identification answer"""
|
| 72 |
+
try:
|
| 73 |
+
# Extract the answer section
|
| 74 |
+
answer_section = answer
|
| 75 |
+
if "Answer:" in answer:
|
| 76 |
+
answer_section = answer.split("Answer:")[-1].strip()
|
| 77 |
+
|
| 78 |
+
# Extract the filtration value with more flexible pattern matching
|
| 79 |
+
value_match = re.search(r'cycle holes:\s*(\d+)', answer_section)
|
| 80 |
+
if not value_match:
|
| 81 |
+
return {"error": "cycle holes not found"}
|
| 82 |
+
|
| 83 |
+
# Parse the value
|
| 84 |
+
try:
|
| 85 |
+
value = int(value_match.group(1).strip())
|
| 86 |
+
return {
|
| 87 |
+
"cycle_holes": value
|
| 88 |
+
}
|
| 89 |
+
except ValueError as e:
|
| 90 |
+
return {"error": f"Error parsing value: {str(e)}"}
|
| 91 |
+
|
| 92 |
+
except Exception as e:
|
| 93 |
+
return {"error": f"Error during extraction: {str(e)}"}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def extract_S_Modification(self, answer: str) -> Dict[str, Any]:
|
| 97 |
+
"""Extract information from graph structure modification answer"""
|
| 98 |
+
try:
|
| 99 |
+
# Extract the answer section
|
| 100 |
+
answer_section = answer
|
| 101 |
+
if "Answer:" in answer:
|
| 102 |
+
answer_section = answer.split("Answer:")[-1].strip()
|
| 103 |
+
|
| 104 |
+
# Try multiple matching patterns
|
| 105 |
+
patterns = [
|
| 106 |
+
r'Edge to add:\s*\[(.*?)\]', # Match "Edge to add: [0, 7]" format
|
| 107 |
+
r'Edge to add:\s*\((\d+)\s*,\s*(\d+)\)', # Match "Edge to add: (0, 7)" format
|
| 108 |
+
r'Edge to add:\s*(\d+)\s*-\s*(\d+)', # Match "Edge to add: 0-7" format
|
| 109 |
+
r'Edge to add:\s*(\d+)\s*,\s*(\d+)' # Match "Edge to add: 0, 7" format
|
| 110 |
+
]
|
| 111 |
+
|
| 112 |
+
for pattern in patterns:
|
| 113 |
+
value_match = re.search(pattern, answer_section)
|
| 114 |
+
if value_match:
|
| 115 |
+
try:
|
| 116 |
+
if pattern == r'Edge to add:\s*\[(.*?)\]':
|
| 117 |
+
# Handle [0, 7] format
|
| 118 |
+
values_str = value_match.group(1).strip()
|
| 119 |
+
values = [int(x.strip()) for x in values_str.split(',')]
|
| 120 |
+
else:
|
| 121 |
+
# Handle other formats
|
| 122 |
+
values = [int(value_match.group(1)), int(value_match.group(2))]
|
| 123 |
+
|
| 124 |
+
return {
|
| 125 |
+
"edge_to_add": values
|
| 126 |
+
}
|
| 127 |
+
except (ValueError, IndexError):
|
| 128 |
+
continue
|
| 129 |
+
|
| 130 |
+
return {"error": "Edge to add not found or invalid format"}
|
| 131 |
+
|
| 132 |
+
except Exception as e:
|
| 133 |
+
return {"error": f"Error during extraction: {str(e)}"}
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def extract_M_Birth(self, answer: str) -> Dict[str, Any]:
|
| 137 |
+
"""Extract birth time calculation task answer"""
|
| 138 |
+
try:
|
| 139 |
+
# Extract the answer section
|
| 140 |
+
answer_section = answer
|
| 141 |
+
if "Answer:" in answer:
|
| 142 |
+
answer_section = answer.split("Answer:")[-1].strip()
|
| 143 |
+
|
| 144 |
+
# Extract the filtration value
|
| 145 |
+
value_match = re.search(r'birth time:\s*\[(.*?)\]', answer_section)
|
| 146 |
+
if not value_match:
|
| 147 |
+
return {"error": "birth_time not found"}
|
| 148 |
+
|
| 149 |
+
# Parse the values
|
| 150 |
+
try:
|
| 151 |
+
values = [self._parse_number(x) for x in value_match.group(1).split(',')]
|
| 152 |
+
return {
|
| 153 |
+
"birth_time": values
|
| 154 |
+
}
|
| 155 |
+
except ValueError as e:
|
| 156 |
+
return {"error": f"Error parsing : {str(e)}"}
|
| 157 |
+
|
| 158 |
+
except Exception as e:
|
| 159 |
+
return {"error": f"Error during extraction: {str(e)}"}
|
| 160 |
+
|
| 161 |
+
def extract_M_Merge(self, answer: str) -> Dict[str, Any]:
|
| 162 |
+
"""Extract information from 0-dimensional persistent homology calculation task answer"""
|
| 163 |
+
try:
|
| 164 |
+
# Extract the answer section
|
| 165 |
+
answer_section = answer
|
| 166 |
+
if "Answer:" in answer:
|
| 167 |
+
answer_section = answer.split("Answer:")[-1].strip()
|
| 168 |
+
|
| 169 |
+
# Extract the filtration value
|
| 170 |
+
value_match = re.search(r'death time:\s*\[(.*?)\]', answer_section)
|
| 171 |
+
if not value_match:
|
| 172 |
+
return {"error": "death_time not found"}
|
| 173 |
+
|
| 174 |
+
# Parse the values
|
| 175 |
+
try:
|
| 176 |
+
values = [self._parse_number(x) for x in value_match.group(1).split(',')]
|
| 177 |
+
return {
|
| 178 |
+
"death_time": values
|
| 179 |
+
}
|
| 180 |
+
except ValueError as e:
|
| 181 |
+
return {"error": f"Error parsing : {str(e)}"}
|
| 182 |
+
|
| 183 |
+
except Exception as e:
|
| 184 |
+
return {"error": f"Error during extraction: {str(e)}"}
|
| 185 |
+
|
| 186 |
+
def extract_M_Filtration(self,answer:str) -> Dict[str, Any]:
|
| 187 |
+
try:
|
| 188 |
+
# Extract the answer section
|
| 189 |
+
answer_section = answer
|
| 190 |
+
if "Answer:" in answer:
|
| 191 |
+
answer_section = answer.split("Answer:")[-1].strip()
|
| 192 |
+
|
| 193 |
+
# Extract the filtration value
|
| 194 |
+
value_match = re.search(r'connected components:\s*\[(.*?)\]', answer_section)
|
| 195 |
+
if not value_match:
|
| 196 |
+
return {"error": "connected components not found"}
|
| 197 |
+
|
| 198 |
+
# Parse the values
|
| 199 |
+
try:
|
| 200 |
+
values = [self._parse_number(x) for x in value_match.group(1).split(',')]
|
| 201 |
+
return {
|
| 202 |
+
"connected_components": values
|
| 203 |
+
}
|
| 204 |
+
except ValueError as e:
|
| 205 |
+
return {"error": f"Error parsing : {str(e)}"}
|
| 206 |
+
|
| 207 |
+
except Exception as e:
|
| 208 |
+
return {"error": f"Error during extraction: {str(e)}"}
|
| 209 |
+
|
| 210 |
+
def extract_H_Selection(self, answer: str) -> Dict[str, Any]:
|
| 211 |
+
"""Extract selected filtration method from the response"""
|
| 212 |
+
try:
|
| 213 |
+
# Extract the answer section
|
| 214 |
+
answer_section = answer
|
| 215 |
+
if "Answer:" in answer:
|
| 216 |
+
answer_section = answer.split("Answer:")[-1].strip()
|
| 217 |
+
# Try multiple matching patterns
|
| 218 |
+
patterns = [
|
| 219 |
+
r'Method:\s*([\w-]+)', # Match "Method: k-shell" format
|
| 220 |
+
r'Method:\s*\[([\w-]+)\]', # Match "Method: [k-shell]" format
|
| 221 |
+
r'selected_method:\s*([\w-]+)', # Match "selected_method: k-shell" format
|
| 222 |
+
r'Selected Method:\s*([\w-]+)' # Match "Selected Method: k-shell" format
|
| 223 |
+
]
|
| 224 |
+
|
| 225 |
+
for pattern in patterns:
|
| 226 |
+
value_match = re.search(pattern, answer_section, re.IGNORECASE)
|
| 227 |
+
if value_match:
|
| 228 |
+
method = value_match.group(1).strip().lower()
|
| 229 |
+
# Validate method name
|
| 230 |
+
valid_methods = ['degree', 'betweenness', 'k-shell', 'closeness', 'weight', 'eigenvector']
|
| 231 |
+
if method in valid_methods:
|
| 232 |
+
return {
|
| 233 |
+
"selected_method": method
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
return {"error": "Method not found or invalid"}
|
| 237 |
+
|
| 238 |
+
except Exception as e:
|
| 239 |
+
return {"error": f"Error during extraction: {str(e)}"}
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def extract_H_Generation(self, answer: str) -> Dict[str, Any]:
|
| 243 |
+
"""Extract information from filteration value selection task answer"""
|
| 244 |
+
try:
|
| 245 |
+
# Extract the answer section
|
| 246 |
+
answer_section = answer
|
| 247 |
+
if "Answer:" in answer:
|
| 248 |
+
answer_section = answer.split("Answer:")[-1].strip()
|
| 249 |
+
|
| 250 |
+
# Extract the filtration value
|
| 251 |
+
value_match = re.search(r'filtration value:\s*\[(.*?)\]', answer_section)
|
| 252 |
+
if not value_match:
|
| 253 |
+
return {"error": "Filtration value not found"}
|
| 254 |
+
|
| 255 |
+
# Parse the values
|
| 256 |
+
try:
|
| 257 |
+
values = [int(x.strip()) for x in value_match.group(1).split(',')]
|
| 258 |
+
return {
|
| 259 |
+
"selected_filtration_values": values
|
| 260 |
+
}
|
| 261 |
+
except ValueError as e:
|
| 262 |
+
return {"error": f"Error parsing filtration values: {str(e)}"}
|
| 263 |
+
|
| 264 |
+
except Exception as e:
|
| 265 |
+
return {"error": f"Error during extraction: {str(e)}"}
|
| 266 |
+
|
| 267 |
+
def extract_filtration_edge_construction(self, answer: str) -> Dict[str, Any]:
|
| 268 |
+
"""Extract information from filtration edge construction task answer"""
|
| 269 |
+
result = {
|
| 270 |
+
"filtration": {}
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
try:
|
| 274 |
+
# Extract filtration process
|
| 275 |
+
filtration_section = _extract_section(answer, "===FILTRATION_START===", "===FILTRATION_END===")
|
| 276 |
+
result["filtration"] = self._parse_filtration_edges(filtration_section)
|
| 277 |
+
|
| 278 |
+
# Validate results
|
| 279 |
+
if not result["filtration"]:
|
| 280 |
+
print("Warning: Failed to extract filtration process")
|
| 281 |
+
print("Filtration process:", result["filtration"])
|
| 282 |
+
|
| 283 |
+
except Exception as e:
|
| 284 |
+
import traceback
|
| 285 |
+
print(f"Error during extraction: {str(e)}")
|
| 286 |
+
print("Error details:")
|
| 287 |
+
print(traceback.format_exc())
|
| 288 |
+
return result # Return partially parsed results instead of None
|
| 289 |
+
|
| 290 |
+
return result
|
| 291 |
+
|
| 292 |
+
def extract_simplicial_complex_construction(self, answer: str) -> Dict[str, Any]:
|
| 293 |
+
"""
|
| 294 |
+
Extract answer for simplicial_complex_construction task
|
| 295 |
+
|
| 296 |
+
Parameters:
|
| 297 |
+
answer: Model generated answer text
|
| 298 |
+
|
| 299 |
+
Returns:
|
| 300 |
+
dict: Contains extracted simplicial complex information
|
| 301 |
+
"""
|
| 302 |
+
try:
|
| 303 |
+
# Extract simplicial complex section
|
| 304 |
+
simplex_text = self._extract_section(answer, "===SIMPLICIAL_COMPLEX_START===", "===SIMPLICIAL_COMPLEX_END===")
|
| 305 |
+
if not simplex_text:
|
| 306 |
+
return {"error": "Simplicial complex section not found"}
|
| 307 |
+
|
| 308 |
+
# Parse simplicial complex
|
| 309 |
+
simplices = {}
|
| 310 |
+
|
| 311 |
+
for line in simplex_text.split('\n'):
|
| 312 |
+
line = line.strip()
|
| 313 |
+
if not line:
|
| 314 |
+
continue
|
| 315 |
+
|
| 316 |
+
# Check if it's a simplex
|
| 317 |
+
if line.startswith('[') and line.endswith(']'):
|
| 318 |
+
try:
|
| 319 |
+
# Parse node list and filtration value
|
| 320 |
+
content = line[1:-1] # Remove outer brackets
|
| 321 |
+
nodes_part, value_part = content.split('),')
|
| 322 |
+
nodes = [int(x.strip()) for x in nodes_part[1:].split(',')] # Remove inner brackets
|
| 323 |
+
value = float(value_part.strip())
|
| 324 |
+
|
| 325 |
+
if len(nodes) == 3: # Only process 2-dimensional simplices (triangles)
|
| 326 |
+
if value not in simplices:
|
| 327 |
+
simplices[value] = []
|
| 328 |
+
simplices[value].append(nodes)
|
| 329 |
+
except (ValueError, IndexError) as e:
|
| 330 |
+
print(f"Error parsing simplex: {line}, error: {str(e)}")
|
| 331 |
+
continue
|
| 332 |
+
|
| 333 |
+
return {
|
| 334 |
+
"simplicial_complexes": simplices
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
except Exception as e:
|
| 338 |
+
return {"error": f"Error during extraction: {str(e)}"}
|
| 339 |
+
|
| 340 |
+
def _parse_number(self, value_str: str) -> float:
|
| 341 |
+
"""Parse number intelligently, try integer first, then float"""
|
| 342 |
+
value_str = value_str.strip()
|
| 343 |
+
try:
|
| 344 |
+
# Try parsing as integer first
|
| 345 |
+
return int(value_str)
|
| 346 |
+
except ValueError:
|
| 347 |
+
try:
|
| 348 |
+
# If integer parsing fails, try parsing as float
|
| 349 |
+
value = float(value_str)
|
| 350 |
+
# If it's an integer (no decimal part), return integer
|
| 351 |
+
if value.is_integer():
|
| 352 |
+
return int(value)
|
| 353 |
+
return value
|
| 354 |
+
except ValueError:
|
| 355 |
+
raise ValueError(f"Cannot parse number: {value_str}")
|
| 356 |
+
|
| 357 |
+
def extract_R_Selection(self, answer: str) -> Dict[str, Any]:
|
| 358 |
+
"""Extract selected filtration method from the response"""
|
| 359 |
+
try:
|
| 360 |
+
# Extract the answer section
|
| 361 |
+
answer_section = answer
|
| 362 |
+
if "Answer:" in answer:
|
| 363 |
+
answer_section = answer.split("Answer:")[-1].strip()
|
| 364 |
+
|
| 365 |
+
# Try multiple matching patterns
|
| 366 |
+
patterns = [
|
| 367 |
+
r'Method:\s*(\w+)', # Match "Method: weight" format
|
| 368 |
+
r'Method:\s*\[(.*?)\]', # Match "Method: [weight]" format
|
| 369 |
+
r'selected_method:\s*(\w+)', # Match "selected_method: weight" format
|
| 370 |
+
r'Selected Method:\s*(\w+)' # Match "Selected Method: weight" format
|
| 371 |
+
]
|
| 372 |
+
|
| 373 |
+
for pattern in patterns:
|
| 374 |
+
value_match = re.search(pattern, answer_section, re.IGNORECASE)
|
| 375 |
+
if value_match:
|
| 376 |
+
method = value_match.group(1).strip().lower()
|
| 377 |
+
# 验证方法名称是否有效
|
| 378 |
+
valid_methods = ['degree', 'betweenness', 'k-shell', 'closeness', 'weight','eigenvector']
|
| 379 |
+
if method in valid_methods:
|
| 380 |
+
return {
|
| 381 |
+
"selected_method": method
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
return {"error": "Method not found or invalid"}
|
| 385 |
+
|
| 386 |
+
except Exception as e:
|
| 387 |
+
return {"error": f"Error during extraction: {str(e)}"}
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def extract_R_Generation(self, answer: str) -> Dict[str, Any]:
|
| 391 |
+
"""Extract filtration values from the response"""
|
| 392 |
+
try:
|
| 393 |
+
# Extract content after "Answer:" if present
|
| 394 |
+
answer_section = answer
|
| 395 |
+
if "Answer:" in answer:
|
| 396 |
+
answer_section = answer.split("Answer:")[-1].strip()
|
| 397 |
+
|
| 398 |
+
# Match pattern like Filtration value: [0.1,0.4,0.5,...]
|
| 399 |
+
pattern = r'Filtration\s*value[s]?:\s*\[([^\]]+)\]'
|
| 400 |
+
match = re.search(pattern, answer_section, re.IGNORECASE)
|
| 401 |
+
if not match:
|
| 402 |
+
return {"error": "Filtration values not found"}
|
| 403 |
+
|
| 404 |
+
# Extract numbers inside brackets, split by comma and convert to float
|
| 405 |
+
nums_str = match.group(1)
|
| 406 |
+
values: List[float] = []
|
| 407 |
+
for part in nums_str.split(','):
|
| 408 |
+
part = part.strip()
|
| 409 |
+
if part:
|
| 410 |
+
try:
|
| 411 |
+
values.append(float(part))
|
| 412 |
+
except ValueError:
|
| 413 |
+
return {"error": f"Cannot convert '{part}' to float"}
|
| 414 |
+
|
| 415 |
+
return {"filtration_values": values}
|
| 416 |
+
|
| 417 |
+
except Exception as e:
|
| 418 |
+
return {"error": f"Error during extraction: {str(e)}"}
|
| 419 |
+
|
| 420 |
+
def extract_R_Directly(self, answer: str) -> Dict[str, Any]:
|
| 421 |
+
"""Extract category classification from the response"""
|
| 422 |
+
# Get content after "Answer:" if present
|
| 423 |
+
if "Answer:" in answer:
|
| 424 |
+
answer_section = answer.split("Answer:")[-1].strip()
|
| 425 |
+
else:
|
| 426 |
+
answer_section = answer
|
| 427 |
+
pattern = r'Category:\s*[\[\(]\s*([\d\.\s,]+)[\]\)]\s*,\s*[\[\(]\s*([\d\.\s,]+)[\]\)]'
|
| 428 |
+
match = re.search(pattern, answer_section, re.IGNORECASE | re.DOTALL)
|
| 429 |
+
if not match:
|
| 430 |
+
return {"error": "Category format not found or incorrect"}
|
| 431 |
+
|
| 432 |
+
def parse_group(group_str: str) -> List[int]:
|
| 433 |
+
return [int(float(x.strip())) for x in group_str.split(',') if x.strip()]
|
| 434 |
+
|
| 435 |
+
category1 = parse_group(match.group(1))
|
| 436 |
+
category2 = parse_group(match.group(2))
|
| 437 |
+
|
| 438 |
+
all_indices = sorted(category1 + category2)
|
| 439 |
+
if all_indices != [1, 2, 3, 4]:
|
| 440 |
+
return {"error": f"Graph indices must be [1, 2, 3, 4], got: {all_indices}"}
|
| 441 |
+
|
| 442 |
+
return {
|
| 443 |
+
"categories": [category1, category2]
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
# def _parse_filtration_edges(self, section: str) -> Dict[float, List[Tuple[int, int]]]:
|
| 447 |
+
# """Parse filtration process, specific to the format of filtration edge construction task"""
|
| 448 |
+
# filtration = {}
|
| 449 |
+
# current_value = None
|
| 450 |
+
# for line in section.split('\n'):
|
| 451 |
+
# line = line.strip()
|
| 452 |
+
# if line.startswith('**Value='):
|
| 453 |
+
# value_part = line.replace('**', '').replace('Value=', '').strip()
|
| 454 |
+
# current_value = float(value_part)
|
| 455 |
+
# filtration[current_value] = []
|
| 456 |
+
# elif line.startswith('(') and line.endswith(')'):
|
| 457 |
+
# try:
|
| 458 |
+
# u, v = map(int, line[1:-1].split(','))
|
| 459 |
+
# filtration[current_value].append((u, v))
|
| 460 |
+
# except:
|
| 461 |
+
# print(f"Cannot parse edge: {line}")
|
| 462 |
+
# return filtration
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
# def extract_structure_identification(self, answer: str) -> Dict[str, Any]:
|
| 466 |
+
# """Extract information from topology structure identification answer"""
|
| 467 |
+
# result = {
|
| 468 |
+
# "cavities": [],
|
| 469 |
+
# "temporal_evolution": {}
|
| 470 |
+
# }
|
| 471 |
+
|
| 472 |
+
# # Extract cavity information
|
| 473 |
+
# if "2-DIMENSIONAL CAVITIES:" in answer:
|
| 474 |
+
# cavities_section = self._extract_section(
|
| 475 |
+
# answer, "2-DIMENSIONAL CAVITIES:", "TEMPORAL EVOLUTION:"
|
| 476 |
+
# )
|
| 477 |
+
# result["cavities"] = self._extract_cavities(cavities_section)
|
| 478 |
+
|
| 479 |
+
# # Extract temporal evolution
|
| 480 |
+
# if "TEMPORAL EVOLUTION:" in answer:
|
| 481 |
+
# evolution_section = answer.split("TEMPORAL EVOLUTION:")[1]
|
| 482 |
+
# result["temporal_evolution"] = self._extract_temporal_evolution(evolution_section)
|
| 483 |
+
|
| 484 |
+
# return result
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
# def extract_simplex_structure_identification(self, answer: str) -> Dict[str, Any]:
|
| 488 |
+
# """Extract information from simplex structure identification answer"""
|
| 489 |
+
# result = {
|
| 490 |
+
# "simplex_count": 0
|
| 491 |
+
# }
|
| 492 |
+
|
| 493 |
+
# lines = answer.strip().split('\n')
|
| 494 |
+
# for line in lines:
|
| 495 |
+
# line = line.strip()
|
| 496 |
+
# if line.startswith('2维单纯形数量:'):
|
| 497 |
+
# count_str = line.split(':')[1].strip()
|
| 498 |
+
# try:
|
| 499 |
+
# result["simplex_count"] = int(count_str)
|
| 500 |
+
# except ValueError:
|
| 501 |
+
# # Keep default value 0 if cannot parse as integer
|
| 502 |
+
# pass
|
| 503 |
+
|
| 504 |
+
# return result
|
| 505 |
+
|
| 506 |
+
# def _extract_section(self, text: str, start_marker: str, end_marker: str) -> str:
|
| 507 |
+
# """Extract text between two markers"""
|
| 508 |
+
# if start_marker in text and end_marker in text:
|
| 509 |
+
# start_idx = text.find(start_marker) + len(start_marker)
|
| 510 |
+
# end_idx = text.find(end_marker)
|
| 511 |
+
# return text[start_idx:end_idx].strip()
|
| 512 |
+
# return ""
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
# def _extract_list(self, text: str) -> List:
|
| 518 |
+
# """Extract list from text"""
|
| 519 |
+
# items = text.split(':')[1].strip()
|
| 520 |
+
# if items.startswith('[') and items.endswith(']'):
|
| 521 |
+
# return eval(items)
|
| 522 |
+
# return []
|
| 523 |
+
|
| 524 |
+
# def _extract_feature_info(self, line: str) -> Dict[str, Any]:
|
| 525 |
+
# """Extract feature information from text"""
|
| 526 |
+
# info = {}
|
| 527 |
+
# if 'Birth time:' in line:
|
| 528 |
+
# info['birth'] = float(line.split(':')[1].strip())
|
| 529 |
+
# elif 'Death time:' in line:
|
| 530 |
+
# info['death'] = float(line.split(':')[1].strip())
|
| 531 |
+
# elif 'Persistence:' in line:
|
| 532 |
+
# info['persistence'] = float(line.split(':')[1].strip())
|
| 533 |
+
# elif 'Description:' in line:
|
| 534 |
+
# info['description'] = line.split(':')[1].strip()
|
| 535 |
+
# return info
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
# def _extract_cavities(self, text: str) -> List[Dict[str, Any]]:
|
| 539 |
+
# """Extract cavity information"""
|
| 540 |
+
# cavities = []
|
| 541 |
+
# current_cavity = None
|
| 542 |
+
|
| 543 |
+
# for line in text.split('\n'):
|
| 544 |
+
# if line.startswith('Cavity'):
|
| 545 |
+
# if current_cavity:
|
| 546 |
+
# cavities.append(current_cavity)
|
| 547 |
+
# current_cavity = {}
|
| 548 |
+
# elif current_cavity is not None and line.startswith('-'):
|
| 549 |
+
# key = line.split(':')[0].strip('- ').lower()
|
| 550 |
+
# value = line.split(':')[1].strip()
|
| 551 |
+
# if key in ['birth threshold', 'death threshold', 'persistence']:
|
| 552 |
+
# value = float(value)
|
| 553 |
+
# elif key in ['nodes', 'edges']:
|
| 554 |
+
# value = eval(value)
|
| 555 |
+
# current_cavity[key] = value
|
| 556 |
+
|
| 557 |
+
# if current_cavity:
|
| 558 |
+
# cavities.append(current_cavity)
|
| 559 |
+
|
| 560 |
+
# return cavities
|
| 561 |
+
|
| 562 |
+
# def _extract_temporal_evolution(self, text: str) -> Dict[float, Dict[str, List[int]]]:
|
| 563 |
+
# """Extract temporal evolution information"""
|
| 564 |
+
# evolution = {}
|
| 565 |
+
# current_threshold = None
|
| 566 |
+
|
| 567 |
+
# for line in text.split('\n'):
|
| 568 |
+
# if line.startswith('Threshold'):
|
| 569 |
+
# current_threshold = float(line.split()[1])
|
| 570 |
+
# evolution[current_threshold] = {
|
| 571 |
+
# 'active': [],
|
| 572 |
+
# 'new': [],
|
| 573 |
+
# 'disappeared': []
|
| 574 |
+
# }
|
| 575 |
+
# elif current_threshold is not None and line.startswith('-'):
|
| 576 |
+
# key = line.split(':')[0].strip('- ').lower()
|
| 577 |
+
# value = eval(line.split(':')[1].strip())
|
| 578 |
+
# evolution[current_threshold][key] = value
|
| 579 |
+
|
| 580 |
+
# return evolution
|
| 581 |
+
|
| 582 |
+
# def _extract_current_state(self, text: str) -> Dict[str, Any]:
|
| 583 |
+
# """Extract current state information"""
|
| 584 |
+
# state = {}
|
| 585 |
+
# for line in text.split('\n'):
|
| 586 |
+
# if line.startswith('- Number of cycles:'):
|
| 587 |
+
# state['cycles'] = int(line.split(':')[1].strip())
|
| 588 |
+
# elif line.startswith('- Cycle locations:'):
|
| 589 |
+
# state['locations'] = eval(line.split(':')[1].strip())
|
| 590 |
+
# return state
|
| 591 |
+
|
| 592 |
+
# def _extract_proposed_modifications(self, text: str) -> List[Dict[str, Any]]:
|
| 593 |
+
# """Extract proposed modifications"""
|
| 594 |
+
# modifications = []
|
| 595 |
+
# current_mod = None
|
| 596 |
+
|
| 597 |
+
# for line in text.split('\n'):
|
| 598 |
+
# if line.startswith('Modification'):
|
| 599 |
+
# if current_mod:
|
| 600 |
+
# modifications.append(current_mod)
|
| 601 |
+
# current_mod = {}
|
| 602 |
+
# elif current_mod is not None and line.startswith('-'):
|
| 603 |
+
# key = line.split(':')[0].strip('- ').lower()
|
| 604 |
+
# value = line.split(':')[1].strip()
|
| 605 |
+
# if key == 'new edge':
|
| 606 |
+
# value = tuple(map(int, value.split('-')))
|
| 607 |
+
# elif key == 'expected new cycles':
|
| 608 |
+
# value = eval(value)
|
| 609 |
+
# current_mod[key] = value
|
| 610 |
+
|
| 611 |
+
# if current_mod:
|
| 612 |
+
# modifications.append(current_mod)
|
| 613 |
+
|
| 614 |
+
# return modifications
|
| 615 |
+
|
| 616 |
+
# def _extract_expected_outcome(self, text: str) -> Dict[str, Any]:
|
| 617 |
+
# """Extract expected outcome"""
|
| 618 |
+
# outcome = {}
|
| 619 |
+
# for line in text.split('\n'):
|
| 620 |
+
# if line.startswith('- New number of cycles:'):
|
| 621 |
+
# outcome['new_cycles'] = int(line.split(':')[1].strip())
|
| 622 |
+
# elif line.startswith('- New cycle locations:'):
|
| 623 |
+
# outcome['new_locations'] = eval(line.split(':')[1].strip())
|
| 624 |
+
# elif line.startswith('- Changes in persistence:'):
|
| 625 |
+
# outcome['persistence_changes'] = line.split(':')[1].strip()
|
| 626 |
+
# return outcome
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
|
evaluate_code/graph_embed.py
ADDED
|
@@ -0,0 +1,583 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 4 |
+
self.embed_type = "text" # Fixed as text format
|
| 5 |
+
self.task_name = task_name
|
| 6 |
+
|
| 7 |
+
def embed_graph(self, graph_data):
|
| 8 |
+
"""
|
| 9 |
+
Embed graph data into prompt
|
| 10 |
+
|
| 11 |
+
Parameters:
|
| 12 |
+
- graph_data: Graph data object
|
| 13 |
+
- task_type: Task type, can be one of:
|
| 14 |
+
- "filtration_edge_construction": Filtration edge construction task
|
| 15 |
+
- "simplicial_complex_construction": Simplicial complex construction task
|
| 16 |
+
- "persistent_homology_calculation": Persistent homology calculation task
|
| 17 |
+
- "node_addition": Node addition analysis task
|
| 18 |
+
- "structure_identification": Topological structure identification task
|
| 19 |
+
- "graph_modification": Graph structure modification task
|
| 20 |
+
- "topology_interpretation": Topological feature interpretation task
|
| 21 |
+
- "vector_representation": Topological feature vectorization task
|
| 22 |
+
- "noise_robustness": Noise robustness testing task
|
| 23 |
+
|
| 24 |
+
Returns:
|
| 25 |
+
- prompt: Prompt with embedded graph data
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
if self.task_name == "S_0D":
|
| 29 |
+
return self._create_S_0D_prompt(graph_data)
|
| 30 |
+
elif self.task_name == "S_1D":
|
| 31 |
+
return self._create_S_1D_prompt(graph_data)
|
| 32 |
+
elif self.task_name == "S_Modification":
|
| 33 |
+
return self._create_S_Modification_prompt(graph_data)
|
| 34 |
+
elif self.task_name == "M_Birth":
|
| 35 |
+
return self._create_M_Birth_prompt(graph_data)
|
| 36 |
+
elif self.task_name == "M_Merge":
|
| 37 |
+
return self._create_M_Merge_prompt(graph_data)
|
| 38 |
+
elif self.task_name=="M_Filtration":
|
| 39 |
+
return self._create_M_Filtration_prompt(graph_data)
|
| 40 |
+
elif self.task_name == "H_Selection":
|
| 41 |
+
return self._create_H_Selection_prompt(graph_data)
|
| 42 |
+
elif self.task_name == "H_Generation":
|
| 43 |
+
return self._create_H_Generation_prompt(graph_data)
|
| 44 |
+
elif self.task_name == "R_Selection":
|
| 45 |
+
return self._create_R_Selection_prompt(graph_data)
|
| 46 |
+
elif self.task_name == "R_Generation":
|
| 47 |
+
return self._create_R_Generation_prompt(graph_data)
|
| 48 |
+
elif self.task_name == "R_Directly":
|
| 49 |
+
return self._create_R_Directly_prompt(graph_data)
|
| 50 |
+
# elif task_type == "P_Prediction":
|
| 51 |
+
# return self._create_truedata_predict_prompt(graph_data)
|
| 52 |
+
else:
|
| 53 |
+
raise ValueError(f"Unsupported task type: {self.task_name}")
|
| 54 |
+
|
| 55 |
+
def _create_S_0D_prompt(self, graph_data):
|
| 56 |
+
"""Create topological structure identification prompt"""
|
| 57 |
+
graph_desc = self._graph_to_text(graph_data,weight=False)
|
| 58 |
+
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Given the following graph structure:
|
| 59 |
+
Graph Structure:
|
| 60 |
+
{graph_desc}
|
| 61 |
+
|
| 62 |
+
Please calculate the number of connected component in this graph(vertex that not connected to other vertex is not a connected component).
|
| 63 |
+
And strictly answer in following format:
|
| 64 |
+
Answer:
|
| 65 |
+
connected components: n
|
| 66 |
+
(e.g.
|
| 67 |
+
Answer:
|
| 68 |
+
connected components: 3"""
|
| 69 |
+
def _create_S_1D_prompt(self, graph_data):
|
| 70 |
+
"""Create topological structure identification prompt"""
|
| 71 |
+
graph_desc = self._graph_to_text(graph_data,weight=False)
|
| 72 |
+
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Given the following graph structure:
|
| 73 |
+
Graph Structure:
|
| 74 |
+
{graph_desc}
|
| 75 |
+
Please identify if 1-dimensional features (cycle holes) exist in the graph.(triangles are not cycle holes)
|
| 76 |
+
And strictly answer in following format:
|
| 77 |
+
Answer:
|
| 78 |
+
cycle holes: n
|
| 79 |
+
(e.g.
|
| 80 |
+
Answer:
|
| 81 |
+
cycle holes: 3"""
|
| 82 |
+
|
| 83 |
+
def _create_S_Modification_prompt(self, graph_data):
|
| 84 |
+
"""Create graph structure modification prompt"""
|
| 85 |
+
graph_desc = self._graph_to_text(graph_data,weight=False)
|
| 86 |
+
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Given the following graph structure:
|
| 87 |
+
|
| 88 |
+
Graph Structure:
|
| 89 |
+
{graph_desc}
|
| 90 |
+
|
| 91 |
+
Task:
|
| 92 |
+
Please identify the connected components in the graph and add one edge to reduce the number of connected components.
|
| 93 |
+
|
| 94 |
+
You can follow these steps:
|
| 95 |
+
Step1:Please identify the connected components in the graph.
|
| 96 |
+
Step2:Please add one edge between the different connected components.
|
| 97 |
+
|
| 98 |
+
Please strictly follow the format below:
|
| 99 |
+
Answer:
|
| 100 |
+
Edge to add: [u,v]
|
| 101 |
+
(e.g.
|
| 102 |
+
Answer:
|
| 103 |
+
Edge to add: [0,3]
|
| 104 |
+
"""
|
| 105 |
+
def _create_M_Birth_prompt(self, graph_data):
|
| 106 |
+
"""Create persistent homology calculation task prompt"""
|
| 107 |
+
graph_desc = self._graph_to_text(graph_data,weight=True)
|
| 108 |
+
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Please calculate persistent homology features based on the following graph structure.
|
| 109 |
+
Graph Structure:
|
| 110 |
+
{graph_desc}
|
| 111 |
+
|
| 112 |
+
Task:Calculate persistent homology on the graph below. There are 1-dimensional persistent features; please give the birth time of the earliest-born 1-dimensional feature.
|
| 113 |
+
|
| 114 |
+
You should follow these steps:
|
| 115 |
+
Step1:Add edges to the graph according to the edge weights(from smallest to largest,and if there are multiple edges with the same weight, should add them at the same time).
|
| 116 |
+
Step2:Find the edges that first construct a cycle(Triangle is not cycle,Cycle should be at least 4 edges).
|
| 117 |
+
Step3:The birth time is the weight of the edge.
|
| 118 |
+
|
| 119 |
+
Rule:
|
| 120 |
+
The cycle cannot be filled by other edges. (e.g. If [0,1], [1,2], [2,3] already exist, adding [3,0] and [3,1] simultaneously would fill the cycle[0,1,2,3] with triangles, so it doesn't count as a birth)
|
| 121 |
+
|
| 122 |
+
Please answer in the following format:
|
| 123 |
+
|
| 124 |
+
Answer:
|
| 125 |
+
birth time:[t]
|
| 126 |
+
(e.g.
|
| 127 |
+
Answer:
|
| 128 |
+
birth time:[3])
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
def _create_M_Merge_prompt(self, graph_data):
|
| 132 |
+
"""Create persistent homology calculation task prompt"""
|
| 133 |
+
graph_desc = self._graph_to_text(graph_data,weight=True)
|
| 134 |
+
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Please calculate persistent homology features based on the following graph structure.
|
| 135 |
+
Graph Structure:
|
| 136 |
+
{graph_desc}
|
| 137 |
+
Task: There are 2 0-dimensional persistent features in the graph,and one 0-dimensional feature is dead at time t(t is a real number),please give the death time t.
|
| 138 |
+
|
| 139 |
+
You can follow these steps:
|
| 140 |
+
Step1:Add edges to the graph according to the edge weights,and record the connected components.
|
| 141 |
+
Step2:Find the edge that first connect two different connected components.
|
| 142 |
+
Step3:The death time t is the weight of the edge.
|
| 143 |
+
|
| 144 |
+
Please answer in the following format:
|
| 145 |
+
Answer:
|
| 146 |
+
death time:[t]
|
| 147 |
+
(e.g.
|
| 148 |
+
Answer:
|
| 149 |
+
death time:[4])
|
| 150 |
+
Please ensure final answer strictly follows above format.
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
def _create_M_Filtration_prompt(self,graph_data):
|
| 154 |
+
"""Create filtration_features_count task prompt"""
|
| 155 |
+
graph_desc = self._graph_to_text(graph_data,weight=True)
|
| 156 |
+
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Now filter the simplicial complex on the following graph according to the edge weights.
|
| 157 |
+
Graph Structure:
|
| 158 |
+
{graph_desc}
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
Task:Count how many connected components are present at filtration value 3?
|
| 162 |
+
|
| 163 |
+
You can follow these steps:
|
| 164 |
+
Step1:Find the edges with weight less than or equal to 3.
|
| 165 |
+
Step2:Use the edges to construct a graph.
|
| 166 |
+
Step3:Count how many connected components are present in the graph.
|
| 167 |
+
|
| 168 |
+
Rule:Vertices are only introduced into the complex when their associated edges are added.
|
| 169 |
+
|
| 170 |
+
Please answer in the following format:
|
| 171 |
+
|
| 172 |
+
Answer:
|
| 173 |
+
connected components:[n]
|
| 174 |
+
(e.g.
|
| 175 |
+
Answer:
|
| 176 |
+
connected components:[3]
|
| 177 |
+
"""
|
| 178 |
+
def _create_H_Selection_prompt(self, graph_data):
|
| 179 |
+
"""Create filtration method selection prompt"""
|
| 180 |
+
graph_desc1 = self._graph_to_text(graph_data[0],weight=True)
|
| 181 |
+
graph_desc2 = self._graph_to_text(graph_data[1],weight=True)
|
| 182 |
+
return f""""You are a mathematical expert specializing in graph theory and persistent homology. Given the following two graph structures.
|
| 183 |
+
Graph structure:
|
| 184 |
+
graph1:
|
| 185 |
+
{graph_desc1}
|
| 186 |
+
|
| 187 |
+
graph2:
|
| 188 |
+
{graph_desc2}
|
| 189 |
+
Task:Please select a filtration method from the following 6 methods that can better distinguish between the two graphs(maximizes the Wasserstein distance between their persistence barcodes).
|
| 190 |
+
The 6 methods are (all methods filter from low value to high value):
|
| 191 |
+
Weight: Edge weight.
|
| 192 |
+
Degree: Number of edges connected to a node.
|
| 193 |
+
K-shell: Core level of a node based on iterative pruning by degree.
|
| 194 |
+
Closeness Centrality: Inverse of average shortest path to all other nodes.
|
| 195 |
+
Betweenness Centrality: Frequency a node lies on shortest paths between others.
|
| 196 |
+
Eigenvector Centrality: Node importance based on connections to other important nodes.
|
| 197 |
+
|
| 198 |
+
You can follow these steps:
|
| 199 |
+
1.Analyze the graph's characteristics: Is it sparse or dense? Are there strong local clusters or more global bridge structures? Do edge weights vary significantly?
|
| 200 |
+
2.Consider what kind of topological features should be emphasized in the filtration: peripheral nodes, local clusters, bridge nodes, or strong/weak connections.
|
| 201 |
+
3.Match these needs to one of the complex filtration methods.
|
| 202 |
+
|
| 203 |
+
Your response should be in this format:
|
| 204 |
+
Answer:
|
| 205 |
+
Method: weight/degree/k_shell/closeness/betweenness/eigenvector
|
| 206 |
+
(e.g
|
| 207 |
+
Answer:
|
| 208 |
+
Method: k-shell
|
| 209 |
+
)
|
| 210 |
+
Please ensure your answer strictly follows this format.
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
def _create_H_Generation_prompt(self, graph_data):
|
| 214 |
+
"""Create filteration value selection prompt"""
|
| 215 |
+
graph_desc1 = self._graph_to_text(graph_data[0])
|
| 216 |
+
graph_desc2 = self._graph_to_text(graph_data[1])
|
| 217 |
+
filtration_values = list(range(1,int(max(max(graph_data[0]['edge_attr']),max(graph_data[1]['edge_attr'])))+1))
|
| 218 |
+
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Given the following two graph structures:
|
| 219 |
+
|
| 220 |
+
graph1 structure:
|
| 221 |
+
{graph_desc1}
|
| 222 |
+
|
| 223 |
+
graph2 structure:
|
| 224 |
+
{graph_desc2}
|
| 225 |
+
Task:Please select a filtration value sequence from [1,2,3,4,5,6,7,8,9,10] that maximizes the difference between graph 1 and graph 2(maximizes the Wasserstein distance between their persistence barcodes).
|
| 226 |
+
|
| 227 |
+
You can follow these steps:
|
| 228 |
+
Step 1:Compare the structure of graph1 and graph2 to see which is denser, whether there are cycles,etc.
|
| 229 |
+
Step 2:From the given filtration values, identify values that trigger major topological changes in the graphs.
|
| 230 |
+
Step 3:Choose 5 filtration values that maximize the difference in persistence barcodes between the two graphs(the max filtration value should be 10).
|
| 231 |
+
|
| 232 |
+
Please answer in the following format:
|
| 233 |
+
Answer:
|
| 234 |
+
filtration value: [filtration value]
|
| 235 |
+
(e.g.
|
| 236 |
+
Answer:
|
| 237 |
+
filtration value: [1,3,4,7,10]
|
| 238 |
+
)
|
| 239 |
+
Please ensure your answer strictly follows this format.
|
| 240 |
+
"""
|
| 241 |
+
|
| 242 |
+
def _create_R_Selection_prompt(self, graph_data):
|
| 243 |
+
"""Create truedata filtration method selection prompt"""
|
| 244 |
+
graph_desc1 = self._graph_to_text(graph_data[0],weight=True)
|
| 245 |
+
graph_desc2 = self._graph_to_text(graph_data[1],weight=True)
|
| 246 |
+
graph_desc3 = self._graph_to_text(graph_data[2],weight=True)
|
| 247 |
+
graph_desc4 = self._graph_to_text(graph_data[3],weight=True)
|
| 248 |
+
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Given the following 4 graph structures (two categories of graphs, each category has 2 graphs, the index of graphs are random):
|
| 249 |
+
Graph1 Structure:
|
| 250 |
+
{graph_desc1}
|
| 251 |
+
|
| 252 |
+
Graph2 Structure:
|
| 253 |
+
{graph_desc2}
|
| 254 |
+
|
| 255 |
+
Graph3 Structure:
|
| 256 |
+
{graph_desc3}
|
| 257 |
+
|
| 258 |
+
Graph4 Structure:
|
| 259 |
+
{graph_desc4}
|
| 260 |
+
|
| 261 |
+
Task:Please select a filtration method from the following 6 methods that can classify the graph into 2 categories(each category has 2 graphs).
|
| 262 |
+
|
| 263 |
+
The 6 methods are (all methods filter from low value to high value):
|
| 264 |
+
Degree: Number of edges connected to a node.
|
| 265 |
+
Weight: Edge weight.
|
| 266 |
+
K-shell: Core level of a node based on iterative pruning by degree.
|
| 267 |
+
Closeness Centrality: Inverse of average shortest path to all other nodes.
|
| 268 |
+
Betweenness Centrality: Frequency a node lies on shortest paths between others.
|
| 269 |
+
Eigenvector Centrality: Node importance based on connections to other important nodes.
|
| 270 |
+
|
| 271 |
+
Your selection should be the method that can maximize the difference in persistence barcodes between the two categories and minimize the difference in persistence barcodes within the same category.
|
| 272 |
+
|
| 273 |
+
Please answer in the following format:
|
| 274 |
+
Answer:
|
| 275 |
+
Method: weight/degree/k-shell/closeness/betweenness/eigenvector
|
| 276 |
+
(e.g.
|
| 277 |
+
Answer:
|
| 278 |
+
Method: k-shell
|
| 279 |
+
)
|
| 280 |
+
Please ensure your answer strictly follows this format.
|
| 281 |
+
"""
|
| 282 |
+
|
| 283 |
+
def _create_R_Generation_prompt(self, graph_data):
|
| 284 |
+
"""Create truedata filteration value selection prompt"""
|
| 285 |
+
graph_desc1 = self._graph_to_text(graph_data[0],weight=True)
|
| 286 |
+
graph_desc2 = self._graph_to_text(graph_data[1],weight=True)
|
| 287 |
+
graph_desc3 = self._graph_to_text(graph_data[2],weight=True)
|
| 288 |
+
graph_desc4 = self._graph_to_text(graph_data[3],weight=True)
|
| 289 |
+
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Given the following 4 graph structures (two categories of graphs, each category 2 graphs, the index of graphs are random):
|
| 290 |
+
Graph1 Structure:
|
| 291 |
+
{graph_desc1}
|
| 292 |
+
|
| 293 |
+
Graph2 Structure:
|
| 294 |
+
{graph_desc2}
|
| 295 |
+
|
| 296 |
+
Graph3 Structure:
|
| 297 |
+
{graph_desc3}
|
| 298 |
+
|
| 299 |
+
Graph4 Structure:
|
| 300 |
+
{graph_desc4}
|
| 301 |
+
|
| 302 |
+
Task:Please select a filtration value sequence that can classify the graph into 2 categories(the persistence barcodes of the two different categories should be as different as possible and the same category should have similar persistence barcodes).
|
| 303 |
+
|
| 304 |
+
You can follow these steps:
|
| 305 |
+
Step1:Compare the structure of 4 graphs.
|
| 306 |
+
Step2:Choose filtration values sequence (from 0 to 1,sequence length not less than 2) that can maximize the difference in persistence barcodes between the two categories and minimize the difference in persistence barcodes within the same category.
|
| 307 |
+
|
| 308 |
+
Please answer in the following format:
|
| 309 |
+
Answer:
|
| 310 |
+
Filtration value: [filtration values]
|
| 311 |
+
(e.g.
|
| 312 |
+
Answer:
|
| 313 |
+
Filtration value: [0.1,0.4,0.5,0.6,0.9,1]
|
| 314 |
+
)
|
| 315 |
+
Please ensure your answer strictly follows this format.
|
| 316 |
+
"""
|
| 317 |
+
|
| 318 |
+
def _create_filtration_edge_construction_prompt(self, graph_data):
|
| 319 |
+
"""Create filtration edge construction task prompt"""
|
| 320 |
+
graph_desc = self._graph_to_text(graph_data)
|
| 321 |
+
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Please construct a filtration edge sequence based on the following graph structure.
|
| 322 |
+
|
| 323 |
+
Graph Structure:
|
| 324 |
+
{graph_desc}
|
| 325 |
+
|
| 326 |
+
Task: Construct filtration edges from the original edge list.
|
| 327 |
+
(e.g. Graph structure [0,1,3],[0,2,1],[1,3,2],[1,4,2],[2,3,3]
|
| 328 |
+
Filtration edge sequence:
|
| 329 |
+
Filtration value: 1
|
| 330 |
+
[0,2]
|
| 331 |
+
Filtration value: 2
|
| 332 |
+
[1,3],[1,4]
|
| 333 |
+
Filtration value: 3
|
| 334 |
+
[0,1],[2,3] )
|
| 335 |
+
Please strictly follow these steps:
|
| 336 |
+
1. First sort the original edge list by weight in ascending order
|
| 337 |
+
2. Divide edges added at each filtration value
|
| 338 |
+
|
| 339 |
+
Please answer in the following format:
|
| 340 |
+
|
| 341 |
+
===FILTRATION_START===
|
| 342 |
+
For each different edge weight, list the edges added at that weight, format as:
|
| 343 |
+
|
| 344 |
+
**Value=1**
|
| 345 |
+
(1,2)
|
| 346 |
+
|
| 347 |
+
**Value=2**
|
| 348 |
+
(1,3)
|
| 349 |
+
|
| 350 |
+
**Value=3**
|
| 351 |
+
(2,3)
|
| 352 |
+
|
| 353 |
+
...continue for other weights
|
| 354 |
+
===FILTRATION_END===
|
| 355 |
+
|
| 356 |
+
Please ensure strict adherence to the above format. Do not add extra explanations, only include content required by the format
|
| 357 |
+
"""
|
| 358 |
+
|
| 359 |
+
def _create_R_Directly_prompt(self, graph_data):
|
| 360 |
+
"""Create truedata classfy prompt"""
|
| 361 |
+
graph_desc1 = self._graph_to_text(graph_data[0],weight=True)
|
| 362 |
+
graph_desc2 = self._graph_to_text(graph_data[1],weight=True)
|
| 363 |
+
graph_desc3 = self._graph_to_text(graph_data[2],weight=True)
|
| 364 |
+
graph_desc4 = self._graph_to_text(graph_data[3],weight=True)
|
| 365 |
+
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Given the following 4 graph structures(two categories of graphs, each category has 2 graphs, the index of graphs are random):
|
| 366 |
+
|
| 367 |
+
Graph1 Structure:
|
| 368 |
+
{graph_desc1}
|
| 369 |
+
|
| 370 |
+
Graph2 Structure:
|
| 371 |
+
{graph_desc2}
|
| 372 |
+
|
| 373 |
+
Graph3 Structure:
|
| 374 |
+
{graph_desc3}
|
| 375 |
+
|
| 376 |
+
Graph4 Structure:
|
| 377 |
+
{graph_desc4}
|
| 378 |
+
|
| 379 |
+
Task:Please classify them into 2 categories(each category has 2 graphs) according to their topological structure.
|
| 380 |
+
|
| 381 |
+
Please answer in the following format:
|
| 382 |
+
Answer:
|
| 383 |
+
Category: [category1 graph index,category2 graph index]
|
| 384 |
+
(e.g.
|
| 385 |
+
Answer:
|
| 386 |
+
Category: [[1,3],[2,4]])
|
| 387 |
+
Please ensure your answer strictly follows this format.
|
| 388 |
+
"""
|
| 389 |
+
|
| 390 |
+
def _graph_to_text(self, graph_data, weight=True, sort=True):
|
| 391 |
+
"""图结构文本转换"""
|
| 392 |
+
num_nodes = graph_data['num_nodes']
|
| 393 |
+
num_edges = graph_data['num_edges']
|
| 394 |
+
edge_index = graph_data['edge_index']
|
| 395 |
+
|
| 396 |
+
# 收集所有边及其权重
|
| 397 |
+
edges = []
|
| 398 |
+
for i in range(0, len(edge_index), 2):
|
| 399 |
+
src = edge_index[i]
|
| 400 |
+
dst = edge_index[i + 1]
|
| 401 |
+
if weight:
|
| 402 |
+
weight_val = 1.0 # 默认权重为1
|
| 403 |
+
else:
|
| 404 |
+
weight_val = 1.0
|
| 405 |
+
edges.append((weight_val, src, dst))
|
| 406 |
+
|
| 407 |
+
if sort:
|
| 408 |
+
edges.sort(key=lambda x: x[0])
|
| 409 |
+
|
| 410 |
+
# Generate text
|
| 411 |
+
text = f"Graph with {num_nodes} nodes and {num_edges} edges:\n"
|
| 412 |
+
if weight:
|
| 413 |
+
for weight_val, src, dst in edges:
|
| 414 |
+
text += f"Node {src}-[{weight_val:.2f}]-Node {dst}\n"
|
| 415 |
+
else:
|
| 416 |
+
for weight_val, src, dst in edges:
|
| 417 |
+
text += f"Node {src}-Node {dst}\n"
|
| 418 |
+
return text
|
| 419 |
+
|
| 420 |
+
def _filt_edges_to_text(self, graph_data,sort=True):
|
| 421 |
+
"""Convert filtration complex to text"""
|
| 422 |
+
num_nodes = graph_data['num_nodes']
|
| 423 |
+
num_edges = graph_data['num_edges']
|
| 424 |
+
edge_index = graph_data['edge_index']
|
| 425 |
+
|
| 426 |
+
edges = []
|
| 427 |
+
for i in range(edge_index.shape[1]):
|
| 428 |
+
src = edge_index[0, i].item()
|
| 429 |
+
dst = edge_index[1, i].item()
|
| 430 |
+
if hasattr(graph_data, 'edge_attr') and graph_data.edge_attr is not None:
|
| 431 |
+
weight = graph_data.edge_attr[i].item()
|
| 432 |
+
else:
|
| 433 |
+
weight = 1.0
|
| 434 |
+
edges.append((weight, src, dst))
|
| 435 |
+
|
| 436 |
+
if sort:
|
| 437 |
+
edges.sort(key=lambda x: x[0])
|
| 438 |
+
|
| 439 |
+
# Generate text
|
| 440 |
+
text = f"Graph with {num_nodes} nodes and {num_edges} edges:\n"
|
| 441 |
+
for weight, src, dst in edges:
|
| 442 |
+
text += f"Node {src}-[{weight:.2f}]-Node {dst}\n"
|
| 443 |
+
return text
|
| 444 |
+
def _complex_to_text(self, graph_data):
|
| 445 |
+
"""Complex structure description"""
|
| 446 |
+
simplex = graph_data.task_simplex[0]
|
| 447 |
+
dim = len(simplex) - 1
|
| 448 |
+
verts = ", ".join(str(v) for v in simplex)
|
| 449 |
+
|
| 450 |
+
if dim == 0:
|
| 451 |
+
desc = f"vertex {verts}"
|
| 452 |
+
elif dim == 1:
|
| 453 |
+
a, b = simplex
|
| 454 |
+
desc = f"edge between {a} and {b}"
|
| 455 |
+
elif dim == 2:
|
| 456 |
+
a, b, c = simplex
|
| 457 |
+
desc = f"triangle with vertices {a}, {b}, {c}"
|
| 458 |
+
else:
|
| 459 |
+
desc = f"{dim}-simplex spanning vertices {verts}"
|
| 460 |
+
|
| 461 |
+
text = f"aim simplex: {desc}"
|
| 462 |
+
return text
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def _ph_to_text(self, ph_data):
|
| 466 |
+
"""Persistent homology barcode description"""
|
| 467 |
+
text = ""
|
| 468 |
+
for dim in ['0dim', '1dim']:
|
| 469 |
+
if dim in ph_data:
|
| 470 |
+
text += f"\n{dim} features:\n"
|
| 471 |
+
for i, (birth, death) in enumerate(ph_data[dim]):
|
| 472 |
+
persistence = death - birth
|
| 473 |
+
text += f"Feature {i}: birth {birth:.2f}, death {death:.2f}, persistence {persistence:.2f}\n"
|
| 474 |
+
return text
|
| 475 |
+
|
| 476 |
+
# def _create_simplicial_complex_construction_prompt(self, graph_data):
|
| 477 |
+
# """Create simplicial complex construction task prompt"""
|
| 478 |
+
# filt_edges_desc = self._filt_edges_to_text(graph_data)
|
| 479 |
+
# return f"""You are a mathematical expert specializing in graph theory and persistent homology. Please construct a simplicial complex sequence based on the following filtration edge sequence.
|
| 480 |
+
|
| 481 |
+
# Filtration Edge Sequence:
|
| 482 |
+
# {filt_edges_desc}
|
| 483 |
+
|
| 484 |
+
# Task: Build complex sequence (2-dimensional simplex) from filtration edge list.
|
| 485 |
+
|
| 486 |
+
# Please strictly follow these steps:
|
| 487 |
+
# 1. For each filtration value, build a complex containing that filtration value and all previous filtration values
|
| 488 |
+
# 2. Record new 2-dimensional simplices appearing at each filtration value (e.g. filtration value 1: [1,2],[2,3] filtration value 2: [1,3] appears 2-dimensional simplex [(1,2,3),2])
|
| 489 |
+
|
| 490 |
+
# Please answer in the following format:
|
| 491 |
+
# List simplicial complexes [(complex),filtration value]:
|
| 492 |
+
# ===SIMPLICIAL_COMPLEX_START===
|
| 493 |
+
|
| 494 |
+
# [(0,1,2),3]
|
| 495 |
+
# [(0,1,4),3]
|
| 496 |
+
# [(0,3,4),4]
|
| 497 |
+
# ...
|
| 498 |
+
# ===SIMPLICIAL_COMPLEX_END===
|
| 499 |
+
|
| 500 |
+
# Note:
|
| 501 |
+
# - 0-dimensional simplices are omitted, only list 1-dimensional and 2-dimensional simplices
|
| 502 |
+
# - 2-dimensional simplex is a triangle formed by three edges (all edge feature values are less than or equal to filtration value)
|
| 503 |
+
|
| 504 |
+
# Please ensure strict adherence to the above format. Do not add extra explanations, only include content required by the format
|
| 505 |
+
# """
|
| 506 |
+
|
| 507 |
+
# def _create_filteration_value_change_prompt(self, graph_data):
|
| 508 |
+
# edge_str = "graph structure:\n"
|
| 509 |
+
# edge_str += self._filt_edges_to_text(graph_data)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
# pd_str = "current persistent homology results:\n"
|
| 513 |
+
# pd_str += self._ph_to_text(graph_data.vr_10_pd)
|
| 514 |
+
|
| 515 |
+
# question = f"""graph structure:{edge_str}
|
| 516 |
+
# current persistent homology results:{pd_str}
|
| 517 |
+
# if we reduce the filtration step from 10 to 5(filtration value[2,4,6,8,10]), will the number of 0-dimensional persistent features decrease?
|
| 518 |
+
|
| 519 |
+
# Please answer in the following format:
|
| 520 |
+
# Answer:
|
| 521 |
+
# Yes/No
|
| 522 |
+
# (e.g.
|
| 523 |
+
# Answer:
|
| 524 |
+
# Yes
|
| 525 |
+
# )
|
| 526 |
+
# """
|
| 527 |
+
|
| 528 |
+
# return question
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
# def _create_truedata_predict_prompt(self, graph_data):
|
| 539 |
+
# """Create truedata predict prompt"""
|
| 540 |
+
# graph_desc1 = self._graph_to_text(graph_data[0],weight=True)
|
| 541 |
+
# graph_desc2 = self._graph_to_text(graph_data[1],weight=True)
|
| 542 |
+
# graph_desc3 = self._graph_to_text(graph_data[2],weight=True)
|
| 543 |
+
# graph_desc4 = self._graph_to_text(graph_data[3],weight=True)
|
| 544 |
+
# graph_desc5 = self._graph_to_text(graph_data[4],weight=True)
|
| 545 |
+
# graph_desc6 = self._graph_to_text(graph_data[5],weight=True)
|
| 546 |
+
# graph_desc7 = self._graph_to_text(graph_data[6],weight=True)
|
| 547 |
+
# closing_price = [graph_data[0].y,graph_data[1].y,graph_data[2].y,graph_data[3].y,graph_data[4].y,graph_data[5].y,graph_data[6].y]
|
| 548 |
+
# return f"""You are a mathematical expert specializing in graph theory and persistent homology. Given the following seven-day ETH trading network and closing prices:
|
| 549 |
+
|
| 550 |
+
# day1:
|
| 551 |
+
# {graph_desc1}
|
| 552 |
+
|
| 553 |
+
# day2:
|
| 554 |
+
# {graph_desc2}
|
| 555 |
+
|
| 556 |
+
# day3:
|
| 557 |
+
# {graph_desc3}
|
| 558 |
+
|
| 559 |
+
# day4:
|
| 560 |
+
# {graph_desc4}
|
| 561 |
+
|
| 562 |
+
# day5:
|
| 563 |
+
# {graph_desc5}
|
| 564 |
+
|
| 565 |
+
# day6:
|
| 566 |
+
# {graph_desc6}
|
| 567 |
+
|
| 568 |
+
# day7:
|
| 569 |
+
# {graph_desc7}
|
| 570 |
+
|
| 571 |
+
# closing price list(from day):{closing_price}
|
| 572 |
+
|
| 573 |
+
# Task:Please predict the closing price of day8.
|
| 574 |
+
|
| 575 |
+
# Please answer in the following format:
|
| 576 |
+
# Answer:
|
| 577 |
+
# Closing price: [closing price]
|
| 578 |
+
# (e.g.
|
| 579 |
+
# Answer:
|
| 580 |
+
# Closing price: 1000
|
| 581 |
+
# )
|
| 582 |
+
# Please ensure your answer strictly follows this format.
|
| 583 |
+
# """
|
evaluate_code/llm_api.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from openai import OpenAI
|
| 3 |
+
from anthropic import Anthropic
|
| 4 |
+
import google.generativeai as genai
|
| 5 |
+
import requests
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
load_dotenv()
|
| 9 |
+
|
| 10 |
+
class LLMCaller:
|
| 11 |
+
def __init__(self, model_name: str = "gpt-4.1-mini-2025-04-14"):
|
| 12 |
+
"""
|
| 13 |
+
Initialize LLM model with unified interface
|
| 14 |
+
|
| 15 |
+
Parameters:
|
| 16 |
+
- model_name: Model name to use, defaults to "gpt-4.1-mini-2025-04-14"
|
| 17 |
+
"""
|
| 18 |
+
self.model_name = model_name
|
| 19 |
+
self._setup_model()
|
| 20 |
+
|
| 21 |
+
def _setup_model(self):
|
| 22 |
+
"""Setup model configuration based on model name"""
|
| 23 |
+
if self.model_name.startswith("gpt"):
|
| 24 |
+
self.client = OpenAI(
|
| 25 |
+
api_key=os.getenv("OPENAI_API_KEY"),
|
| 26 |
+
base_url="https://api.openai.com/v1"
|
| 27 |
+
)
|
| 28 |
+
self.api_type = "openai"
|
| 29 |
+
elif self.model_name.startswith("claude"):
|
| 30 |
+
self.client = Anthropic(
|
| 31 |
+
api_key=os.getenv("ANTHROPIC_API_KEY")
|
| 32 |
+
)
|
| 33 |
+
self.api_type = "anthropic"
|
| 34 |
+
elif self.model_name.startswith("deepseek"):
|
| 35 |
+
self.api_key = os.getenv("DEEPSEEK_API_KEY")
|
| 36 |
+
self.api_url = "https://api.deepseek.com/v1/chat/completions"
|
| 37 |
+
self.api_type = "deepseek"
|
| 38 |
+
elif self.model_name.startswith("gemini"):
|
| 39 |
+
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
| 40 |
+
self.model = genai.GenerativeModel(self.model_name)
|
| 41 |
+
self.api_type = "gemini"
|
| 42 |
+
elif self.model_name in ["llama-3-70b", "mixtral-8x7b", "qwen-72b"]:
|
| 43 |
+
self.api_url = "http://localhost:8000/v1"
|
| 44 |
+
self.api_type = "local"
|
| 45 |
+
else:
|
| 46 |
+
raise ValueError(f"Unsupported model: {self.model_name}")
|
| 47 |
+
|
| 48 |
+
def call(self, prompt: str) -> str:
|
| 49 |
+
"""
|
| 50 |
+
Call LLM API with a single prompt
|
| 51 |
+
|
| 52 |
+
Parameters:
|
| 53 |
+
- prompt: Input prompt string
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
- response: Model's response
|
| 57 |
+
"""
|
| 58 |
+
try:
|
| 59 |
+
if self.api_type == "openai":
|
| 60 |
+
response = self.client.chat.completions.create(
|
| 61 |
+
model=self.model_name,
|
| 62 |
+
messages=[
|
| 63 |
+
{"role": "system", "content": "You are a mathematical expert specializing in graph theory and persistent homology."},
|
| 64 |
+
{"role": "user", "content": prompt}
|
| 65 |
+
]
|
| 66 |
+
)
|
| 67 |
+
return response.choices[0].message.content
|
| 68 |
+
|
| 69 |
+
elif self.api_type == "anthropic":
|
| 70 |
+
response = self.client.messages.create(
|
| 71 |
+
model=self.model_name,
|
| 72 |
+
system="You are a helpful assistant.",
|
| 73 |
+
messages=[{"role": "user", "content": prompt}]
|
| 74 |
+
)
|
| 75 |
+
return response.content[0].text
|
| 76 |
+
|
| 77 |
+
elif self.api_type == "deepseek":
|
| 78 |
+
headers = {
|
| 79 |
+
"Authorization": f"Bearer {self.api_key}",
|
| 80 |
+
"Content-Type": "application/json"
|
| 81 |
+
}
|
| 82 |
+
data = {
|
| 83 |
+
"model": self.model_name,
|
| 84 |
+
"messages": [
|
| 85 |
+
{"role": "user", "content": "/no_think" + prompt}
|
| 86 |
+
]
|
| 87 |
+
}
|
| 88 |
+
response = requests.post(self.api_url, headers=headers, json=data)
|
| 89 |
+
response.raise_for_status()
|
| 90 |
+
return response.json()["choices"][0]["message"]["content"]
|
| 91 |
+
|
| 92 |
+
elif self.api_type == "gemini":
|
| 93 |
+
response = self.model.generate_content(prompt)
|
| 94 |
+
return response.text
|
| 95 |
+
|
| 96 |
+
elif self.api_type == "local":
|
| 97 |
+
data = {
|
| 98 |
+
"model": self.model_name,
|
| 99 |
+
"messages": [
|
| 100 |
+
{"role": "user", "content": prompt}
|
| 101 |
+
]
|
| 102 |
+
}
|
| 103 |
+
response = requests.post(self.api_url, json=data)
|
| 104 |
+
response.raise_for_status()
|
| 105 |
+
return response.json()["choices"][0]["message"]["content"]
|
| 106 |
+
|
| 107 |
+
except Exception as e:
|
| 108 |
+
print(f"Error calling {self.model_name} API: {e}")
|
| 109 |
+
return f"API call error: {str(e)}"
|
| 110 |
+
|
| 111 |
+
def batch_call(self, prompts: list[str]) -> list[str]:
|
| 112 |
+
"""
|
| 113 |
+
Batch call LLM API with multiple prompts
|
| 114 |
+
|
| 115 |
+
Parameters:
|
| 116 |
+
- prompts: List of input prompts
|
| 117 |
+
|
| 118 |
+
Returns:
|
| 119 |
+
- responses: List of model responses
|
| 120 |
+
"""
|
| 121 |
+
responses = []
|
| 122 |
+
for idx, prompt in enumerate(prompts, start=1):
|
| 123 |
+
print(f"Processing prompt {idx}/{len(prompts)}")
|
| 124 |
+
response = self.call(prompt)
|
| 125 |
+
responses.append(response)
|
| 126 |
+
return responses
|
evaluate_code/llm_evaluator.py
ADDED
|
@@ -0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from evaluate_code.load_datasets import load_data
|
| 3 |
+
from evaluate_code.graph_embed import GraphEmbedder
|
| 4 |
+
from evaluate_code.extract import AnswerExtractor
|
| 5 |
+
from evaluate_code.llm_api import LLMCaller
|
| 6 |
+
from evaluate_code.evaluate import Evaluator
|
| 7 |
+
TASK_DATASET_MAPPING = {
|
| 8 |
+
# Simple Tasks
|
| 9 |
+
"S_0D": "datasets/Simple_Tasks/0D_Component_Counting", # 0D component counting
|
| 10 |
+
"S_1D": "datasets/Simple_Tasks/1D_Simplex_Counting", # 1D simplex counting
|
| 11 |
+
"S_Modification": "datasets/Simple_Tasks/Component_Reduction", # Component reduction task
|
| 12 |
+
|
| 13 |
+
# Medium Tasks
|
| 14 |
+
"M_Merge": "datasets/Medium_Tasks/Component_Merge_Time", # Persistent homology calculation
|
| 15 |
+
"M_Birth": "datasets/Medium_Tasks/Simplex_Birth_Time", # Birth time calculation
|
| 16 |
+
"M_Filtration": "datasets/Medium_Tasks/Component_Count_Under_Filtration", # Filtration feature counting
|
| 17 |
+
|
| 18 |
+
# Hard Tasks
|
| 19 |
+
"H_Selection": "datasets/Hard_Tasks/Optimal_Filtration_Selection", # Filtration method selection
|
| 20 |
+
"H_Generation": "datasets/Hard_Tasks/Non-Uniform_Filtration_Generation", # Filtration value selection
|
| 21 |
+
|
| 22 |
+
# Real World Tasks
|
| 23 |
+
"R_Selection": "datasets/Real_World_Tasks/Filtration_Selection_for_Classification", # Real data filtration method selection
|
| 24 |
+
"R_Generation": "datasets/Real_World_Tasks/Filtration_Sequence_Generation_for_Classification", # Real data filtration value selection
|
| 25 |
+
"R_Directly": "datasets/Real_World_Tasks/Direct_Classification" # Direct classification
|
| 26 |
+
}
|
| 27 |
+
class LLMEvaluator:
|
| 28 |
+
def __init__(self, task_name, model_name="gpt-4o"):
|
| 29 |
+
"""
|
| 30 |
+
Initialize LLM evaluator
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
dataset_name (str): Name of the dataset to evaluate
|
| 34 |
+
model_name (str): Name of the model to use
|
| 35 |
+
"""
|
| 36 |
+
self.task_name = task_name
|
| 37 |
+
|
| 38 |
+
# Initialize LLM caller
|
| 39 |
+
self.llm_caller = LLMCaller(model_name)
|
| 40 |
+
|
| 41 |
+
# Initialize graph embedder and evaluator
|
| 42 |
+
self.graph_embedder = GraphEmbedder(self.task_name)
|
| 43 |
+
self.extractor = AnswerExtractor(self.task_name)
|
| 44 |
+
self.evaluator = Evaluator(self.task_name)
|
| 45 |
+
|
| 46 |
+
# Load dataset
|
| 47 |
+
self.dataset = self._load_dataset()
|
| 48 |
+
|
| 49 |
+
def _load_dataset(self):
|
| 50 |
+
"""Load dataset based on task name"""
|
| 51 |
+
dataset_path = TASK_DATASET_MAPPING[self.task_name]
|
| 52 |
+
data = {}
|
| 53 |
+
|
| 54 |
+
# Check if path exists
|
| 55 |
+
if not os.path.exists(dataset_path):
|
| 56 |
+
raise FileNotFoundError(f"Dataset path not found: {dataset_path}")
|
| 57 |
+
|
| 58 |
+
# Load all files in the dataset directory
|
| 59 |
+
for file_name in os.listdir(dataset_path):
|
| 60 |
+
file_path = os.path.join(dataset_path, file_name)
|
| 61 |
+
if os.path.isfile(file_path):
|
| 62 |
+
file_data = load_data(file_path)
|
| 63 |
+
data[file_name] = file_data
|
| 64 |
+
return data
|
| 65 |
+
|
| 66 |
+
def process_single_data(self, graph_data):
|
| 67 |
+
"""
|
| 68 |
+
Process a single graph through the complete pipeline:
|
| 69 |
+
1. Generate prompt
|
| 70 |
+
2. Get LLM response
|
| 71 |
+
3. Extract and evaluate answer
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
graph_data: A single graph data object
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
dict: Dictionary containing:
|
| 78 |
+
- prompt: Generated prompt
|
| 79 |
+
- response: Raw LLM response
|
| 80 |
+
- extracted_answer: Processed answer
|
| 81 |
+
- evaluation: Evaluation results
|
| 82 |
+
"""
|
| 83 |
+
# try:
|
| 84 |
+
# Step 1: Generate prompt for single graph
|
| 85 |
+
prompt = self.graph_embedder.embed_graph(graph_data)
|
| 86 |
+
|
| 87 |
+
# Step 2: Get LLM response
|
| 88 |
+
response = self.llm_caller.call(prompt)
|
| 89 |
+
|
| 90 |
+
# Step 3: Extract answer
|
| 91 |
+
extracted_answer = self.extractor.extract_answers(response)
|
| 92 |
+
|
| 93 |
+
return extracted_answer
|
| 94 |
+
|
| 95 |
+
def process_dataset(self):
|
| 96 |
+
"""
|
| 97 |
+
Process all graphs in all parquet files in the dataset.
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
list: List of results for each file, where each file's results is a list of results for each graph
|
| 101 |
+
"""
|
| 102 |
+
all_results = {}
|
| 103 |
+
if self.task_name in ["S_0D", "S_1D", "S_Modification", "M_Merge", "M_Birth", "M_Filtration"]:
|
| 104 |
+
# Process each parquet file in the dataset
|
| 105 |
+
for file_idx, (file_name, file_data) in enumerate(self.dataset.items()):
|
| 106 |
+
print(f"\nProcessing file {file_idx + 1}/{len(self.dataset)}")
|
| 107 |
+
|
| 108 |
+
# Process each graph in the current file (DataFrame)
|
| 109 |
+
graph_datas = []
|
| 110 |
+
answers = []
|
| 111 |
+
for idx, row in file_data.iterrows():
|
| 112 |
+
# if idx >= 3: # Only process first 3 graphs
|
| 113 |
+
# break
|
| 114 |
+
print(f"Processing graph {idx + 1}/{len(file_data)} in file {file_idx + 1}")
|
| 115 |
+
|
| 116 |
+
# Convert DataFrame row to dict
|
| 117 |
+
graph_data = row.to_dict()
|
| 118 |
+
graph_datas.append(graph_data)
|
| 119 |
+
answer = self.process_single_data(graph_data)
|
| 120 |
+
answers.append(answer)
|
| 121 |
+
evaluation = self.evaluator.evaluate(graph_datas, answers)
|
| 122 |
+
all_results[file_name] = evaluation
|
| 123 |
+
|
| 124 |
+
return all_results
|
| 125 |
+
elif self.task_name in ["H_Selection", "H_Generation"]:
|
| 126 |
+
# Process each parquet file in the dataset
|
| 127 |
+
for file_idx, (file_name, file_data) in enumerate(self.dataset.items()):
|
| 128 |
+
print(f"\nProcessing file {file_idx + 1}/{len(self.dataset)}")
|
| 129 |
+
|
| 130 |
+
# Group data by pair_id
|
| 131 |
+
pairs = {}
|
| 132 |
+
for idx, row in file_data.iterrows():
|
| 133 |
+
pair_id = row['pair_id']
|
| 134 |
+
if pair_id not in pairs:
|
| 135 |
+
pairs[pair_id] = []
|
| 136 |
+
pairs[pair_id].append(row.to_dict())
|
| 137 |
+
|
| 138 |
+
# Process each pair
|
| 139 |
+
graph_datas = []
|
| 140 |
+
answers = []
|
| 141 |
+
pair_count = 0
|
| 142 |
+
for pair_id, pair_data in pairs.items():
|
| 143 |
+
if len(pair_data) != 2: # Skip if pair is incomplete
|
| 144 |
+
continue
|
| 145 |
+
# if pair_count >= 3: # Only process first 3 pairs
|
| 146 |
+
# break
|
| 147 |
+
# print(f"Processing pair {pair_id}")
|
| 148 |
+
# Sort by graph_position to ensure correct order
|
| 149 |
+
pair_data.sort(key=lambda x: x['graph_position'])
|
| 150 |
+
graph_datas.append(pair_data)
|
| 151 |
+
answer = self.process_single_data(pair_data)
|
| 152 |
+
answers.append(answer)
|
| 153 |
+
pair_count += 1
|
| 154 |
+
|
| 155 |
+
evaluation = self.evaluator.evaluate(graph_datas, answers)
|
| 156 |
+
all_results[file_name] = evaluation
|
| 157 |
+
|
| 158 |
+
return all_results
|
| 159 |
+
elif self.task_name in ["R_Selection", "R_Generation"]:
|
| 160 |
+
# Process each parquet file in the dataset
|
| 161 |
+
for file_idx, (file_name, file_data) in enumerate(self.dataset.items()):
|
| 162 |
+
print(f"\nProcessing file {file_idx + 1}/{len(self.dataset)}")
|
| 163 |
+
|
| 164 |
+
# Group data by group_id
|
| 165 |
+
groups = {}
|
| 166 |
+
for idx, row in file_data.iterrows():
|
| 167 |
+
group_id = row['group_id']
|
| 168 |
+
if group_id not in groups:
|
| 169 |
+
groups[group_id] = []
|
| 170 |
+
groups[group_id].append(row.to_dict())
|
| 171 |
+
|
| 172 |
+
# Process each group
|
| 173 |
+
graph_datas = []
|
| 174 |
+
answers = []
|
| 175 |
+
group_count = 0
|
| 176 |
+
for group_id, group_data in groups.items():
|
| 177 |
+
if len(group_data) != 4: # Skip if group is incomplete
|
| 178 |
+
continue
|
| 179 |
+
# if group_count >= 3: # Only process first 3 groups
|
| 180 |
+
# break
|
| 181 |
+
|
| 182 |
+
# Sort by graph_position to ensure correct order
|
| 183 |
+
group_data.sort(key=lambda x: x['graph_position'])
|
| 184 |
+
graph_datas.append(group_data)
|
| 185 |
+
answer = self.process_single_data(group_data)
|
| 186 |
+
answers.append(answer)
|
| 187 |
+
group_count += 1
|
| 188 |
+
|
| 189 |
+
evaluation = self.evaluator.evaluate(graph_datas, answers)
|
| 190 |
+
all_results[file_name] = evaluation
|
| 191 |
+
|
| 192 |
+
return all_results
|
evaluate_code/load_datasets.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from huggingface_hub import list_repo_files, hf_hub_download
|
| 5 |
+
|
| 6 |
+
def load_data(file_path):
|
| 7 |
+
"""Load data based on file extension"""
|
| 8 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 9 |
+
if ext == '.json':
|
| 10 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 11 |
+
return json.load(f)
|
| 12 |
+
elif ext == '.csv':
|
| 13 |
+
return pd.read_csv(file_path)
|
| 14 |
+
elif ext == '.jsonl':
|
| 15 |
+
data = []
|
| 16 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 17 |
+
for line in f:
|
| 18 |
+
data.append(json.loads(line))
|
| 19 |
+
return data
|
| 20 |
+
elif ext == '.parquet':
|
| 21 |
+
return pd.read_parquet(file_path)
|
| 22 |
+
else:
|
| 23 |
+
raise ValueError(f"Unsupported file extension: {ext}")
|
| 24 |
+
|
| 25 |
+
def download_and_load_datasets():
|
| 26 |
+
repo_id = "Antislab/LLM4PH"
|
| 27 |
+
files = list_repo_files(repo_id=repo_id, repo_type="dataset")
|
| 28 |
+
|
| 29 |
+
downloaded_files = []
|
| 30 |
+
for file in files:
|
| 31 |
+
if file.startswith("datasets/"):
|
| 32 |
+
local_path = os.path.join(".", file)
|
| 33 |
+
if not os.path.exists(local_path):
|
| 34 |
+
print(f"Downloading {file}...")
|
| 35 |
+
hf_hub_download(
|
| 36 |
+
repo_id=repo_id,
|
| 37 |
+
filename=file,
|
| 38 |
+
repo_type="dataset",
|
| 39 |
+
local_dir="."
|
| 40 |
+
)
|
| 41 |
+
else:
|
| 42 |
+
print(f"File {file} already exists, skipping download.")
|
| 43 |
+
downloaded_files.append(local_path)
|
| 44 |
+
|
| 45 |
+
# Load all downloaded files
|
| 46 |
+
loaded_data = {}
|
| 47 |
+
for file_path in downloaded_files:
|
| 48 |
+
try:
|
| 49 |
+
loaded_data[file_path] = load_data(file_path)
|
| 50 |
+
print(f"Successfully loaded {file_path}")
|
| 51 |
+
except Exception as e:
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from scipy.sparse.csgraph import connected_components
|
| 3 |
+
import gudhi as gd
|
| 4 |
+
from persim import wasserstein
|
| 5 |
+
import bisect
|
| 6 |
+
|
| 7 |
+
def count_connected_components(edge_index, num_nodes):
|
| 8 |
+
"""Count the number of connected components in a graph"""
|
| 9 |
+
# Create adjacency matrix
|
| 10 |
+
adj_matrix = np.zeros((num_nodes, num_nodes))
|
| 11 |
+
for i in range(edge_index.shape[1]):
|
| 12 |
+
src, dst = edge_index[0, i], edge_index[1, i]
|
| 13 |
+
adj_matrix[src, dst] = 1
|
| 14 |
+
adj_matrix[dst, src] = 1
|
| 15 |
+
|
| 16 |
+
# Calculate connected components using scipy
|
| 17 |
+
n_components, _ = connected_components(adj_matrix)
|
| 18 |
+
return n_components
|
| 19 |
+
|
| 20 |
+
def Filtration(edge_index, edge_attr,filt,filt_value):
|
| 21 |
+
def filt_edge(edges,filt_value):
|
| 22 |
+
upper_bounds = filt_value
|
| 23 |
+
filted_edges = []
|
| 24 |
+
for edge in edges:
|
| 25 |
+
src, tgt, w = edge
|
| 26 |
+
index = bisect.bisect_left(upper_bounds, w)
|
| 27 |
+
if index < len(upper_bounds):
|
| 28 |
+
assigned_upper = upper_bounds[index]
|
| 29 |
+
else:
|
| 30 |
+
assigned_upper = upper_bounds[-1]
|
| 31 |
+
|
| 32 |
+
filted_edges.append((src, tgt, assigned_upper))
|
| 33 |
+
|
| 34 |
+
return filted_edges
|
| 35 |
+
edge_index = np.array(edge_index).reshape(2, -1)
|
| 36 |
+
original_edges = []
|
| 37 |
+
for i in range(edge_index.shape[1]):
|
| 38 |
+
source = edge_index[0, i].item()
|
| 39 |
+
target = edge_index[1, i].item()
|
| 40 |
+
weight = edge_attr[i].item()
|
| 41 |
+
original_edges.append((source, target, weight))
|
| 42 |
+
if filt:
|
| 43 |
+
original_edges = filt_edge(original_edges,filt_value)
|
| 44 |
+
sorted_edges = sorted(original_edges, key=lambda x: x[2])
|
| 45 |
+
|
| 46 |
+
simplices = gd.SimplexTree()
|
| 47 |
+
for u, v, weight in sorted_edges:
|
| 48 |
+
simplices.insert([u, v], filtration=weight)
|
| 49 |
+
simplices.expansion(2)
|
| 50 |
+
filtration = simplices.get_filtration()
|
| 51 |
+
simplex_list = []
|
| 52 |
+
|
| 53 |
+
for simplex in filtration:
|
| 54 |
+
simplex_list.append(simplex)
|
| 55 |
+
|
| 56 |
+
simplices.persistence()
|
| 57 |
+
barcode = []
|
| 58 |
+
for i in range(2):
|
| 59 |
+
intervals = simplices.persistence_intervals_in_dimension(i)
|
| 60 |
+
barcode.append(intervals)
|
| 61 |
+
|
| 62 |
+
vr_e_pd = {}
|
| 63 |
+
for dim, intervals in enumerate(barcode):
|
| 64 |
+
if intervals.size > 0 and dim<=2:
|
| 65 |
+
intervals = intervals.tolist()
|
| 66 |
+
intervals.sort(key=lambda x: x[0])
|
| 67 |
+
vr_e_pd[f'{dim}dim'] = intervals
|
| 68 |
+
else:
|
| 69 |
+
vr_e_pd[f'{dim}dim'] = []
|
| 70 |
+
|
| 71 |
+
return sorted_edges, simplex_list, vr_e_pd
|
| 72 |
+
|
| 73 |
+
def add_vr_ORI(dataset,filt,filt_value=None):
|
| 74 |
+
for i in range(len(dataset)):
|
| 75 |
+
edge_index = dataset[i]['edge_index']
|
| 76 |
+
edge_attr = dataset[i]['edge_attr']
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
sorted_edges,simplex_list, vr_e_pd = Filtration(edge_index, edge_attr,filt,filt_value)
|
| 80 |
+
|
| 81 |
+
for dim in vr_e_pd:
|
| 82 |
+
vr_e_pd[dim].sort(key=lambda interval: interval[0])
|
| 83 |
+
|
| 84 |
+
# dataset[i].sorted_edges = sorted_edges
|
| 85 |
+
# dataset[i].simplex = simplex_list
|
| 86 |
+
# dataset[i].vr_e_pd = vr_e_pd
|
| 87 |
+
|
| 88 |
+
if filt:
|
| 89 |
+
dataset[i]['selected_vr_e_pd'] = vr_e_pd
|
| 90 |
+
else:
|
| 91 |
+
dataset[i]['vr_e_pd'] = vr_e_pd
|
| 92 |
+
|
| 93 |
+
def PD_to_diagram(PD):
|
| 94 |
+
"""
|
| 95 |
+
Convert persistence diagram dictionary to numpy array format.
|
| 96 |
+
"""
|
| 97 |
+
diagram = []
|
| 98 |
+
for dim, intervals in PD.items():
|
| 99 |
+
dim_int = int(dim[0])
|
| 100 |
+
for interval in intervals:
|
| 101 |
+
birth, death = interval
|
| 102 |
+
diagram.append([birth, death, dim_int])
|
| 103 |
+
return np.array(diagram)
|
| 104 |
+
|
| 105 |
+
def compute_wasserstein_distance(PD1, PD2):
|
| 106 |
+
"""
|
| 107 |
+
Compute Wasserstein distance between two persistence diagrams.
|
| 108 |
+
"""
|
| 109 |
+
diagram1 = PD_to_diagram(PD1)
|
| 110 |
+
diagram2 = PD_to_diagram(PD2)
|
| 111 |
+
|
| 112 |
+
# Handle infinite death times
|
| 113 |
+
diagram1[~np.isfinite(diagram1[:, 1]), 1] = 1.1
|
| 114 |
+
diagram2[~np.isfinite(diagram2[:, 1]), 1] = 1.1
|
| 115 |
+
|
| 116 |
+
return wasserstein(diagram1, diagram2)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def check_graph_group(graphs, method='weight', pre_calculate=True, filt_value=None):
|
| 120 |
+
"""
|
| 121 |
+
Check if four graphs satisfy the separation condition:
|
| 122 |
+
1. Both distances within same class are smaller than all four distances between different classes
|
| 123 |
+
2. Four graphs must be arranged in [1,1,-1,-1] order
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
graphs: List of 4 graphs arranged in [1,1,-1,-1] order
|
| 127 |
+
method: Persistent homology calculation method
|
| 128 |
+
pre_calculate: Whether persistence diagrams are pre-calculated
|
| 129 |
+
filt_value: Filtration value for calculation
|
| 130 |
+
|
| 131 |
+
Returns:
|
| 132 |
+
tuple: (bool, list) - Whether separation condition is satisfied and list of distances
|
| 133 |
+
"""
|
| 134 |
+
if len(graphs) != 4:
|
| 135 |
+
raise ValueError("Must provide exactly 4 graphs")
|
| 136 |
+
|
| 137 |
+
# Verify graph label order
|
| 138 |
+
if not (graphs[0]['y'] == graphs[1]['y'] and graphs[2]['y'] == graphs[3]['y'] and graphs[0]['y'] != graphs[2]['y']):
|
| 139 |
+
raise ValueError("Graphs must be ordered as [1,1,-1,-1]")
|
| 140 |
+
|
| 141 |
+
if not pre_calculate:
|
| 142 |
+
add_vr_ORI(graphs, filt=True, filt_value=filt_value)
|
| 143 |
+
|
| 144 |
+
# Calculate distances between all graph pairs
|
| 145 |
+
distances = []
|
| 146 |
+
for i in range(4):
|
| 147 |
+
for j in range(i+1, 4):
|
| 148 |
+
if method == 'weight':
|
| 149 |
+
if pre_calculate:
|
| 150 |
+
dist = compute_wasserstein_distance(graphs[i]['vr_e_pd'], graphs[j]['vr_e_pd'])
|
| 151 |
+
else:
|
| 152 |
+
dist = compute_wasserstein_distance(graphs[i]['selected_vr_e_pd'], graphs[j]['selected_vr_e_pd'])
|
| 153 |
+
else:
|
| 154 |
+
dist = compute_wasserstein_distance(
|
| 155 |
+
getattr(graphs[i], f'vr_{method}_pd'),
|
| 156 |
+
getattr(graphs[j], f'vr_{method}_pd')
|
| 157 |
+
)
|
| 158 |
+
distances.append((i, j, dist))
|
| 159 |
+
|
| 160 |
+
# Distances within same class
|
| 161 |
+
same_class_distances = [dist for i, j, dist in distances
|
| 162 |
+
if (i < 2 and j < 2) or (i >= 2 and j >= 2)]
|
| 163 |
+
|
| 164 |
+
# Distances between different classes
|
| 165 |
+
diff_class_distances = [dist for i, j, dist in distances
|
| 166 |
+
if (i < 2 and j >= 2) or (i >= 2 and j < 2)]
|
| 167 |
+
|
| 168 |
+
max_same = max(same_class_distances)
|
| 169 |
+
min_diff = min(diff_class_distances)
|
| 170 |
+
|
| 171 |
+
return max_same < min_diff, distances
|
llm4ph.png
ADDED
|
Git LFS Details
|
main.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from evaluate_code.llm_evaluator import LLMEvaluator
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from config import TASKS, MODEL_NAMES
|
| 4 |
+
import os
|
| 5 |
+
import json
|
| 6 |
+
import csv
|
| 7 |
+
|
| 8 |
+
def save_results(date_str,results, task_name):
|
| 9 |
+
"""
|
| 10 |
+
Save results to both JSON and CSV files
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
results: Dictionary containing evaluation results
|
| 14 |
+
task_name: Name of the task
|
| 15 |
+
"""
|
| 16 |
+
# Create results directory if it doesn't exist
|
| 17 |
+
if not os.path.exists("results"):
|
| 18 |
+
os.makedirs("results")
|
| 19 |
+
|
| 20 |
+
# Create date folder
|
| 21 |
+
date_path = os.path.join("results", date_str)
|
| 22 |
+
if not os.path.exists(date_path):
|
| 23 |
+
os.makedirs(date_path)
|
| 24 |
+
|
| 25 |
+
# Create task folder
|
| 26 |
+
task_path = os.path.join(date_path, task_name)
|
| 27 |
+
if not os.path.exists(task_path):
|
| 28 |
+
os.makedirs(task_path)
|
| 29 |
+
|
| 30 |
+
# Save JSON
|
| 31 |
+
json_path = os.path.join(task_path, "results.json")
|
| 32 |
+
with open(json_path, 'w', encoding='utf-8') as f:
|
| 33 |
+
json.dump(results, f, ensure_ascii=False, indent=2)
|
| 34 |
+
if task_name in ["S_0D", "S_1D", "S_Modification", "M_Merge", "M_Birth", "M_Filtration", "R_Selection", "R_Generation"]:
|
| 35 |
+
# Save CSV
|
| 36 |
+
csv_path = os.path.join(task_path, "results.csv")
|
| 37 |
+
with open(csv_path, 'w', newline='', encoding='utf-8') as f:
|
| 38 |
+
writer = csv.writer(f)
|
| 39 |
+
# Write header
|
| 40 |
+
writer.writerow(['file_name', 'accuracy'])
|
| 41 |
+
# Write data
|
| 42 |
+
for file_name, (accuracy, _) in results.items():
|
| 43 |
+
# Remove .parquet extension
|
| 44 |
+
file_name = file_name.replace('.parquet', '')
|
| 45 |
+
writer.writerow([file_name, accuracy])
|
| 46 |
+
elif task_name in ["H_Selection", "H_Generation"]:
|
| 47 |
+
# Save CSV
|
| 48 |
+
csv_path = os.path.join(task_path, "results.csv")
|
| 49 |
+
with open(csv_path, 'w', newline='', encoding='utf-8') as f:
|
| 50 |
+
writer = csv.writer(f)
|
| 51 |
+
# Write header
|
| 52 |
+
writer.writerow(['file_name', 'mean_rank', 'std_rank'])
|
| 53 |
+
# Write data
|
| 54 |
+
for file_name, (_, details) in results.items():
|
| 55 |
+
mean_rank = details['statistics']['mean_rank']
|
| 56 |
+
std_rank = details['statistics']['std_rank']
|
| 57 |
+
file_name = file_name.replace('.parquet', '')
|
| 58 |
+
writer.writerow([file_name, mean_rank, std_rank])
|
| 59 |
+
|
| 60 |
+
def main():
|
| 61 |
+
date_str = datetime.now().strftime("%Y%m%d_%H%M")
|
| 62 |
+
# Process each task in the task list
|
| 63 |
+
for task_name in TASKS:
|
| 64 |
+
for model_name in MODEL_NAMES:
|
| 65 |
+
print(f"Processing task: {task_name} with model: {model_name}")
|
| 66 |
+
evaluator = LLMEvaluator(
|
| 67 |
+
task_name=task_name,
|
| 68 |
+
model_name=model_name
|
| 69 |
+
)
|
| 70 |
+
# Process all graphs in all files
|
| 71 |
+
results = evaluator.process_dataset()
|
| 72 |
+
# Save results
|
| 73 |
+
save_results(date_str, results, task_name)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Core dependencies
|
| 2 |
+
numpy==2.1.3
|
| 3 |
+
pandas==2.2.3
|
| 4 |
+
torch==2.5.1
|
| 5 |
+
scikit-learn==1.6.1
|
| 6 |
+
scipy==1.14.1
|
| 7 |
+
|
| 8 |
+
# Topology and graph related
|
| 9 |
+
gudhi==3.11.0
|
| 10 |
+
persim==0.3.8
|
| 11 |
+
networkx==3.4.2
|
| 12 |
+
|
| 13 |
+
# LLM API support
|
| 14 |
+
openai==1.79.0
|
| 15 |
+
anthropic==0.51.0
|
| 16 |
+
google-generativeai==0.8.5
|
| 17 |
+
python-dotenv==1.1.0
|
| 18 |
+
|
| 19 |
+
# Visualization and utilities
|
| 20 |
+
matplotlib==3.9.2
|
| 21 |
+
tqdm==4.67.1
|
| 22 |
+
huggingface-hub==0.31.2
|