Build an edge predicate that passes for edges for which one of the given nodes is the subject.
968416
def build_downstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate:
    """"""
    nodes = set(nodes)

    def downstream_filter(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool:
        """Pass for relations for which one of the given nodes is the subject."""
        return u in nodes and graph[u][v][k][RELATION] in CAUSAL_RELATIONS

    return downstream_filter
1155185
public boolean isVersionedNode(final Graph graph, final Node subject) {
        return listObjects(graph, subject, RDF.type.asNode()).toList().stream().map(Node::getURI)
            .anyMatch((MEMENTO_TYPE)::equals);
    }
1107209
def canonicalize_edge(edge_data: EdgeData) -> Tuple[str, Optional[Tuple], Optional[Tuple]]:
    """"""
    return (
        edge_data[RELATION],
        _canonicalize_edge_modifications(edge_data.get(SUBJECT)),
        _canonicalize_edge_modifications(edge_data.get(OBJECT)),
    )
300036
def from_edges(edges, source_key='source', target_key='target', weight_key='weight', directed=True):
    
    raw = list(map(lambda x: [x[source_key], x[target_key], int(x[weight_key])], edges))
    g = IGraph.TupleList(raw, weights=True, directed=directed)
    g.vs['indegree'] = g.degree(mode="in")
    g.vs['outdegree'] = g.degree(mode="out")
    g.vs['label'] = g.vs['name']
    if 'group' not in g.vs.attributes():
        g.vs['group'] = labels_to_groups(g.vs['label'])
    return g
489168
def build_node_graph_data_search(key: str, data_predicate: Callable[[Any], bool]):  # noqa: D202
    

    def node_data_filter(graph: BELGraph, node: BaseEntity) -> bool:
        """Pass if the given node has a given data annotated and passes the contained filter."""
        value = graph.nodes[node].get(key)
        return value is not None and data_predicate(value)

    return node_data_filter
883454
def chk_edges_nodes(edges, nodes, name):
        """"""
        edge_nodes = set(e for es in edges for e in es)
        missing_nodes = edge_nodes.difference(nodes)
        assert not missing_nodes, "MISSING: {GOs}\n{NM} EDGES MISSING {N} NODES (OF {T})".format(
            NM=name, N=len(missing_nodes), T=len(edge_nodes), GOs=missing_nodes)
1165094
def getNextNode(nodes,usednodes,parent):
    ''''''
    for e in edges:
        if e.source==parent:
            if e.target in usednodes:
                x = e.target
                break
        elif e.target==parent:
            if e.source in usednoes:
                x = e.source
                break  
    return x
62167
def invert_edge_predicate(edge_predicate: EdgePredicate) -> EdgePredicate:  # noqa: D202
    """"""

    def _inverse_filter(graph, u, v, k):
        return not edge_predicate(graph, u, v, k)

    return _inverse_filter
332213
def _edge_both_nodes(nodes: List[Node]):
        """"""
        node_ids = [node.id for node in nodes]

        return and_(
            Edge.source_id.in_(node_ids),
            Edge.target_id.in_(node_ids),
        )
706626
def wt(u, v, dfs_data):
    """"""
    # 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]
328049
def complete(self, match, subject_graph):
        """"""
        if not CustomPattern.complete(self, match, subject_graph):
            return False
        if self.strong:
            # If the ring is not strong, return False
            if self.size % 2 == 0:
                # even ring
                for i in range(self.size//2):
                    vertex1_start = match.forward[i]
                    vertex1_stop = match.forward[(i+self.size//2)%self.size]
                    paths = list(subject_graph.iter_shortest_paths(vertex1_start, vertex1_stop))
                    if len(paths) != 2:
                        #print "Even ring must have two paths between opposite vertices"
                        return False
                    for path in paths:
                        if len(path) != self.size//2+1:
                            #print "Paths between opposite vertices must half the size of the ring+1"
                            return False
            else:
                # odd ring
                for i in range(self.size//2+1):
                    vertex1_start = match.forward[i]
                    vertex1_stop = match.forward[(i+self.size//2)%self.size]
                    paths = list(subject_graph.iter_shortest_paths(vertex1_start, vertex1_stop))
                    if len(paths) > 1:
                        return False
                    if len(paths[0]) != self.size//2+1:
                        return False
                    vertex1_stop = match.forward[(i+self.size//2+1)%self.size]
                    paths = list(subject_graph.iter_shortest_paths(vertex1_start, vertex1_stop))
                    if len(paths) > 1:
                        return False
                    if len(paths[0]) != self.size//2+1:
                        return False
        return True
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
611139
def skolemize(gin: Graph) -> Graph:
    
    gout = Graph()

    # Emit any unreferenced subject BNodes (boxes)
    anon_subjs = [s for s in gin.subjects() if isinstance(s, BNode) and len([gin.subject_predicates(s)]) == 0]
    if anon_subjs:
        idx = None if len(anon_subjs) == 1 else 0
        for s in anon_subjs:
            map_node(s, FHIR['treeRoot' + ('_{}'.format(idx) if idx is not None else '')], gin, gout)
            if idx is not None:
                idx += 1

    # Cover all other non-bnode entries
    for subj in set(s for s in gin.subjects() if isinstance(s, URIRef)):
        map_node(subj, subj, gin, gout)
    return gout
1261728
def inc_edges(self, node):
        
        try:
            return list(self.nodes[node][0])
        except KeyError:
            raise GraphError('Invalid node %s' % node)

        return None
61979
def chk_edges(self):
        """"""
        goids = set(self.go2obj)
        self.chk_edges_nodes(self.edges, goids, "is_a")
        for reltype, edges in self.edges_rel.items():
            self.chk_edges_nodes(edges, goids, reltype)
221859
def _iter_new_relations(self, init_match, subject_graph, edges0, constraints0, edges1):
        """"""
        # Count the number of unique edges0[i][1] values. This is also
        # the number of new relations.
        num_new_relations = len(set(j for i, j in edges0))

        def combine_small(relations, num):
            """iterate over all compatible combinations within one set of relations"""
            if len(relations) == 0:
                return
            for i, pivot in enumerate(relations):
                if num == 1:
                    yield (pivot, )
                else:
                    compatible_relations = list(
                        item for item in relations[:i]
                        if pivot[0]!=item[0] and pivot[1]!=item[1]
                    )
                    for tail in combine_small(compatible_relations, num-1):
                        yield (pivot, ) + tail

        # generate candidate relations
        candidate_relations = []
        icg = self._iter_candidate_groups(init_match, edges0, edges1)
        for end_vertices0, end_vertices1 in icg:
            if len(end_vertices0) > len(end_vertices1):
                return # this can never work, the subject graph is 'too small'
            elif not self.pattern.sub and \
                 len(end_vertices0) != len(end_vertices1):
                return # an exact match is sought, this can never work
            l = []
            for end_vertex0 in end_vertices0:
                for end_vertex1 in end_vertices1:
                    if self.pattern.compare(end_vertex0, end_vertex1, subject_graph):
                        l.append((end_vertex0, end_vertex1))
            # len(end_vertices0) = the total number of relations that must be
            # made in this group
            if len(l) > 0:
                # turn l into a list of sets of internally compatible candidate
                # relations in this group
                l = list(combine_small(l, len(end_vertices0)))
                candidate_relations.append(l)
        if len(candidate_relations) == 0:
            return
        self.print_debug("candidate_relations: %s" % candidate_relations)

        def combine_big(pos=0):
            """Iterate over all possible sets of relations"""
            # pos is an index in candidate_relations
            crs = candidate_relations[pos]
            if pos == len(candidate_relations)-1:
                for relations in crs:
                    yield relations
            else:
                for tail in combine_big(pos+1):
                    for relations in crs:
                        yield relations + tail

        # final loop
        for new_relations in combine_big():
            new_relations = set(new_relations)
            self.print_debug("new_relations: %s" % (new_relations, ))
            # check the total number of new relations
            if len(new_relations) != num_new_relations:
                continue
            # check sanity of relations
            forward = dict(new_relations)
            if len(forward) != num_new_relations:
                continue
            reverse = dict((j, i) for i, j in new_relations)
            if len(reverse) != num_new_relations:
                continue
            # check the constraints
            for a0, b0 in constraints0:
                if forward[a0] not in subject_graph.neighbors[forward[b0]]:
                    forward = None
                    break
            if forward is None:
                continue
            yield forward
128302
def predicates(G: Graph, n: Node) -> Set[TriplePredicate]:
    
    return predicatesOut(G, n) | predicatesIn(G, n)