LLM4PH / evaluate_code /graph_embed.py
lihaogx's picture
Upload 12 files
9f50319 verified
Raw
History Blame Contribute Delete
24.6 kB
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.
# """