code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
ret = self.get_edge_ids_by_node_ids(node_a, node_b)
if not ret:
return None
else:
return ret[0] | def get_first_edge_id_by_node_ids(self, node_a, node_b) | Returns the first (and possibly only) edge connecting node_a and node_b. | 2.403947 | 2.272178 | 1.057992 |
list_of_components = []
# Run the algorithm on each of the connected components of the graph
components = get_connected_components_as_subgraphs(graph)
for component in components:
# --Call the internal biconnnected components function to find
# --the edge lists for this particular... | def find_biconnected_components(graph) | Finds all the biconnected components in a graph.
Returns a list of lists, each containing the edges that form a biconnected component.
Returns an empty list for an empty graph. | 4.859263 | 4.883123 | 0.995114 |
list_of_graphs = []
list_of_components = find_biconnected_components(graph)
for edge_list in list_of_components:
subgraph = get_subgraph_from_edge_list(graph, edge_list)
list_of_graphs.append(subgraph)
return list_of_graphs | def find_biconnected_components_as_subgraphs(graph) | Finds the biconnected components and returns them as subgraphs. | 2.119065 | 2.056737 | 1.030305 |
articulation_vertices = []
all_nodes = graph.get_all_node_ids()
if len(all_nodes) == 0:
return articulation_vertices
# Run the algorithm on each of the connected components of the graph
components = get_connected_components_as_subgraphs(graph)
for component in components:
... | def find_articulation_vertices(graph) | Finds all of the articulation vertices within a graph.
Returns a list of all articulation vertices within the graph.
Returns an empty list for an empty graph. | 4.211879 | 4.061112 | 1.037124 |
edge_list = []
while len(edge_stack) > 0:
edge_id = edge_stack.popleft()
edge_list.append(edge_id)
edge = graph.get_edge(edge_id)
tpl_a = (u, v)
tpl_b = (v, u)
if tpl_a == edge['vertices'] or tpl_b == edge['vertices']:
break
return edge_list | def output_component(graph, edge_stack, u, v) | Helper function to pop edges off the stack and produce a list of them. | 2.885208 | 2.742081 | 1.052196 |
list_of_cut_vertices = set()
if graph.num_nodes() == 0:
return list(list_of_cut_vertices)
dfs_count = 0
root_dfs_count = 1
dfs_stack = deque()
visited = defaultdict(lambda: False)
parent = defaultdict(lambda: None)
children = defaultdict(lambda: [])
depth = {}
low =... | def _internal_get_cut_vertex_list(graph) | Works on a single connected component to produce the node list of cut vertices.
Returns a list of nodes.
Returns an empty list if there are no nodes in the graph (i.e. if it's an empty graph). | 2.746967 | 2.725144 | 1.008008 |
ordering, parent_lookup, children_lookup = depth_first_search_with_parent_data(graph, root_node)
return ordering | def depth_first_search(graph, root_node=None) | Searches through the tree in a breadth-first fashion.
If root_node is None, an arbitrary node will be used as the root.
If root_node is not None, it will be used as the root for the search tree.
Returns a list of nodes, in the order that they were reached. | 6.822851 | 8.246007 | 0.827413 |
ordering = []
parent_lookup = {}
children_lookup = defaultdict(lambda: [])
all_nodes = graph.get_all_node_ids()
if not all_nodes:
return ordering, parent_lookup, children_lookup
stack = deque()
discovered = defaultdict(lambda: False)
unvisited_nodes = set(all_nodes)
i... | def depth_first_search_with_parent_data(graph, root_node = None, adjacency_lists = None) | Performs a depth-first search with visiting order of nodes determined by provided adjacency lists,
and also returns a parent lookup dict and a children lookup dict. | 3.064041 | 3.001589 | 1.020807 |
ordering = []
all_nodes = graph.get_all_node_ids()
if not all_nodes:
return ordering
queue = deque()
discovered = defaultdict(lambda: False)
to_visit = set(all_nodes)
if root_node is None:
root_node = all_nodes[0]
discovered[root_node] = True
queue.appendleft... | def breadth_first_search(graph, root_node=None) | Searches through the tree in a breadth-first fashion.
If root_node is None, an arbitrary node will be used as the root.
If root_node is not None, it will be used as the root for the search tree.
Returns a list of nodes, in the order that they were reached. | 2.775625 | 2.846314 | 0.975165 |
node_pairs = list(graph.nodes.items())
edge_pairs = list(graph.edges.items())
if node_renderer is None:
node_renderer_wrapper = lambda nid: ''
else:
node_renderer_wrapper = lambda nid: ' [%s]' % ','.join(
['%s=%s' % tpl for tpl in list(node_renderer(graph, nid).items())... | def graph_to_dot(graph, node_renderer=None, edge_renderer=None) | Produces a DOT specification string from the provided graph. | 2.446048 | 2.405661 | 1.016788 |
list_of_components = []
component = [] # Not strictly necessary due to the while loop structure, but it helps the automated analysis tools
# Store a list of all unreached vertices
unreached = set(graph.get_all_node_ids())
to_explore = deque()
while len(unreached) > 0:
# This hap... | def get_connected_components(graph) | Finds all connected components of the graph.
Returns a list of lists, each containing the nodes that form a connected component.
Returns an empty list for an empty graph. | 3.502339 | 3.585843 | 0.976713 |
components = get_connected_components(graph)
list_of_graphs = []
for c in components:
edge_ids = set()
nodes = [graph.get_node(node) for node in c]
for n in nodes:
# --Loop through the edges in each node, to determine if it should be included
for e in n... | def get_connected_components_as_subgraphs(graph) | Finds all connected components of the graph.
Returns a list of graph objects, each representing a connected component.
Returns an empty list for an empty graph. | 2.978239 | 3.087244 | 0.964692 |
edge_id = super(UndirectedGraph, self).new_edge(node_a, node_b, cost)
self.nodes[node_b]['edges'].append(edge_id)
return edge_id | def new_edge(self, node_a, node_b, cost=1) | Adds a new, undirected edge between node_a and node_b with a cost.
Returns the edge id of the new edge. | 2.551523 | 2.6056 | 0.979246 |
node = self.get_node(node_id)
flattened_nodes_list = []
for a, b in [self.get_edge(edge_id)['vertices'] for edge_id in node['edges']]:
flattened_nodes_list.append(a)
flattened_nodes_list.append(b)
node_set = set(flattened_nodes_list)
if node_id in... | def neighbors(self, node_id) | Find all the nodes where there is an edge from the specified node to that node.
Returns a list of node ids. | 2.590124 | 2.473626 | 1.047096 |
edge = self.get_edge(edge_id)
# Remove the edge from the "from node"
# --Determine the from node
from_node_id = edge['vertices'][0]
from_node = self.get_node(from_node_id)
# --Remove the edge from it
from_node['edges'].remove(edge_id)
# Remove ... | def delete_edge_by_id(self, edge_id) | Removes the edge identified by "edge_id" from the graph. | 2.102714 | 2.066679 | 1.017436 |
# Grab the edge
edge = self.get_edge(edge_id)
# Remove the edge from the original "target node"
original_target_node_id = edge['vertices'][1]
original_target_node = self.get_node(original_target_node_id)
original_target_node['edges'].remove(edge_id)
# A... | def move_edge_target(self, edge_id, node_a) | Moves an edge so that it targets node_a. | 2.108018 | 2.088251 | 1.009466 |
mst = []
if graph.num_nodes() == 0:
return mst
if graph.num_edges() == 0:
return mst
connected_components = get_connected_components(graph)
if len(connected_components) > 1:
raise DisconnectedGraphError
edge_list = kruskal_mst(graph)
return edge_list | def find_minimum_spanning_tree(graph) | Calculates a minimum spanning tree for a graph.
Returns a list of edges that define the tree.
Returns an empty list for an empty graph. | 3.091075 | 3.066584 | 1.007986 |
edge_list = find_minimum_spanning_tree(graph)
subgraph = get_subgraph_from_edge_list(graph, edge_list)
return subgraph | def find_minimum_spanning_tree_as_subgraph(graph) | Calculates a minimum spanning tree and returns a graph representation. | 2.456879 | 2.402054 | 1.022824 |
msf = []
if graph.num_nodes() == 0:
return msf
if graph.num_edges() == 0:
return msf
connected_components = get_connected_components_as_subgraphs(graph)
for subgraph in connected_components:
edge_list = kruskal_mst(subgraph)
msf.append(edge_list)
return ms... | def find_minimum_spanning_forest(graph) | Calculates the minimum spanning forest of a disconnected graph.
Returns a list of lists, each containing the edges that define that tree.
Returns an empty list for an empty graph. | 2.849942 | 2.675428 | 1.065228 |
forest = find_minimum_spanning_forest(graph)
list_of_subgraphs = [get_subgraph_from_edge_list(graph, edge_list) for edge_list in forest]
return list_of_subgraphs | def find_minimum_spanning_forest_as_subgraphs(graph) | Calculates the minimum spanning forest and returns a list of trees as subgraphs. | 2.486108 | 2.434867 | 1.021045 |
edges_accepted = 0
ds = DisjointSet()
pq = PriorityQueue()
accepted_edges = []
label_lookup = {}
nodes = graph.get_all_node_ids()
num_vertices = len(nodes)
for n in nodes:
label = ds.add_set()
label_lookup[n] = label
edges = graph.get_all_edge_objects()
for... | def kruskal_mst(graph) | Implements Kruskal's Algorithm for finding minimum spanning trees.
Assumes a non-empty, connected graph. | 2.387379 | 2.40611 | 0.992215 |
root_node = ordering[0]
for i in range(2, len(ordering)):
current_node = ordering[i]
if graph.adjacent(current_node, root_node):
path = []
while current_node != root_node:
path.append(current_node)
current_node = parent_lookup[current_... | def __get_cycle(graph, ordering, parent_lookup) | Gets the main cycle of the dfs tree. | 2.058202 | 1.955564 | 1.052485 |
list_of_segments = []
node_object = graph.get_node(node)
for e in node_object['edges']:
list_of_segments.append(e)
return list_of_segments | def __get_segments_from_node(node, graph) | Calculates the segments that can emanate from a particular node on the main cycle. | 3.055458 | 2.707564 | 1.12849 |
list_of_segments = []
# We work through the cycle in a bottom-up fashion
for n in cycle_path[::-1]:
segments = __get_segments_from_node(n, graph)
if segments:
list_of_segments.append(segments)
return list_of_segments | def __get_segments_from_cycle(graph, cycle_path) | Calculates the segments that emanate from the main cycle. | 3.313726 | 3.144007 | 1.053982 |
# Copy the entire graph
local_graph = copy.deepcopy(graph)
# Remove all the edges that aren't in the list
edges_to_delete = [x for x in local_graph.get_all_edge_ids() if x not in edges]
for e in edges_to_delete:
local_graph.delete_edge_by_id(e)
# Remove all the vertices that aren'... | def make_subgraph(graph, vertices, edges) | Converts a subgraph given by a list of vertices and edges into a graph object. | 1.978237 | 1.964455 | 1.007015 |
udg = UndirectedGraph()
# Copy the graph
# --Copy nodes
# --Copy edges
udg.nodes = copy.deepcopy(dg.nodes)
udg.edges = copy.deepcopy(dg.edges)
udg.next_node_id = dg.next_node_id
udg.next_edge_id = dg.next_edge_id
# Convert the directed edges into undirected edges
for edge... | def convert_graph_directed_to_undirected(dg) | Converts a directed graph into an undirected graph. Directed edges are made undirected. | 2.51966 | 2.477006 | 1.01722 |
# With directed edges, we can just hash the to and from node id tuples and if
# a node happens to conflict with one that already exists, we delete it
# --For aesthetic, we sort the edge ids so that lower edge ids are kept
lookup = {}
edges = sorted(dg.get_all_edge_ids())
for edge_id in edg... | def remove_duplicate_edges_directed(dg) | Removes duplicate edges from a directed graph. | 7.114655 | 7.193705 | 0.989011 |
# With undirected edges, we need to hash both combinations of the to-from node ids, since a-b and b-a are equivalent
# --For aesthetic, we sort the edge ids so that lower edges ids are kept
lookup = {}
edges = sorted(udg.get_all_edge_ids())
for edge_id in edges:
e = udg.get_edge(edge_id... | def remove_duplicate_edges_undirected(udg) | Removes duplicate edges from an undirected graph. | 4.742454 | 4.771925 | 0.993824 |
node_set = set()
for edge_id in edge_list:
edge = graph.get_edge(edge_id)
a, b = edge['vertices']
node_set.add(a)
node_set.add(b)
return list(node_set) | def get_vertices_from_edge_list(graph, edge_list) | Transforms a list of edges into a list of the nodes those edges connect.
Returns a list of nodes, or an empty list if given an empty list. | 2.258706 | 2.240249 | 1.008239 |
node_list = get_vertices_from_edge_list(graph, edge_list)
subgraph = make_subgraph(graph, node_list, edge_list)
return subgraph | def get_subgraph_from_edge_list(graph, edge_list) | Transforms a list of edges into a subgraph. | 2.808847 | 2.705328 | 1.038265 |
node_mapping = {}
edge_mapping = {}
for node in addition_graph.get_all_node_objects():
node_id = node['id']
new_id = main_graph.new_node()
node_mapping[node_id] = new_id
for edge in addition_graph.get_all_edge_objects():
edge_id = edge['id']
old_vertex_a_i... | def merge_graphs(main_graph, addition_graph) | Merges an ''addition_graph'' into the ''main_graph''.
Returns a tuple of dictionaries, mapping old node ids and edge ids to new ids. | 1.721265 | 1.562636 | 1.101514 |
if is_adjacency_matrix_symmetric(adjacency_matrix):
graph = UndirectedGraph()
else:
graph = DirectedGraph()
node_column_mapping = []
num_columns = len(adjacency_matrix)
for _ in range(num_columns):
node_id = graph.new_node()
node_column_mapping.append(node_id)
... | def create_graph_from_adjacency_matrix(adjacency_matrix) | Generates a graph from an adjacency matrix specification.
Returns a tuple containing the graph and a list-mapping of node ids to matrix column indices.
The graph will be an UndirectedGraph if the provided adjacency matrix is symmetric.
The graph will be a DirectedGraph if the provided adjacency ma... | 3.03229 | 2.794433 | 1.085118 |
# Verify that the matrix is square
num_columns = len(adjacency_matrix)
for column in adjacency_matrix:
# In a square matrix, every row should be the same length as the number of columns
if len(column) != num_columns:
return False
# Loop through the bottom half of the ma... | def is_adjacency_matrix_symmetric(adjacency_matrix) | Determines if an adjacency matrix is symmetric.
Ref: http://mathworld.wolfram.com/SymmetricMatrix.html | 3.896163 | 4.02075 | 0.969014 |
all_nodes = graph.get_all_node_ids()
if start not in all_nodes:
raise NonexistentNodeError(start)
if goal not in all_nodes:
raise NonexistentNodeError(goal)
came_from, cost_so_far, goal_reached = _a_star_search_internal(graph, start, goal)
if goal_reached:
path = recons... | def a_star_search(graph, start, goal) | Runs an A* search on the specified graph to find a path from the ''start'' node to the ''goal'' node.
Returns a list of nodes specifying a minimal path between the two nodes.
If no path exists (disconnected components), returns an empty list. | 2.174404 | 2.221442 | 0.978825 |
frontier = PriorityQueue()
frontier.put(start, 0)
came_from = {start: None}
cost_so_far = {start: 0}
goal_reached = False
while not frontier.empty():
current = frontier.get()
if current == goal:
goal_reached = True
break
for next_node in gr... | def _a_star_search_internal(graph, start, goal) | Performs an A* search, returning information about whether the goal node was reached
and path cost information that can be used to reconstruct the path. | 1.294592 | 1.31318 | 0.985844 |
self.__label_counter += 1
new_label = self.__label_counter
self.__forest[new_label] = -1 # All new sets have their parent set to themselves
self.__set_counter += 1
return new_label | def add_set(self) | Adds a new set to the forest.
Returns a label by which the new set can be referenced | 7.685897 | 4.882961 | 1.574024 |
queue = []
current_node = node_label
while self.__forest[current_node] >= 0:
queue.append(current_node)
current_node = self.__forest[current_node]
root_node = current_node
# Path compression
for n in queue:
self.__forest[n] = ... | def find(self, node_label) | Finds the set containing the node_label.
Returns the set label. | 3.4025 | 3.1978 | 1.064013 |
# Base case to avoid work
if label_a == label_b:
return
# Find the tree root of each node
root_a = self.find(label_a)
root_b = self.find(label_b)
# Avoid merging a tree to itself
if root_a == root_b:
return
self.__intern... | def union(self, label_a, label_b) | Joins two sets into a single new set.
label_a, label_b can be any nodes within the sets | 4.022912 | 3.877706 | 1.037446 |
# Merge the trees, smaller to larger
update_rank = False
# --Determine the larger tree
rank_a = self.__forest[root_a]
rank_b = self.__forest[root_b]
if rank_a < rank_b:
larger = root_b
smaller = root_a
else:
larger = ro... | def __internal_union(self, root_a, root_b) | Internal function to join two set trees specified by root_a and root_b.
Assumes root_a and root_b are distinct. | 3.183581 | 3.110805 | 1.023394 |
# Determine connected components as subgraphs; their planarity is independent of each other
connected_components = get_connected_components_as_subgraphs(graph)
for component in connected_components:
# Biconnected components likewise have independent planarity
biconnected_components = fi... | def is_planar(graph) | Determines whether a graph is planar or not. | 3.380724 | 3.524996 | 0.959072 |
# --First pass: Determine edge and vertex counts validate Euler's Formula
num_nodes = graph.num_nodes()
num_edges = graph.num_edges()
# --We can guarantee that if there are 4 or less nodes, then the graph is planar
# --A 4-node simple graph has a maximum of 6 possible edges (K4); this will alw... | def __is_subgraph_planar(graph) | Internal function to determine if a subgraph is planar. | 8.32554 | 7.968565 | 1.044798 |
dfs_data = __get_dfs_data(graph, adj)
dfs_data['graph'] = graph
dfs_data['adj'] = adj
L1, L2 = __low_point_dfs(dfs_data)
dfs_data['lowpoint_1_lookup'] = L1
dfs_data['lowpoint_2_lookup'] = L2
edge_weights = __calculate_edge_weights(dfs_data)
dfs_data['edge_weights'] = edge_weights... | def __setup_dfs_data(graph, adj) | Sets up the dfs_data object, for consistency. | 2.921278 | 2.779643 | 1.050954 |
graph = dfs_data['graph']
weights = {}
for edge_id in graph.get_all_edge_ids():
edge_weight = __edge_weight(edge_id, dfs_data)
weights[edge_id] = edge_weight
return weights | def __calculate_edge_weights(dfs_data) | Calculates the weight of each edge, for embedding-order sorting. | 3.050183 | 2.952888 | 1.032949 |
new_adjacency_lists = {}
adjacency_lists = dfs_data['adj']
edge_weights = dfs_data['edge_weights']
edge_lookup = dfs_data['edge_lookup']
for node_id, adj_list in list(adjacency_lists.items()):
node_weight_lookup = {}
frond_lookup = {}
for node_b in adj_list:
... | def __sort_adjacency_lists(dfs_data) | Sorts the adjacency list representation by the edge weights. | 2.993628 | 2.90227 | 1.031478 |
u = dfs_data['ordering'][0]
large_n = {}
large_n[u] = 0
stem = {}
stem[u] = u
b = {}
b[u] = 1
__branch_point_dfs_recursive(u, large_n, b, stem, dfs_data)
dfs_data['N_u_lookup'] = large_n
dfs_data['b_u_lookup'] = b
return | def __branch_point_dfs(dfs_data) | DFS that calculates the b(u) and N(u) lookups, and also reorders the adjacency lists. | 4.799255 | 3.331697 | 1.440484 |
first_vertex = dfs_data['adj'][u][0]
large_w = wt(u, first_vertex, dfs_data)
if large_w % 2 == 0:
large_w += 1
v_I = 0
v_II = 0
for v in [v for v in dfs_data['adj'][u] if wt(u, v, dfs_data) <= large_w]:
stem[u] = v # not in the original paper, but a logical extension based o... | def __branch_point_dfs_recursive(u, large_n, b, stem, dfs_data) | A recursive implementation of the BranchPtDFS function, as defined on page 14 of the paper. | 3.015043 | 2.92813 | 1.029682 |
u = dfs_data['ordering'][0]
dfs_data['LF'] = []
dfs_data['RF'] = []
dfs_data['FG'] = {}
n = dfs_data['graph'].num_nodes()
f0 = (0, n)
g0 = (0, n)
L0 = {'u': 0, 'v': n}
R0 = {'x': 0, 'y': n}
dfs_data['LF'].append(f0)
dfs_data['RF'].append(g0)
dfs_data['FG'][0] = [L0, ... | def __embed_branch(dfs_data) | Builds the combinatorial embedding of the graph. Returns whether the graph is planar. | 3.595105 | 3.208778 | 1.120397 |
#print "\nu: {}\nadj: {}".format(u, dfs_data['adj'][u])
#print 'Pre-inserts'
#print "FG: {}".format(dfs_data['FG'])
#print "LF: {}".format(dfs_data['LF'])
#print "RF: {}".format(dfs_data['RF'])
for v in dfs_data['adj'][u]:
#print "\nu, v: {}, {}".format(u, v)
#print "dfs_u... | def __embed_branch_recursive(u, dfs_data) | A recursive implementation of the EmbedBranch function, as defined on pages 8 and 22 of the paper. | 3.576265 | 3.566858 | 1.002637 |
w = L1(v, dfs_data)
d_u = D(u, dfs_data)
d_w = D(w, dfs_data)
# Embed uw
successful = __embed_frond(u, w, dfs_data)
if not successful:
return False
# Embed a branch marker uu on the side opposite to uw, in the same frond block
#successful = __embed_frond(u, v, dfs_data, as... | def __insert_branch(u, v, dfs_data) | Embeds a branch Bu(v) (as described on page 22 of the paper). Returns whether the embedding was successful. | 5.851254 | 5.035939 | 1.161899 |
# --We should only ever see u-cases 1 and 2
if case_3:
# --We should never get here
return False
comp_d_w = abs(d_w)
#if case_1:
# --Add the frond to the left side
__insert_frond_LF(d_w, d_u, dfs_data)
# --Add uw to Lm
m = dfs_data['FG']['m']
Lm = L(m, dfs_dat... | def __do_case_5_work(d_w, d_u, case_1, case_2, case_3, dfs_data) | Encapsulates the work that will be done for case 5 of __embed_frond,
since it gets used in more than one place. | 5.518186 | 5.202285 | 1.060724 |
# --We should only ever see u-cases 1 and 3
if case_2:
# --We should never get here
return False
comp_d_w = abs(d_w)
# --Add the frond to the right side
__insert_frond_RF(d_w, d_u, dfs_data)
# --Add uw to Rm
m = dfs_data['FG']['m']
Rm = R(m, dfs_data)
if comp_... | def __do_case_6_work(d_w, d_u, case_1, case_2, case_3, dfs_data) | Encapsulates the work that will be done for case 6 of __embed_frond,
since it gets used in more than one place. | 5.384212 | 5.023468 | 1.071812 |
# --Add the frond to the right side
dfs_data['RF'].append( (d_w, d_u) )
dfs_data['FG']['r'] += 1
dfs_data['last_inserted_side'] = 'RF' | def __insert_frond_RF(d_w, d_u, dfs_data) | Encapsulates the process of inserting a frond uw into the right side frond group. | 7.601625 | 6.197546 | 1.226554 |
# --Add the frond to the left side
dfs_data['LF'].append( (d_w, d_u) )
dfs_data['FG']['l'] += 1
dfs_data['last_inserted_side'] = 'LF' | def __insert_frond_LF(d_w, d_u, dfs_data) | Encapsulates the process of inserting a frond uw into the left side frond group. | 7.919363 | 6.320854 | 1.252894 |
FG = dfs_data['FG']
m = FG['m']
FGm = FG[m]
FGm1 = FG[m-1]
if FGm[0]['u'] < FGm1[0]['u']:
FGm1[0]['u'] = FGm[0]['u']
if FGm[0]['v'] > FGm1[0]['v']:
FGm1[0]['v'] = FGm[0]['v']
if FGm[1]['x'] < FGm1[1]['x']:
FGm1[1]['x'] = FGm[1]['x']
if FGm[1]['y'] > FGm1[... | def merge_Fm(dfs_data) | Merges Fm-1 and Fm, as defined on page 19 of the paper. | 2.084951 | 2.061239 | 1.011504 |
l = dfs_data['FG']['l']
w, z = dfs_data['LF'][l]
return __check_conflict_fronds(x, y, w, z, dfs_data) | def __check_left_side_conflict(x, y, dfs_data) | Checks to see if the frond xy will conflict with a frond on the left side of the embedding. | 10.355797 | 7.747295 | 1.336698 |
r = dfs_data['FG']['r']
w, z = dfs_data['RF'][r]
return __check_conflict_fronds(x, y, w, z, dfs_data) | def __check_right_side_conflict(x, y, dfs_data) | Checks to see if the frond xy will conflict with a frond on the right side of the embedding. | 10.489802 | 8.039564 | 1.304773 |
# Case 1: False frond and corresponding branch marker
# --x and w should both be negative, and either xy or wz should be the same value uu
if x < 0 and w < 0 and (x == y or w == z):
# --Determine if the marker and frond correspond (have the same low-value)
if x == w:
return... | def __check_conflict_fronds(x, y, w, z, dfs_data) | Checks a pair of fronds to see if they conflict. Returns True if a conflict was found, False otherwise. | 6.704047 | 6.313391 | 1.061877 |
buv = B(u, v, dfs_data)
new_list = []
for edge_id in buv:
edge = dfs_data['graph'].get_edge(edge_id)
j, k = edge['vertices']
d_x = D(j, dfs_data)
d_y = D(k, dfs_data)
if d_x < d_y:
smaller = d_x
larger = d_y
else:
small... | def __dfsify_branch_uv(u, v, dfs_data) | Helper function to convert the output of Bu(v) from edge ids to dfs-ordered fronds. | 3.451668 | 2.900815 | 1.189896 |
ordering, parent_lookup, children_lookup = depth_first_search_with_parent_data(graph, adjacency_lists=adj)
ordering_lookup = dict(list(zip(ordering, list(range(1, len(ordering) + 1)))))
node_lookup = dict(list(zip(list(range(1, len(ordering) + 1)), ordering)))
edge_lookup = {}
for edge_id in g... | def __get_dfs_data(graph, adj=None) | Internal function that calculates the depth-first search of the graph.
Returns a dictionary with the following data:
* 'ordering': A dfs-ordering list of nodes
* 'ordering_lookup': A lookup dict mapping nodes to dfs-ordering
* 'node_lookup': A lookup dict mapping dfs-ordering to n... | 2.029175 | 1.82892 | 1.109494 |
adj = {}
for node in graph.get_all_node_ids():
neighbors = graph.neighbors(node)
adj[node] = neighbors
return adj | def __calculate_adjacency_lists(graph) | Builds an adjacency list representation for the graph, since we can't guarantee that the
internal representation of the graph is stored that way. | 3.752598 | 3.593675 | 1.044223 |
lowpoint_1_lookup = {}
lowpoint_2_lookup = {}
ordering = dfs_data['ordering']
for node in ordering:
low_1, low_2 = __get_lowpoints(node, dfs_data)
lowpoint_1_lookup[node] = low_1
lowpoint_2_lookup[node] = low_2
return lowpoint_1_lookup, lowpoint_2_lookup | def __get_all_lowpoints(dfs_data) | Calculates the lowpoints for each node in a graph. | 2.499841 | 2.181065 | 1.146156 |
ordering_lookup = dfs_data['ordering_lookup']
t_u = T(node, dfs_data)
sorted_t_u = sorted(t_u, key=lambda a: ordering_lookup[a])
lowpoint_1 = sorted_t_u[0]
lowpoint_2 = sorted_t_u[1]
return lowpoint_1, lowpoint_2 | def __get_lowpoints(node, dfs_data) | Calculates the lowpoints for a single node in a graph. | 3.457542 | 3.261688 | 1.060047 |
graph = dfs_data['graph']
edge_lookup = dfs_data['edge_lookup']
edge = graph.get_edge(edge_id)
u, v = edge['vertices']
d_u = D(u, dfs_data)
d_v = D(v, dfs_data)
lp_1 = L1(v, dfs_data)
d_lp_1 = D(lp_1, dfs_data)
if edge_lookup[edge_id] == 'backedge' and d_v < d_u:
retur... | def __edge_weight(edge_id, dfs_data) | Calculates the edge weight used to sort edges. | 3.10924 | 3.013517 | 1.031764 |
u = dfs_data['ordering'][0]
b = {}
b[u] = D(u, dfs_data)
__calculate_bu_dfs_recursively(u, b, dfs_data)
return b | def __calculate_bu_dfs(dfs_data) | Calculates the b(u) lookup table. | 7.102667 | 5.627492 | 1.262137 |
first_time = True
for v in dfs_data['adj'][u]:
if a(v, dfs_data) == u:
if first_time:
b[v] = b[u]
else:
b[v] = D(u, dfs_data)
__calculate_bu_dfs_recursively(v, b, dfs_data)
first_time = False | def __calculate_bu_dfs_recursively(u, b, dfs_data) | Calculates the b(u) lookup table with a recursive DFS. | 3.453149 | 3.095183 | 1.115653 |
if u != a(v, dfs_data):
return False
if u == L2(v, dfs_data):
return True
return False | def is_type_I_branch(u, v, dfs_data) | Determines whether a branch uv is a type I branch. | 6.414018 | 6.593583 | 0.972767 |
if u != a(v, dfs_data):
return False
if u < L2(v, dfs_data):
return True
return False | def is_type_II_branch(u, v, dfs_data) | Determines whether a branch uv is a type II branch. | 7.128975 | 7.16773 | 0.994593 |
d_u = D(u, dfs_data)
d_v = D(v, dfs_data)
edge_id = dfs_data['graph'].get_first_edge_id_by_node_ids(u, v)
return True if dfs_data['edge_lookup'][edge_id] == 'backedge' and d_v < d_u else False | def is_frond(u, v, dfs_data) | Determines if the edge uv is a frond ("backedge"). | 3.818422 | 3.716769 | 1.02735 |
list_of_descendants = []
stack = deque()
children_lookup = dfs_data['children_lookup']
current_node = node
children = children_lookup[current_node]
dfs_current_node = D(current_node, dfs_data)
for n in children:
dfs_child = D(n, dfs_data)
# Validate that the child nod... | def __get_descendants(node, dfs_data) | Gets the descendants of a node. | 2.125649 | 2.1106 | 1.00713 |
s_u = S(u, dfs_data)
if u not in s_u:
s_u.append(u)
return s_u | def S_star(u, dfs_data) | The set of all descendants of u, with u added. | 3.252633 | 2.624697 | 1.239241 |
return list(set([w for v in S_star(u, dfs_data) for w in A(v, dfs_data)])) | def T(u, dfs_data) | T(u) consists of all vertices adjacent to u or any descendant of u. | 7.198195 | 6.375719 | 1.129001 |
if a(v, dfs_data) != u:
return None
return list(set([edge_id for w in S_star(v, dfs_data) for edge_id in dfs_data['graph'].get_node(w)['edges']])) | def B(u, v, dfs_data) | The branch at u containing v is the set of all edges incident on v or any descendant of v, if a(v) == u. | 7.580983 | 7.09117 | 1.069074 |
#return dfs_data['graph'].get_first_edge_id_by_node_ids(u, v)
uv_edges = dfs_data['graph'].get_edge_ids_by_node_ids(u, v)
buv_edges = B(u, v, dfs_data)
for edge_id in uv_edges:
if edge_id in buv_edges:
return edge_id
return None | def stem(u, v, dfs_data) | The stem of Bu(v) is the edge uv in Bu(v). | 3.264108 | 3.105648 | 1.051023 |
# Determine the edge_id
edge_id = dfs_data['graph'].get_first_edge_id_by_node_ids(u, v)
# Pull the weight of that edge
return dfs_data['edge_weights'][edge_id] | def wt(u, v, dfs_data) | The wt_u[v] function used in the paper. | 4.925615 | 5.095968 | 0.966571 |
node_set = set()
for v, adj in list(dfs_data['adj'].items()):
w = adj[0]
if is_frond(v, w, dfs_data):
node_set.add(v)
return list(node_set) | def _L(dfs_data) | L(T) contains leaves and branch points for the DFS-tree T. | 4.784734 | 5.128006 | 0.933059 |
try:
return R(i, dfs_data)['x']
except Exception as e:
# Page 17 states that if Ri is empty, then we take xi to be n
return dfs_data['graph'].num_nodes() | def fn_x(i, dfs_data) | The minimum vertex (DFS-number) in a frond contained in Ri. | 16.587166 | 14.002178 | 1.184613 |
global single_symbol_classifier
if single_symbol_classifier is None:
single_symbol_classifier = SingleClassificer()
return single_symbol_classifier.predict(recording, result_format) | def classify_segmented_recording(recording, result_format=None) | Use this function if you are sure you have a single symbol.
Parameters
----------
recording : string
The recording in JSON format
Returns
-------
list of dictionaries
Each dictionary contains the keys 'symbol' and 'probability'. The list
is sorted descending by probabil... | 4.44208 | 5.278837 | 0.841488 |
evaluate = utils.evaluate_model_single_recording_preloaded
results = evaluate(self.preprocessing_queue,
self.feature_list,
self.model,
self.output_semantics,
recording)
if result_... | def predict(self, recording, result_format=None) | Predict the class of the given recording.
Parameters
----------
recording : string
Recording of a single handwritten dataset in JSON format.
result_format : string, optional
If it is 'LaTeX', then only the latex code will be returned
Returns
----... | 5.924642 | 5.946949 | 0.996249 |
metadata = get_metadata()
symbol_ids = get_symbol_ids(symbol_yml_file, metadata)
symbol_ids = transform_sids(symbol_ids)
raw = load_raw(raw_pickle_file)
filter_and_save(raw, symbol_ids, pickle_dest_path) | def main(symbol_yml_file, raw_pickle_file, pickle_dest_path) | Parameters
----------
symbol_yml_file : str
Path to a YAML file which contains recordings.
raw_pickle_file : str
Path to a pickle file which contains raw recordings.
pickle_dest_path : str
Path where the filtered dict gets serialized as a pickle file again. | 3.127669 | 3.432613 | 0.911163 |
with open(symbol_yml_file, 'r') as stream:
symbol_cfg = yaml.load(stream)
symbol_ids = []
symbol_ids_set = set()
for symbol in symbol_cfg:
if 'latex' not in symbol:
logging.error("Key 'latex' not found for a symbol in %s (%s)",
symbol_yml_file,... | def get_symbol_ids(symbol_yml_file, metadata) | Get a list of ids which describe which class they get mapped to.
Parameters
----------
symbol_yml_file : string
Path to a YAML file.
metadata : dict
Metainformation of symbols, like the id on write-math.com.
Has keys 'symbols', 'tags', 'tags2symbols'.
Returns
-------
... | 3.177481 | 2.790243 | 1.138783 |
misc_path = pkg_resources.resource_filename('hwrt', 'misc/')
wm_symbols = os.path.join(misc_path, 'wm_symbols.csv')
wm_tags = os.path.join(misc_path, 'wm_tags.csv')
wm_tags2symbols = os.path.join(misc_path, 'wm_tags2symbols.csv')
return {'symbols': read_csv(wm_symbols),
'tags': read... | def get_metadata() | Get metadata of symbols, like their tags, id on write-math.com, LaTeX
command and unicode code point.
Returns
-------
dict | 2.454224 | 2.608402 | 0.940892 |
symbols = []
with open(filepath, 'rb') as csvfile:
spamreader = csv.DictReader(csvfile, delimiter=',', quotechar='"')
for row in spamreader:
symbols.append(row)
return symbols | def read_csv(filepath) | Read a CSV into a list of dictionarys. The first line of the CSV determines
the keys of the dictionary.
Parameters
----------
filepath : string
Returns
-------
list of dictionaries | 2.253006 | 2.595656 | 0.867991 |
with open(raw_pickle_file, 'rb') as f:
raw = pickle.load(f)
logging.info("Loaded %i recordings.", len(raw['handwriting_datasets']))
return raw | def load_raw(raw_pickle_file) | Load a pickle file of raw recordings.
Parameters
----------
raw_pickle_file : str
Path to a pickle file which contains raw recordings.
Returns
-------
dict
The loaded pickle file. | 4.544334 | 4.689635 | 0.969016 |
logging.info('Start filtering...')
new_hw_ds = []
for el in raw['handwriting_datasets']:
if el['formula_id'] in symbol_ids:
el['formula_id'] = symbol_ids[el['formula_id']]
el['handwriting'].formula_id = symbol_ids[el['formula_id']]
new_hw_ds.append(el)
ra... | def filter_and_save(raw, symbol_ids, destination_path) | Parameters
----------
raw : dict
with key 'handwriting_datasets'
symbol_ids : dict
Maps LaTeX to write-math.com id
destination_path : str
Path where the filtered dict 'raw' will be saved | 3.431225 | 2.839796 | 1.208264 |
return utils.get_objectlist(metrics_description,
config_key='data_analyzation_plugins',
module=sys.modules[__name__]) | def get_metrics(metrics_description) | Get metrics from a list of dictionaries. | 14.840513 | 14.32643 | 1.035884 |
directory = os.path.join(utils.get_project_root(), "analyzation/")
if not os.path.exists(directory):
os.makedirs(directory)
workfilename = os.path.join(directory, filename)
open(workfilename, 'w').close() # Truncate the file
return workfilename | def prepare_file(filename) | Truncate the file and return the filename. | 3.744396 | 3.233871 | 1.157868 |
by_formula_id = defaultdict(list)
for el in raw_datasets:
by_formula_id[el['handwriting'].formula_id].append(el['handwriting'])
return by_formula_id | def sort_by_formula_id(raw_datasets) | Sort a list of formulas by `id`, where `id` represents the accepted
formula id.
Parameters
----------
raw_datasets : list of dictionaries
A list of raw datasets.
Examples
--------
The parameter `raw_datasets` has to be of the format
>>> rd = [{'is_in_testset': 0,
... ... | 3.594952 | 3.973071 | 0.90483 |
write_file = open(self.filename, "a")
s = ""
for symbol, count in sorted(symbols.items(), key=lambda n: n[0]):
if symbol in ['a', '0', 'A']:
s += "\n%s (%i), " % (symbol, count)
elif symbol in ['z', '9', 'Z']:
s += "%s (%i) \n" % (... | def _write_data(self, symbols, err_recs, nr_recordings,
total_error_count, percentages, time_max_list) | Write all obtained data to a file.
Parameters
----------
symbols : list of tuples (String, non-negative int)
List of all symbols with the count of recordings
err_recs : dictionary
count of recordings by error type
nr_recordings : non-negative int
... | 2.271535 | 2.187116 | 1.038598 |
return utils.get_objectlist(model_description_features,
config_key='features',
module=sys.modules[__name__]) | def get_features(model_description_features) | Get features from a list of dictionaries
Parameters
----------
model_description_features : list of dictionaries
Examples
--------
>>> l = [{'StrokeCount': None}, \
{'ConstantPointCoordinates': \
[{'strokes': 4}, \
{'points_per_stroke': 81}, \
... | 8.439531 | 12.579437 | 0.670899 |
input_features = sum(map(lambda n: n.get_dimension(), feature_list))
print("## Features (%i)" % input_features)
print("```")
for algorithm in feature_list:
print("* %s" % str(algorithm))
print("```") | def print_featurelist(feature_list) | Print the feature_list in a human-readable form.
Parameters
----------
feature_list : list
feature objects | 5.03539 | 6.09691 | 0.825892 |
if self.strokes > 0:
if self.pixel_env > 0:
return (2 + (1 + 2*self.pixel_env)**2) \
* self.strokes * self.points_per_stroke
else:
return 2*self.strokes * self.points_per_stroke
else:
if self.pen_down:
... | def get_dimension(self) | Get the dimension of the returned feature. This equals the number
of elements in the returned list of numbers. | 3.461942 | 3.410042 | 1.01522 |
x = []
img = Image.new('L', ((int(hwr_obj.get_width()*self.scaling_factor) + 2), (int(hwr_obj.get_height()*self.scaling_factor) + 2)), 'black')
draw = ImageDraw.Draw(img, 'L')
pointlist = hwr_obj.get_pointlist()
bb = hwr_obj.get_bounding_box()
for stroke_nr in ra... | def _features_with_strokes(self, hwr_obj) | Calculate the ConstantPointCoordinates features for the case of
a fixed number of strokes. | 1.984162 | 1.957465 | 1.013639 |
x = []
for point in hwr_obj.get_pointlist()[0]:
if len(x) >= 3*self.points_per_stroke or \
(len(x) >= 2*self.points_per_stroke and not self.pen_down):
break
x.append(point['x'])
x.append(point['y'])
if self.pen_down:... | def _features_without_strokes(self, hwr_obj) | Calculate the ConstantPointCoordinates features for the case of
a single (callapesed) stroke with pen_down features. | 3.71534 | 3.216643 | 1.155036 |
# Find the point with the biggest distance
dmax = 0
index = 0
for i in range(1, len(pointlist)):
d = geometry.perpendicular_distance(pointlist[i],
pointlist[0],
pointlist... | def _stroke_simplification(self, pointlist) | The Douglas-Peucker line simplification takes a list of points as an
argument. It tries to simplifiy this list by removing as many points
as possible while still maintaining the overall shape of the stroke.
It does so by taking the first and the last point, connecting them
by... | 2.801818 | 2.532282 | 1.10644 |
return int(round(float(self.strokes**2)/2 + float(self.strokes)/2)) | def get_dimension(self) | Get the dimension of the returned feature. This equals the number
of elements in the returned list of numbers. | 13.534588 | 14.041197 | 0.96392 |
# Fail when '{' and '}' don't match - be aware of escaped symbols!
opened_braces = 0
last_char = ''
for char in text:
if char == '{' and last_char != '\\':
opened_braces += 1
if char == '}' and last_char != '\\':
opened_braces -= 1
if opened_brac... | def chunk_math(text) | Parameters
----------
text : string
A mathematical context
Returns
-------
list :
A list of single LaTeX entities
Examples
--------
>>> chunk_math('\sum_i^n i^2')
['\\\\sum', '_', 'i', '^', 'n', ' ', 'i', '^', '2']
>>> chunk_math('\sum_{i}^n i^2')
['\\\\sum... | 2.502271 | 2.47528 | 1.010904 |
string = ''
began_context = False
context_depth = 0
context_triggers = ['_', '^']
for chunk in chunks:
if began_context and chunk != '{':
string += '{' + chunk + '}'
began_context = False
elif began_context and chunk == '{':
began_context = Fa... | def chunks_to_string(chunks) | Parameters
----------
chunks : list of strings
A list of single entities in order
Returns
-------
string :
A LaTeX-parsable string
Examples
--------
>>> chunks_to_string(['\\\\sum', '_', 'i', '^', 'n', 'i', '^', '2'])
'\\\\sum_{i}^{n}i^{2}'
>>> chunks_to_string(... | 3.381655 | 3.367649 | 1.004159 |
return utils.get_objectlist(preprocessing_list,
config_key='preprocessing',
module=sys.modules[__name__]) | def get_preprocessing_queue(preprocessing_list) | Get preprocessing queue from a list of dictionaries
>>> l = [{'RemoveDuplicateTime': None},
{'ScaleAndShift': [{'center': True}]}
]
>>> get_preprocessing_queue(l)
[RemoveDuplicateTime, ScaleAndShift
- center: True
- max_width: 1
- max_height: 1
] | 9.716175 | 12.864376 | 0.755278 |
print("## Preprocessing")
print("```")
for algorithm in preprocessing_queue:
print("* " + str(algorithm))
print("```") | def print_preprocessing_list(preprocessing_queue) | Print the ``preproc_list`` in a human-readable form.
Parameters
----------
preprocessing_queue : list of preprocessing objects
Algorithms that get applied for preprocessing. | 5.186262 | 5.333102 | 0.972466 |
a = hwr_obj.get_bounding_box()
width = a['maxx'] - a['minx'] + self.width_add
height = a['maxy'] - a['miny'] + self.height_add
factor_x, factor_y = 1, 1
if width != 0:
factor_x = self.max_width / width
if height != 0:
factor_y = self.ma... | def _get_parameters(self, hwr_obj) | Take a list of points and calculate the factors for scaling and
moving it so that it's in the unit square. Keept the aspect
ratio.
Optionally center the points inside of the unit square. | 2.308834 | 2.255166 | 1.023798 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.