From list of edges, record per node, incoming and outgoing edges
506877
def node_to_edge(edges, directed=True):
    
    outgoing = defaultdict(set)
    incoming = defaultdict(set) if directed else outgoing
    nodes = set()
    for i, edge in enumerate(edges):
        a, b, = edge[:2]
        outgoing[a].add(i)
        incoming[b].add(i)
        nodes.add(a)
        nodes.add(b)
    nodes = sorted(nodes)
    if directed:
        return outgoing, incoming, nodes
    return outgoing, nodes
943088
def from_perseus(network_table, networks):
    
    graphs = []
    for guid, graph_attr in zip(network_table['GUID'], network_table.values):
        network = networks[guid]
        edge_table = network['edge_table']
        if edge_table[['Source', 'Target']].duplicated().any():
            warnings.warn('Duplicate edges were found and ignored in network {}'.format(network['name']))
        G = nx.from_pandas_edgelist(edge_table, 'Source', 'Target', True, create_using=nx.DiGraph())
        for attr, value in zip(network_table.columns, graph_attr):
            G.graph[attr] = value
        node_table = network['node_table']
        if node_table['Node'].duplicated().any():
            warnings.warn('Duplicate nodes were found and ignored in network {}'.format(network['name']))
        node_column = node_table['Node']
        for name, attributes in zip(node_column, node_table.values):
            if name not in G:
                G.add_node(name)
            for attr, value in zip(node_table.columns, attributes):
                G.node[name][attr] = value
        graphs.append(G)
    return graphs
1334976
def outputs_of(self, idx, create=False):
        
        if create and not idx in self.edges:
            self.edges[idx] = set()
        return self.edges[idx]
147725
def root_and_children_to_graph(self,root):
     """"""
     g = Graph()
     g.add_node(root)
     edges = []
     edges += self.get_node_edges(root,"outgoing")
     for c in self.get_children(root):
           g.add_node(c)
           edges += self.get_node_edges(c,"outgoing")
     for e in edges: g.add_edge(e)
     return g
554768
def edge_by_node(self, head, tail):
        
        for edge in self.out_edges(head):
            if self.tail(edge) == tail:
                return edge
        return None
637272
@SuppressWarnings("unchecked")
	public Iterable<OutgoingEdge<VertexKey, EdgeValue>> getOutgoingEdges() {
		if (edgesUsed) {
			throw new IllegalStateException("Can use either 'getOutgoingEdges()' or 'sendMessageToAllTargets()' exactly once.");
		}
		edgesUsed = true;
		
		if (this.edgeWithValueIter != null) {
			this.edgeWithValueIter.set((Iterator<Tuple3<VertexKey, VertexKey, EdgeValue>>) edges);
			return this.edgeWithValueIter;
		} else {
			this.edgeNoValueIter.set((Iterator<Tuple2<VertexKey, VertexKey>>) edges);
			return this.edgeNoValueIter;
		}
	}
174163
def parse(self, data):
        
        # initialize graph and list of aggregated nodes
        graph = self._init_graph()
        server = self._server_common_name
        # add server (central node) to graph
        graph.add_node(server)
        # data may be empty
        if data is None:
            clients = []
            links = []
        else:
            clients = data.client_list.values()
            links = data.routing_table.values()
        # add clients in graph as nodes
        for client in clients:
            if client.common_name == 'UNDEF':
                continue
            client_properties = {
                'label': client.common_name,
                'real_address': str(client.real_address.host),
                'port': int(client.real_address.port),
                'connected_since': client.connected_since.strftime('%Y-%m-%dT%H:%M:%SZ'),
                'bytes_received': int(client.bytes_received),
                'bytes_sent': int(client.bytes_sent)
            }
            local_addresses = [
                str(route.virtual_address)
                for route in data.routing_table.values()
                if route.real_address == client.real_address
            ]
            if local_addresses:
                client_properties['local_addresses'] = local_addresses
            graph.add_node(str(client.real_address.host), **client_properties)
        # add links in routing table to graph
        for link in links:
            if link.common_name == 'UNDEF':
                continue
            graph.add_edge(server, str(link.real_address.host), weight=1)
        return graph
777730
def transfer_causal_edges(graph, source: BaseEntity, target: BaseEntity) -> Iterable[str]:
    """"""
    for _, v, data in graph.out_edges(source, data=True):
        if data[RELATION] not in CAUSAL_RELATIONS:
            continue

        yield graph.add_qualified_edge(
            target,
            v,
            relation=data[RELATION],
            evidence=data[EVIDENCE],
            citation=data[CITATION],
            annotations=data.get(ANNOTATIONS),
            subject_modifier=data.get(SUBJECT),
            object_modifier=data.get(OBJECT),
        )

    for u, _, data in graph.in_edges(source, data=True):
        if data[RELATION] not in CAUSAL_RELATIONS:
            continue

        yield graph.add_qualified_edge(
            u,
            target,
            relation=data[RELATION],
            evidence=data[EVIDENCE],
            citation=data[CITATION],
            annotations=data.get(ANNOTATIONS),
            subject_modifier=data.get(SUBJECT),
            object_modifier=data.get(OBJECT),
        )
1183532
def _iterbfs(self, start, end=None, forward=True):
        
        queue, visited = deque([(start, 0)]), set([start])

        # the direction of the bfs depends on the edges that are sampled
        if forward:
            get_edges = self.out_edges
            get_next = self.tail
        else:
            get_edges = self.inc_edges
            get_next = self.head

        while queue:
            curr_node, curr_step = queue.popleft()
            yield (curr_node, curr_step)
            if curr_node == end:
                break
            for edge in get_edges(curr_node):
                tail = get_next(edge)
                if tail not in visited:
                    visited.add(tail)
                    queue.append((tail, curr_step + 1))
958250
def _group_edges(self):
        
        # edit edges on parent nodes and make new edges for them
        edges_to_add = [[], []]  # [group_edges, uuid_lists]
        for e in self._edges:
            new_edge = deepcopy(e)
            new_edge['data'].pop('id', None)
            uuid_list = new_edge['data'].pop('uuid_list', [])
            # Check if edge source or target are contained in a parent
            # If source or target in parent edit edge
            # Nodes may only point within their container
            source = e['data']['source']
            target = e['data']['target']
            source_node = [x for x in self._nodes if
                           x['data']['id'] == source][0]
            target_node = [x for x in self._nodes if
                           x['data']['id'] == target][0]
            # If the source node is in a group, we change the source of this
            # edge to the group
            if source_node['data']['parent'] != '':
                new_edge['data']['source'] = source_node['data']['parent']
                e['data']['i'] = 'Virtual'
            # If the targete node is in a group, we change the target of this
            # edge to the group
            if target_node['data']['parent'] != '':
                new_edge['data']['target'] = target_node['data']['parent']
                e['data']['i'] = 'Virtual'
            if e['data']['i'] == 'Virtual':
                if new_edge not in edges_to_add[0]:
                    edges_to_add[0].append(new_edge)
                    edges_to_add[1].append(uuid_list)
                else:
                    idx = edges_to_add[0].index(new_edge)
                    edges_to_add[1][idx] += uuid_list
                    edges_to_add[1][idx] = list(set(edges_to_add[1][idx]))
        for ze in zip(*edges_to_add):
            edge = ze[0]
            edge['data']['id'] = self._get_new_id()
            edge['data']['uuid_list'] = ze[1]
            self._edges.append(edge)
662579
def prevnode(edges, component):
    """"""
    e = edges
    c = component
    n2c = [(a, b) for a, b in e if type(a) == tuple]
    c2n = [(a, b) for a, b in e if type(b) == tuple]
    node2cs = [(a, b) for a, b in e if b == c]
    c2nodes = []
    for node2c in node2cs:
        c2node = [(a, b) for a, b in c2n if b == node2c[0]]
        if len(c2node) == 0:
            # return []
            c2nodes = []
            break
        c2nodes.append(c2node[0])
    cs = [a for a, b in c2nodes]
    # test for connections that have no nodes
    # filter for no nodes
    nonodes = [(a, b) for a, b in e if type(a) != tuple and type(b) != tuple]
    for a, b in nonodes:
        if b == component:
            cs.append(a)
    return cs
585453
def neighbors(self, node_id):
        """"""
        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 node_set:
            node_set.remove(node_id)
        return [nid for nid in node_set]
342024
void build(int nodeOffset, GraphMeshData graphData, List<int[]> connections) {
		for (int n = 0; n < connections.size(); n++) {
			int[] nodeConnections = connections.get(n);
			MeshData tile = graphData.getTile(n);
			Poly node = graphData.getNode(n);
			for (int connection : nodeConnections) {
				MeshData neighbourTile = graphData.getTile(connection - nodeOffset);
				if (neighbourTile != tile) {
					buildExternalLink(tile, node, neighbourTile);
				} else {
					Poly neighbour = graphData.getNode(connection - nodeOffset);
					buildInternalLink(tile, node, neighbourTile, neighbour);
				}
			}
		}
	}
1261728
def inc_edges(self, node):
        
        try:
            return list(self.nodes[node][0])
        except KeyError:
            raise GraphError('Invalid node %s' % node)

        return None
683126
def filterGraph(graph, node_fnc):
		
		nodes = filter(lambda l: node_fnc(l), graph.nodes())
		edges = {}

		gedges = graph.edges()
		for u in gedges:
			if u not in nodes:
				continue
			for v in gedges[u]:
				if v not in nodes:
					continue
				try:
					edges[u].append(v)
				except KeyError:
					edges[u] = [v]

		return Graph(nodes, edges)
954056
def build_edges(self):
        
        self.edges = [
            edge if isinstance(edge, Edge) else Edge(*edge)
            for node in self.nodes.values()
            for edge in getattr(node, "edges", [])
            if edge[0] in self.nodes and edge[1] in self.nodes
        ]
        return self
770849
def _generate_edges(self, edge_prob):
        
        self.E, self.parent = [], {}
        for i in range(self.m):
            if random() < edge_prob and i > 0:
                p_i = choice(i)
                self.E.append((p_i, i))
                self.parent[i] = p_i