MCPcopy Create free account
hub / github.com/microsoft/JARVIS / GraphSampler

Class GraphSampler

taskbench/graph_sampler.py:8–203  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6
7random.seed(0)
8class GraphSampler:
9 def __init__(self, graph: nx.Graph = None, file_name = None):
10 if file_name:
11 with open(file_name, "r") as f:
12 data = json.load(f)
13
14 # Represent your graph in NetworkX
15 graph = nx.DiGraph()
16
17 # Add nodes to the graph
18 if "input-type" in data["nodes"][0]:
19 for node in data["nodes"]:
20 graph.add_node(node["id"], desc=node["desc"], input_type=node["input-type"], output_type=node["output-type"])
21 else:
22 for node in data["nodes"]:
23 graph.add_node(node["id"], desc=node["desc"], parameters=node["parameters"])
24
25 # Add edges to the graph
26 for link in data["links"]:
27 graph.add_edge(link["source"], link["target"], type=link["type"])
28
29 self.graph = graph
30
31 def sample_subgraph_by_weight(self, number_weights, method_weights):
32 method = random.choices(list(method_weights.keys()), weights=list(method_weights.values()))[0]
33 if method == "single":
34 tool_number = 1
35 else:
36 tool_number = random.choices(list(number_weights.keys()), weights=list(number_weights.values()))[0]
37 return self.sample_subgraph(tool_number, sample_method=method)
38
39 def sample_subgraph(self, num_nodes=3, sample_method="chain"):
40 seed_node = random.choice(list(self.graph.nodes))
41 if sample_method == "single":
42 sub_G = nx.DiGraph()
43 sub_G.add_node(seed_node)
44 return sub_G
45 elif sample_method == "chain":
46 return self.sample_subgraph_chain(seed_node, num_nodes)
47 elif sample_method == "dag":
48 return self.sample_subgraph_dag(seed_node, num_nodes)
49 else:
50 raise ValueError("Invalid sample method")
51
52 def sample_subgraph_chain(self, seed_node, num_nodes):
53 # Create a list to store the sub-graph nodes
54 sub_graph_nodes = [seed_node]
55 head_node = seed_node
56 tail_node = seed_node
57 edges = []
58
59 # Keep adding nodes until we reach the desired number
60 while len(sub_graph_nodes) < num_nodes:
61 # Get the neighbors of the last node in the sub-graph
62 head_node_neighbors = list(self.graph.predecessors(head_node))
63 tail_node_neighbors = list(self.graph.successors(tail_node))
64 neighbors = head_node_neighbors + tail_node_neighbors
65

Callers 2

mainFunction · 0.90
sample_subgraphFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected