File size: 26,154 Bytes
9f50319 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 | from typing import Dict, List, Any
import re
def _extract_section(text: str, start_marker: str, end_marker: str) -> str:
"""Extract content between two markers"""
start = text.find(start_marker)
if start == -1:
return ""
start += len(start_marker)
end = text.find(end_marker, start)
if end == -1:
return ""
return text[start:end].strip()
class AnswerExtractor:
def __init__(self, task_name):
"""Initialize answer extractor"""
self.task_name = task_name
def extract_answers(self, response):
"""Extract answers based on task type"""
try:
task_extractors = {
"S_0D": self.extract_S_0D,
"S_1D": self.extract_S_1D,
"S_Modification": self.extract_S_Modification,
"M_Birth": self.extract_M_Birth,
"M_Merge": self.extract_M_Merge,
"M_Filtration": self.extract_M_Filtration,
"H_Selection": self.extract_H_Selection,
"H_Generation": self.extract_H_Generation,
"R_Selection": self.extract_R_Selection,
"R_Generation": self.extract_R_Generation,
"R_Directly": self.extract_R_Directly
}
answer = task_extractors.get(self.task_name)(response) if self.task_name in task_extractors else None
return answer
except Exception as e:
print(f"Error extracting answer: {str(e)}")
return None
def extract_S_0D(self, answer: str) -> Dict[str, Any]:
"""Extract information from 0-dimensional topology structure identification answer"""
try:
# Extract the answer section
answer_section = answer
if "Answer:" in answer:
answer_section = answer.split("Answer:")[-1].strip()
# Extract the filtration value with more flexible pattern matching
value_match = re.search(r'connected components:\s*(\d+)', answer_section)
if not value_match:
return {"error": "connected components not found"}
# Parse the value
try:
value = int(value_match.group(1).strip())
return {
"connected_components": value
}
except ValueError as e:
return {"error": f"Error parsing value: {str(e)}"}
except Exception as e:
return {"error": f"Error during extraction: {str(e)}"}
def extract_S_1D(self, answer: str) -> Dict[str, Any]:
"""Extract information from 1-dimensional topology structure identification answer"""
try:
# Extract the answer section
answer_section = answer
if "Answer:" in answer:
answer_section = answer.split("Answer:")[-1].strip()
# Extract the filtration value with more flexible pattern matching
value_match = re.search(r'cycle holes:\s*(\d+)', answer_section)
if not value_match:
return {"error": "cycle holes not found"}
# Parse the value
try:
value = int(value_match.group(1).strip())
return {
"cycle_holes": value
}
except ValueError as e:
return {"error": f"Error parsing value: {str(e)}"}
except Exception as e:
return {"error": f"Error during extraction: {str(e)}"}
def extract_S_Modification(self, answer: str) -> Dict[str, Any]:
"""Extract information from graph structure modification answer"""
try:
# Extract the answer section
answer_section = answer
if "Answer:" in answer:
answer_section = answer.split("Answer:")[-1].strip()
# Try multiple matching patterns
patterns = [
r'Edge to add:\s*\[(.*?)\]', # Match "Edge to add: [0, 7]" format
r'Edge to add:\s*\((\d+)\s*,\s*(\d+)\)', # Match "Edge to add: (0, 7)" format
r'Edge to add:\s*(\d+)\s*-\s*(\d+)', # Match "Edge to add: 0-7" format
r'Edge to add:\s*(\d+)\s*,\s*(\d+)' # Match "Edge to add: 0, 7" format
]
for pattern in patterns:
value_match = re.search(pattern, answer_section)
if value_match:
try:
if pattern == r'Edge to add:\s*\[(.*?)\]':
# Handle [0, 7] format
values_str = value_match.group(1).strip()
values = [int(x.strip()) for x in values_str.split(',')]
else:
# Handle other formats
values = [int(value_match.group(1)), int(value_match.group(2))]
return {
"edge_to_add": values
}
except (ValueError, IndexError):
continue
return {"error": "Edge to add not found or invalid format"}
except Exception as e:
return {"error": f"Error during extraction: {str(e)}"}
def extract_M_Birth(self, answer: str) -> Dict[str, Any]:
"""Extract birth time calculation task answer"""
try:
# Extract the answer section
answer_section = answer
if "Answer:" in answer:
answer_section = answer.split("Answer:")[-1].strip()
# Extract the filtration value
value_match = re.search(r'birth time:\s*\[(.*?)\]', answer_section)
if not value_match:
return {"error": "birth_time not found"}
# Parse the values
try:
values = [self._parse_number(x) for x in value_match.group(1).split(',')]
return {
"birth_time": values
}
except ValueError as e:
return {"error": f"Error parsing : {str(e)}"}
except Exception as e:
return {"error": f"Error during extraction: {str(e)}"}
def extract_M_Merge(self, answer: str) -> Dict[str, Any]:
"""Extract information from 0-dimensional persistent homology calculation task answer"""
try:
# Extract the answer section
answer_section = answer
if "Answer:" in answer:
answer_section = answer.split("Answer:")[-1].strip()
# Extract the filtration value
value_match = re.search(r'death time:\s*\[(.*?)\]', answer_section)
if not value_match:
return {"error": "death_time not found"}
# Parse the values
try:
values = [self._parse_number(x) for x in value_match.group(1).split(',')]
return {
"death_time": values
}
except ValueError as e:
return {"error": f"Error parsing : {str(e)}"}
except Exception as e:
return {"error": f"Error during extraction: {str(e)}"}
def extract_M_Filtration(self,answer:str) -> Dict[str, Any]:
try:
# Extract the answer section
answer_section = answer
if "Answer:" in answer:
answer_section = answer.split("Answer:")[-1].strip()
# Extract the filtration value
value_match = re.search(r'connected components:\s*\[(.*?)\]', answer_section)
if not value_match:
return {"error": "connected components not found"}
# Parse the values
try:
values = [self._parse_number(x) for x in value_match.group(1).split(',')]
return {
"connected_components": values
}
except ValueError as e:
return {"error": f"Error parsing : {str(e)}"}
except Exception as e:
return {"error": f"Error during extraction: {str(e)}"}
def extract_H_Selection(self, answer: str) -> Dict[str, Any]:
"""Extract selected filtration method from the response"""
try:
# Extract the answer section
answer_section = answer
if "Answer:" in answer:
answer_section = answer.split("Answer:")[-1].strip()
# Try multiple matching patterns
patterns = [
r'Method:\s*([\w-]+)', # Match "Method: k-shell" format
r'Method:\s*\[([\w-]+)\]', # Match "Method: [k-shell]" format
r'selected_method:\s*([\w-]+)', # Match "selected_method: k-shell" format
r'Selected Method:\s*([\w-]+)' # Match "Selected Method: k-shell" format
]
for pattern in patterns:
value_match = re.search(pattern, answer_section, re.IGNORECASE)
if value_match:
method = value_match.group(1).strip().lower()
# Validate method name
valid_methods = ['degree', 'betweenness', 'k-shell', 'closeness', 'weight', 'eigenvector']
if method in valid_methods:
return {
"selected_method": method
}
return {"error": "Method not found or invalid"}
except Exception as e:
return {"error": f"Error during extraction: {str(e)}"}
def extract_H_Generation(self, answer: str) -> Dict[str, Any]:
"""Extract information from filteration value selection task answer"""
try:
# Extract the answer section
answer_section = answer
if "Answer:" in answer:
answer_section = answer.split("Answer:")[-1].strip()
# Extract the filtration value
value_match = re.search(r'filtration value:\s*\[(.*?)\]', answer_section)
if not value_match:
return {"error": "Filtration value not found"}
# Parse the values
try:
values = [int(x.strip()) for x in value_match.group(1).split(',')]
return {
"selected_filtration_values": values
}
except ValueError as e:
return {"error": f"Error parsing filtration values: {str(e)}"}
except Exception as e:
return {"error": f"Error during extraction: {str(e)}"}
def extract_filtration_edge_construction(self, answer: str) -> Dict[str, Any]:
"""Extract information from filtration edge construction task answer"""
result = {
"filtration": {}
}
try:
# Extract filtration process
filtration_section = _extract_section(answer, "===FILTRATION_START===", "===FILTRATION_END===")
result["filtration"] = self._parse_filtration_edges(filtration_section)
# Validate results
if not result["filtration"]:
print("Warning: Failed to extract filtration process")
print("Filtration process:", result["filtration"])
except Exception as e:
import traceback
print(f"Error during extraction: {str(e)}")
print("Error details:")
print(traceback.format_exc())
return result # Return partially parsed results instead of None
return result
def extract_simplicial_complex_construction(self, answer: str) -> Dict[str, Any]:
"""
Extract answer for simplicial_complex_construction task
Parameters:
answer: Model generated answer text
Returns:
dict: Contains extracted simplicial complex information
"""
try:
# Extract simplicial complex section
simplex_text = self._extract_section(answer, "===SIMPLICIAL_COMPLEX_START===", "===SIMPLICIAL_COMPLEX_END===")
if not simplex_text:
return {"error": "Simplicial complex section not found"}
# Parse simplicial complex
simplices = {}
for line in simplex_text.split('\n'):
line = line.strip()
if not line:
continue
# Check if it's a simplex
if line.startswith('[') and line.endswith(']'):
try:
# Parse node list and filtration value
content = line[1:-1] # Remove outer brackets
nodes_part, value_part = content.split('),')
nodes = [int(x.strip()) for x in nodes_part[1:].split(',')] # Remove inner brackets
value = float(value_part.strip())
if len(nodes) == 3: # Only process 2-dimensional simplices (triangles)
if value not in simplices:
simplices[value] = []
simplices[value].append(nodes)
except (ValueError, IndexError) as e:
print(f"Error parsing simplex: {line}, error: {str(e)}")
continue
return {
"simplicial_complexes": simplices
}
except Exception as e:
return {"error": f"Error during extraction: {str(e)}"}
def _parse_number(self, value_str: str) -> float:
"""Parse number intelligently, try integer first, then float"""
value_str = value_str.strip()
try:
# Try parsing as integer first
return int(value_str)
except ValueError:
try:
# If integer parsing fails, try parsing as float
value = float(value_str)
# If it's an integer (no decimal part), return integer
if value.is_integer():
return int(value)
return value
except ValueError:
raise ValueError(f"Cannot parse number: {value_str}")
def extract_R_Selection(self, answer: str) -> Dict[str, Any]:
"""Extract selected filtration method from the response"""
try:
# Extract the answer section
answer_section = answer
if "Answer:" in answer:
answer_section = answer.split("Answer:")[-1].strip()
# Try multiple matching patterns
patterns = [
r'Method:\s*(\w+)', # Match "Method: weight" format
r'Method:\s*\[(.*?)\]', # Match "Method: [weight]" format
r'selected_method:\s*(\w+)', # Match "selected_method: weight" format
r'Selected Method:\s*(\w+)' # Match "Selected Method: weight" format
]
for pattern in patterns:
value_match = re.search(pattern, answer_section, re.IGNORECASE)
if value_match:
method = value_match.group(1).strip().lower()
# 验证方法名称是否有效
valid_methods = ['degree', 'betweenness', 'k-shell', 'closeness', 'weight','eigenvector']
if method in valid_methods:
return {
"selected_method": method
}
return {"error": "Method not found or invalid"}
except Exception as e:
return {"error": f"Error during extraction: {str(e)}"}
def extract_R_Generation(self, answer: str) -> Dict[str, Any]:
"""Extract filtration values from the response"""
try:
# Extract content after "Answer:" if present
answer_section = answer
if "Answer:" in answer:
answer_section = answer.split("Answer:")[-1].strip()
# Match pattern like Filtration value: [0.1,0.4,0.5,...]
pattern = r'Filtration\s*value[s]?:\s*\[([^\]]+)\]'
match = re.search(pattern, answer_section, re.IGNORECASE)
if not match:
return {"error": "Filtration values not found"}
# Extract numbers inside brackets, split by comma and convert to float
nums_str = match.group(1)
values: List[float] = []
for part in nums_str.split(','):
part = part.strip()
if part:
try:
values.append(float(part))
except ValueError:
return {"error": f"Cannot convert '{part}' to float"}
return {"filtration_values": values}
except Exception as e:
return {"error": f"Error during extraction: {str(e)}"}
def extract_R_Directly(self, answer: str) -> Dict[str, Any]:
"""Extract category classification from the response"""
# Get content after "Answer:" if present
if "Answer:" in answer:
answer_section = answer.split("Answer:")[-1].strip()
else:
answer_section = answer
pattern = r'Category:\s*[\[\(]\s*([\d\.\s,]+)[\]\)]\s*,\s*[\[\(]\s*([\d\.\s,]+)[\]\)]'
match = re.search(pattern, answer_section, re.IGNORECASE | re.DOTALL)
if not match:
return {"error": "Category format not found or incorrect"}
def parse_group(group_str: str) -> List[int]:
return [int(float(x.strip())) for x in group_str.split(',') if x.strip()]
category1 = parse_group(match.group(1))
category2 = parse_group(match.group(2))
all_indices = sorted(category1 + category2)
if all_indices != [1, 2, 3, 4]:
return {"error": f"Graph indices must be [1, 2, 3, 4], got: {all_indices}"}
return {
"categories": [category1, category2]
}
# def _parse_filtration_edges(self, section: str) -> Dict[float, List[Tuple[int, int]]]:
# """Parse filtration process, specific to the format of filtration edge construction task"""
# filtration = {}
# current_value = None
# for line in section.split('\n'):
# line = line.strip()
# if line.startswith('**Value='):
# value_part = line.replace('**', '').replace('Value=', '').strip()
# current_value = float(value_part)
# filtration[current_value] = []
# elif line.startswith('(') and line.endswith(')'):
# try:
# u, v = map(int, line[1:-1].split(','))
# filtration[current_value].append((u, v))
# except:
# print(f"Cannot parse edge: {line}")
# return filtration
# def extract_structure_identification(self, answer: str) -> Dict[str, Any]:
# """Extract information from topology structure identification answer"""
# result = {
# "cavities": [],
# "temporal_evolution": {}
# }
# # Extract cavity information
# if "2-DIMENSIONAL CAVITIES:" in answer:
# cavities_section = self._extract_section(
# answer, "2-DIMENSIONAL CAVITIES:", "TEMPORAL EVOLUTION:"
# )
# result["cavities"] = self._extract_cavities(cavities_section)
# # Extract temporal evolution
# if "TEMPORAL EVOLUTION:" in answer:
# evolution_section = answer.split("TEMPORAL EVOLUTION:")[1]
# result["temporal_evolution"] = self._extract_temporal_evolution(evolution_section)
# return result
# def extract_simplex_structure_identification(self, answer: str) -> Dict[str, Any]:
# """Extract information from simplex structure identification answer"""
# result = {
# "simplex_count": 0
# }
# lines = answer.strip().split('\n')
# for line in lines:
# line = line.strip()
# if line.startswith('2维单纯形数量:'):
# count_str = line.split(':')[1].strip()
# try:
# result["simplex_count"] = int(count_str)
# except ValueError:
# # Keep default value 0 if cannot parse as integer
# pass
# return result
# def _extract_section(self, text: str, start_marker: str, end_marker: str) -> str:
# """Extract text between two markers"""
# if start_marker in text and end_marker in text:
# start_idx = text.find(start_marker) + len(start_marker)
# end_idx = text.find(end_marker)
# return text[start_idx:end_idx].strip()
# return ""
# def _extract_list(self, text: str) -> List:
# """Extract list from text"""
# items = text.split(':')[1].strip()
# if items.startswith('[') and items.endswith(']'):
# return eval(items)
# return []
# def _extract_feature_info(self, line: str) -> Dict[str, Any]:
# """Extract feature information from text"""
# info = {}
# if 'Birth time:' in line:
# info['birth'] = float(line.split(':')[1].strip())
# elif 'Death time:' in line:
# info['death'] = float(line.split(':')[1].strip())
# elif 'Persistence:' in line:
# info['persistence'] = float(line.split(':')[1].strip())
# elif 'Description:' in line:
# info['description'] = line.split(':')[1].strip()
# return info
# def _extract_cavities(self, text: str) -> List[Dict[str, Any]]:
# """Extract cavity information"""
# cavities = []
# current_cavity = None
# for line in text.split('\n'):
# if line.startswith('Cavity'):
# if current_cavity:
# cavities.append(current_cavity)
# current_cavity = {}
# elif current_cavity is not None and line.startswith('-'):
# key = line.split(':')[0].strip('- ').lower()
# value = line.split(':')[1].strip()
# if key in ['birth threshold', 'death threshold', 'persistence']:
# value = float(value)
# elif key in ['nodes', 'edges']:
# value = eval(value)
# current_cavity[key] = value
# if current_cavity:
# cavities.append(current_cavity)
# return cavities
# def _extract_temporal_evolution(self, text: str) -> Dict[float, Dict[str, List[int]]]:
# """Extract temporal evolution information"""
# evolution = {}
# current_threshold = None
# for line in text.split('\n'):
# if line.startswith('Threshold'):
# current_threshold = float(line.split()[1])
# evolution[current_threshold] = {
# 'active': [],
# 'new': [],
# 'disappeared': []
# }
# elif current_threshold is not None and line.startswith('-'):
# key = line.split(':')[0].strip('- ').lower()
# value = eval(line.split(':')[1].strip())
# evolution[current_threshold][key] = value
# return evolution
# def _extract_current_state(self, text: str) -> Dict[str, Any]:
# """Extract current state information"""
# state = {}
# for line in text.split('\n'):
# if line.startswith('- Number of cycles:'):
# state['cycles'] = int(line.split(':')[1].strip())
# elif line.startswith('- Cycle locations:'):
# state['locations'] = eval(line.split(':')[1].strip())
# return state
# def _extract_proposed_modifications(self, text: str) -> List[Dict[str, Any]]:
# """Extract proposed modifications"""
# modifications = []
# current_mod = None
# for line in text.split('\n'):
# if line.startswith('Modification'):
# if current_mod:
# modifications.append(current_mod)
# current_mod = {}
# elif current_mod is not None and line.startswith('-'):
# key = line.split(':')[0].strip('- ').lower()
# value = line.split(':')[1].strip()
# if key == 'new edge':
# value = tuple(map(int, value.split('-')))
# elif key == 'expected new cycles':
# value = eval(value)
# current_mod[key] = value
# if current_mod:
# modifications.append(current_mod)
# return modifications
# def _extract_expected_outcome(self, text: str) -> Dict[str, Any]:
# """Extract expected outcome"""
# outcome = {}
# for line in text.split('\n'):
# if line.startswith('- New number of cycles:'):
# outcome['new_cycles'] = int(line.split(':')[1].strip())
# elif line.startswith('- New cycle locations:'):
# outcome['new_locations'] = eval(line.split(':')[1].strip())
# elif line.startswith('- Changes in persistence:'):
# outcome['persistence_changes'] = line.split(':')[1].strip()
# return outcome
|