File size: 24,577 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 | class GraphEmbedder:
def __init__(self, task_name):
"""Initialize graph embedder (text format only)"""
self.embed_type = "text" # Fixed as text format
self.task_name = task_name
def embed_graph(self, graph_data):
"""
Embed graph data into prompt
Parameters:
- graph_data: Graph data object
- task_type: Task type, can be one of:
- "filtration_edge_construction": Filtration edge construction task
- "simplicial_complex_construction": Simplicial complex construction task
- "persistent_homology_calculation": Persistent homology calculation task
- "node_addition": Node addition analysis task
- "structure_identification": Topological structure identification task
- "graph_modification": Graph structure modification task
- "topology_interpretation": Topological feature interpretation task
- "vector_representation": Topological feature vectorization task
- "noise_robustness": Noise robustness testing task
Returns:
- prompt: Prompt with embedded graph data
"""
if self.task_name == "S_0D":
return self._create_S_0D_prompt(graph_data)
elif self.task_name == "S_1D":
return self._create_S_1D_prompt(graph_data)
elif self.task_name == "S_Modification":
return self._create_S_Modification_prompt(graph_data)
elif self.task_name == "M_Birth":
return self._create_M_Birth_prompt(graph_data)
elif self.task_name == "M_Merge":
return self._create_M_Merge_prompt(graph_data)
elif self.task_name=="M_Filtration":
return self._create_M_Filtration_prompt(graph_data)
elif self.task_name == "H_Selection":
return self._create_H_Selection_prompt(graph_data)
elif self.task_name == "H_Generation":
return self._create_H_Generation_prompt(graph_data)
elif self.task_name == "R_Selection":
return self._create_R_Selection_prompt(graph_data)
elif self.task_name == "R_Generation":
return self._create_R_Generation_prompt(graph_data)
elif self.task_name == "R_Directly":
return self._create_R_Directly_prompt(graph_data)
# elif task_type == "P_Prediction":
# return self._create_truedata_predict_prompt(graph_data)
else:
raise ValueError(f"Unsupported task type: {self.task_name}")
def _create_S_0D_prompt(self, graph_data):
"""Create topological structure identification prompt"""
graph_desc = self._graph_to_text(graph_data,weight=False)
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Given the following graph structure:
Graph Structure:
{graph_desc}
Please calculate the number of connected component in this graph(vertex that not connected to other vertex is not a connected component).
And strictly answer in following format:
Answer:
connected components: n
(e.g.
Answer:
connected components: 3"""
def _create_S_1D_prompt(self, graph_data):
"""Create topological structure identification prompt"""
graph_desc = self._graph_to_text(graph_data,weight=False)
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Given the following graph structure:
Graph Structure:
{graph_desc}
Please identify if 1-dimensional features (cycle holes) exist in the graph.(triangles are not cycle holes)
And strictly answer in following format:
Answer:
cycle holes: n
(e.g.
Answer:
cycle holes: 3"""
def _create_S_Modification_prompt(self, graph_data):
"""Create graph structure modification prompt"""
graph_desc = self._graph_to_text(graph_data,weight=False)
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Given the following graph structure:
Graph Structure:
{graph_desc}
Task:
Please identify the connected components in the graph and add one edge to reduce the number of connected components.
You can follow these steps:
Step1:Please identify the connected components in the graph.
Step2:Please add one edge between the different connected components.
Please strictly follow the format below:
Answer:
Edge to add: [u,v]
(e.g.
Answer:
Edge to add: [0,3]
"""
def _create_M_Birth_prompt(self, graph_data):
"""Create persistent homology calculation task prompt"""
graph_desc = self._graph_to_text(graph_data,weight=True)
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.
Graph Structure:
{graph_desc}
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.
You should follow these steps:
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).
Step2:Find the edges that first construct a cycle(Triangle is not cycle,Cycle should be at least 4 edges).
Step3:The birth time is the weight of the edge.
Rule:
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)
Please answer in the following format:
Answer:
birth time:[t]
(e.g.
Answer:
birth time:[3])
"""
def _create_M_Merge_prompt(self, graph_data):
"""Create persistent homology calculation task prompt"""
graph_desc = self._graph_to_text(graph_data,weight=True)
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.
Graph Structure:
{graph_desc}
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.
You can follow these steps:
Step1:Add edges to the graph according to the edge weights,and record the connected components.
Step2:Find the edge that first connect two different connected components.
Step3:The death time t is the weight of the edge.
Please answer in the following format:
Answer:
death time:[t]
(e.g.
Answer:
death time:[4])
Please ensure final answer strictly follows above format.
"""
def _create_M_Filtration_prompt(self,graph_data):
"""Create filtration_features_count task prompt"""
graph_desc = self._graph_to_text(graph_data,weight=True)
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.
Graph Structure:
{graph_desc}
Task:Count how many connected components are present at filtration value 3?
You can follow these steps:
Step1:Find the edges with weight less than or equal to 3.
Step2:Use the edges to construct a graph.
Step3:Count how many connected components are present in the graph.
Rule:Vertices are only introduced into the complex when their associated edges are added.
Please answer in the following format:
Answer:
connected components:[n]
(e.g.
Answer:
connected components:[3]
"""
def _create_H_Selection_prompt(self, graph_data):
"""Create filtration method selection prompt"""
graph_desc1 = self._graph_to_text(graph_data[0],weight=True)
graph_desc2 = self._graph_to_text(graph_data[1],weight=True)
return f""""You are a mathematical expert specializing in graph theory and persistent homology. Given the following two graph structures.
Graph structure:
graph1:
{graph_desc1}
graph2:
{graph_desc2}
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).
The 6 methods are (all methods filter from low value to high value):
Weight: Edge weight.
Degree: Number of edges connected to a node.
K-shell: Core level of a node based on iterative pruning by degree.
Closeness Centrality: Inverse of average shortest path to all other nodes.
Betweenness Centrality: Frequency a node lies on shortest paths between others.
Eigenvector Centrality: Node importance based on connections to other important nodes.
You can follow these steps:
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?
2.Consider what kind of topological features should be emphasized in the filtration: peripheral nodes, local clusters, bridge nodes, or strong/weak connections.
3.Match these needs to one of the complex filtration methods.
Your response should be in this format:
Answer:
Method: weight/degree/k_shell/closeness/betweenness/eigenvector
(e.g
Answer:
Method: k-shell
)
Please ensure your answer strictly follows this format.
"""
def _create_H_Generation_prompt(self, graph_data):
"""Create filteration value selection prompt"""
graph_desc1 = self._graph_to_text(graph_data[0])
graph_desc2 = self._graph_to_text(graph_data[1])
filtration_values = list(range(1,int(max(max(graph_data[0]['edge_attr']),max(graph_data[1]['edge_attr'])))+1))
return f"""You are a mathematical expert specializing in graph theory and persistent homology. Given the following two graph structures:
graph1 structure:
{graph_desc1}
graph2 structure:
{graph_desc2}
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).
You can follow these steps:
Step 1:Compare the structure of graph1 and graph2 to see which is denser, whether there are cycles,etc.
Step 2:From the given filtration values, identify values that trigger major topological changes in the graphs.
Step 3:Choose 5 filtration values that maximize the difference in persistence barcodes between the two graphs(the max filtration value should be 10).
Please answer in the following format:
Answer:
filtration value: [filtration value]
(e.g.
Answer:
filtration value: [1,3,4,7,10]
)
Please ensure your answer strictly follows this format.
"""
def _create_R_Selection_prompt(self, graph_data):
"""Create truedata filtration method selection prompt"""
graph_desc1 = self._graph_to_text(graph_data[0],weight=True)
graph_desc2 = self._graph_to_text(graph_data[1],weight=True)
graph_desc3 = self._graph_to_text(graph_data[2],weight=True)
graph_desc4 = self._graph_to_text(graph_data[3],weight=True)
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):
Graph1 Structure:
{graph_desc1}
Graph2 Structure:
{graph_desc2}
Graph3 Structure:
{graph_desc3}
Graph4 Structure:
{graph_desc4}
Task:Please select a filtration method from the following 6 methods that can classify the graph into 2 categories(each category has 2 graphs).
The 6 methods are (all methods filter from low value to high value):
Degree: Number of edges connected to a node.
Weight: Edge weight.
K-shell: Core level of a node based on iterative pruning by degree.
Closeness Centrality: Inverse of average shortest path to all other nodes.
Betweenness Centrality: Frequency a node lies on shortest paths between others.
Eigenvector Centrality: Node importance based on connections to other important nodes.
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.
Please answer in the following format:
Answer:
Method: weight/degree/k-shell/closeness/betweenness/eigenvector
(e.g.
Answer:
Method: k-shell
)
Please ensure your answer strictly follows this format.
"""
def _create_R_Generation_prompt(self, graph_data):
"""Create truedata filteration value selection prompt"""
graph_desc1 = self._graph_to_text(graph_data[0],weight=True)
graph_desc2 = self._graph_to_text(graph_data[1],weight=True)
graph_desc3 = self._graph_to_text(graph_data[2],weight=True)
graph_desc4 = self._graph_to_text(graph_data[3],weight=True)
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):
Graph1 Structure:
{graph_desc1}
Graph2 Structure:
{graph_desc2}
Graph3 Structure:
{graph_desc3}
Graph4 Structure:
{graph_desc4}
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).
You can follow these steps:
Step1:Compare the structure of 4 graphs.
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.
Please answer in the following format:
Answer:
Filtration value: [filtration values]
(e.g.
Answer:
Filtration value: [0.1,0.4,0.5,0.6,0.9,1]
)
Please ensure your answer strictly follows this format.
"""
def _create_filtration_edge_construction_prompt(self, graph_data):
"""Create filtration edge construction task prompt"""
graph_desc = self._graph_to_text(graph_data)
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.
Graph Structure:
{graph_desc}
Task: Construct filtration edges from the original edge list.
(e.g. Graph structure [0,1,3],[0,2,1],[1,3,2],[1,4,2],[2,3,3]
Filtration edge sequence:
Filtration value: 1
[0,2]
Filtration value: 2
[1,3],[1,4]
Filtration value: 3
[0,1],[2,3] )
Please strictly follow these steps:
1. First sort the original edge list by weight in ascending order
2. Divide edges added at each filtration value
Please answer in the following format:
===FILTRATION_START===
For each different edge weight, list the edges added at that weight, format as:
**Value=1**
(1,2)
**Value=2**
(1,3)
**Value=3**
(2,3)
...continue for other weights
===FILTRATION_END===
Please ensure strict adherence to the above format. Do not add extra explanations, only include content required by the format
"""
def _create_R_Directly_prompt(self, graph_data):
"""Create truedata classfy prompt"""
graph_desc1 = self._graph_to_text(graph_data[0],weight=True)
graph_desc2 = self._graph_to_text(graph_data[1],weight=True)
graph_desc3 = self._graph_to_text(graph_data[2],weight=True)
graph_desc4 = self._graph_to_text(graph_data[3],weight=True)
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):
Graph1 Structure:
{graph_desc1}
Graph2 Structure:
{graph_desc2}
Graph3 Structure:
{graph_desc3}
Graph4 Structure:
{graph_desc4}
Task:Please classify them into 2 categories(each category has 2 graphs) according to their topological structure.
Please answer in the following format:
Answer:
Category: [category1 graph index,category2 graph index]
(e.g.
Answer:
Category: [[1,3],[2,4]])
Please ensure your answer strictly follows this format.
"""
def _graph_to_text(self, graph_data, weight=True, sort=True):
"""图结构文本转换"""
num_nodes = graph_data['num_nodes']
num_edges = graph_data['num_edges']
edge_index = graph_data['edge_index']
# 收集所有边及其权重
edges = []
for i in range(0, len(edge_index), 2):
src = edge_index[i]
dst = edge_index[i + 1]
if weight:
weight_val = 1.0 # 默认权重为1
else:
weight_val = 1.0
edges.append((weight_val, src, dst))
if sort:
edges.sort(key=lambda x: x[0])
# Generate text
text = f"Graph with {num_nodes} nodes and {num_edges} edges:\n"
if weight:
for weight_val, src, dst in edges:
text += f"Node {src}-[{weight_val:.2f}]-Node {dst}\n"
else:
for weight_val, src, dst in edges:
text += f"Node {src}-Node {dst}\n"
return text
def _filt_edges_to_text(self, graph_data,sort=True):
"""Convert filtration complex to text"""
num_nodes = graph_data['num_nodes']
num_edges = graph_data['num_edges']
edge_index = graph_data['edge_index']
edges = []
for i in range(edge_index.shape[1]):
src = edge_index[0, i].item()
dst = edge_index[1, i].item()
if hasattr(graph_data, 'edge_attr') and graph_data.edge_attr is not None:
weight = graph_data.edge_attr[i].item()
else:
weight = 1.0
edges.append((weight, src, dst))
if sort:
edges.sort(key=lambda x: x[0])
# Generate text
text = f"Graph with {num_nodes} nodes and {num_edges} edges:\n"
for weight, src, dst in edges:
text += f"Node {src}-[{weight:.2f}]-Node {dst}\n"
return text
def _complex_to_text(self, graph_data):
"""Complex structure description"""
simplex = graph_data.task_simplex[0]
dim = len(simplex) - 1
verts = ", ".join(str(v) for v in simplex)
if dim == 0:
desc = f"vertex {verts}"
elif dim == 1:
a, b = simplex
desc = f"edge between {a} and {b}"
elif dim == 2:
a, b, c = simplex
desc = f"triangle with vertices {a}, {b}, {c}"
else:
desc = f"{dim}-simplex spanning vertices {verts}"
text = f"aim simplex: {desc}"
return text
def _ph_to_text(self, ph_data):
"""Persistent homology barcode description"""
text = ""
for dim in ['0dim', '1dim']:
if dim in ph_data:
text += f"\n{dim} features:\n"
for i, (birth, death) in enumerate(ph_data[dim]):
persistence = death - birth
text += f"Feature {i}: birth {birth:.2f}, death {death:.2f}, persistence {persistence:.2f}\n"
return text
# def _create_simplicial_complex_construction_prompt(self, graph_data):
# """Create simplicial complex construction task prompt"""
# filt_edges_desc = self._filt_edges_to_text(graph_data)
# 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.
# Filtration Edge Sequence:
# {filt_edges_desc}
# Task: Build complex sequence (2-dimensional simplex) from filtration edge list.
# Please strictly follow these steps:
# 1. For each filtration value, build a complex containing that filtration value and all previous filtration values
# 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])
# Please answer in the following format:
# List simplicial complexes [(complex),filtration value]:
# ===SIMPLICIAL_COMPLEX_START===
# [(0,1,2),3]
# [(0,1,4),3]
# [(0,3,4),4]
# ...
# ===SIMPLICIAL_COMPLEX_END===
# Note:
# - 0-dimensional simplices are omitted, only list 1-dimensional and 2-dimensional simplices
# - 2-dimensional simplex is a triangle formed by three edges (all edge feature values are less than or equal to filtration value)
# Please ensure strict adherence to the above format. Do not add extra explanations, only include content required by the format
# """
# def _create_filteration_value_change_prompt(self, graph_data):
# edge_str = "graph structure:\n"
# edge_str += self._filt_edges_to_text(graph_data)
# pd_str = "current persistent homology results:\n"
# pd_str += self._ph_to_text(graph_data.vr_10_pd)
# question = f"""graph structure:{edge_str}
# current persistent homology results:{pd_str}
# 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?
# Please answer in the following format:
# Answer:
# Yes/No
# (e.g.
# Answer:
# Yes
# )
# """
# return question
# def _create_truedata_predict_prompt(self, graph_data):
# """Create truedata predict prompt"""
# graph_desc1 = self._graph_to_text(graph_data[0],weight=True)
# graph_desc2 = self._graph_to_text(graph_data[1],weight=True)
# graph_desc3 = self._graph_to_text(graph_data[2],weight=True)
# graph_desc4 = self._graph_to_text(graph_data[3],weight=True)
# graph_desc5 = self._graph_to_text(graph_data[4],weight=True)
# graph_desc6 = self._graph_to_text(graph_data[5],weight=True)
# graph_desc7 = self._graph_to_text(graph_data[6],weight=True)
# 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]
# 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:
# day1:
# {graph_desc1}
# day2:
# {graph_desc2}
# day3:
# {graph_desc3}
# day4:
# {graph_desc4}
# day5:
# {graph_desc5}
# day6:
# {graph_desc6}
# day7:
# {graph_desc7}
# closing price list(from day):{closing_price}
# Task:Please predict the closing price of day8.
# Please answer in the following format:
# Answer:
# Closing price: [closing price]
# (e.g.
# Answer:
# Closing price: 1000
# )
# Please ensure your answer strictly follows this format.
# """ |