def test_basic(self): # This example is from the Wikipedia article "Trie" # <https://en.wikipedia.org/wiki/Trie>. strings = ["a", "to", "tea", "ted", "ten", "i", "in", "inn"] T, root = nx.prefix_tree(strings) def source_label(v): return T.nodes[v]["source"] # First, we check that the tree has the expected # structure. Recall that each node that corresponds to one of # the input strings has an edge to the NIL node. # # Consider the three children at level 1 in the trie. a, i, t = sorted(T[root], key=source_label) # Check the 'a' branch. assert len(T[a]) == 1 nil = arbitrary_element(T[a]) assert len(T[nil]) == 0 # Check the 'i' branch. assert len(T[i]) == 2 nil, in_ = sorted(T[i], key=source_label) assert len(T[nil]) == 0 assert len(T[in_]) == 2 nil, inn = sorted(T[in_], key=source_label) assert len(T[nil]) == 0 assert len(T[inn]) == 1 nil = arbitrary_element(T[inn]) assert len(T[nil]) == 0 # Check the 't' branch. te, to = sorted(T[t], key=source_label) assert len(T[to]) == 1 nil = arbitrary_element(T[to]) assert len(T[nil]) == 0 tea, ted, ten = sorted(T[te], key=source_label) assert len(T[tea]) == 1 assert len(T[ted]) == 1 assert len(T[ten]) == 1 nil = arbitrary_element(T[tea]) assert len(T[nil]) == 0 nil = arbitrary_element(T[ted]) assert len(T[nil]) == 0 nil = arbitrary_element(T[ten]) assert len(T[nil]) == 0 # Next, we check that the "sources" of each of the nodes is the # rightmost letter in the string corresponding to the path to # that node. assert source_label(root) is None assert source_label(a) == "a" assert source_label(i) == "i" assert source_label(t) == "t" assert source_label(in_) == "n" assert source_label(inn) == "n" assert source_label(to) == "o" assert source_label(te) == "e" assert source_label(tea) == "a" assert source_label(ted) == "d" assert source_label(ten) == "n" assert source_label(NIL) == NIL
def test_basic(self): # This example is from the Wikipedia article "Trie" # <https://en.wikipedia.org/wiki/Trie>. strings = ['a', 'to', 'tea', 'ted', 'ten', 'i', 'in', 'inn'] T, root = nx.prefix_tree(strings) def source_label(v): return T.node[v]['source'] # First, we check that the tree has the expected # structure. Recall that each node that corresponds to one of # the input strings has an edge to the NIL node. # # Consider the three children at level 1 in the trie. a, i, t = sorted(T[root], key=source_label) # Check the 'a' branch. assert_equal(len(T[a]), 1) nil = arbitrary_element(T[a]) assert_equal(len(T[nil]), 0) # Check the 'i' branch. assert_equal(len(T[i]), 2) nil, in_ = sorted(T[i], key=source_label) assert_equal(len(T[nil]), 0) assert_equal(len(T[in_]), 2) nil, inn = sorted(T[in_], key=source_label) assert_equal(len(T[nil]), 0) assert_equal(len(T[inn]), 1) nil = arbitrary_element(T[inn]) assert_equal(len(T[nil]), 0) # Check the 't' branch. te, to = sorted(T[t], key=source_label) assert_equal(len(T[to]), 1) nil = arbitrary_element(T[to]) assert_equal(len(T[nil]), 0) tea, ted, ten = sorted(T[te], key=source_label) assert_equal(len(T[tea]), 1) assert_equal(len(T[ted]), 1) assert_equal(len(T[ten]), 1) nil = arbitrary_element(T[tea]) assert_equal(len(T[nil]), 0) nil = arbitrary_element(T[ted]) assert_equal(len(T[nil]), 0) nil = arbitrary_element(T[ten]) assert_equal(len(T[nil]), 0) # Next, we check that the "sources" of each of the nodes is the # rightmost letter in the string corresponding to the path to # that node. assert_equal(source_label(root), None) assert_equal(source_label(a), 'a') assert_equal(source_label(i), 'i') assert_equal(source_label(t), 't') assert_equal(source_label(in_), 'n') assert_equal(source_label(inn), 'n') assert_equal(source_label(to), 'o') assert_equal(source_label(te), 'e') assert_equal(source_label(tea), 'a') assert_equal(source_label(ted), 'd') assert_equal(source_label(ten), 'n') assert_equal(source_label(NIL), NIL)
def get_as_tree(self): """ :return: prefix tree / trie composed of the identifiers of the boundary cells """ cell_ids = [cell.value for cell in self.cells] sorted_cell_ids = sorted(cell_ids) t, r = nx.prefix_tree( sorted_cell_ids ) # A Prefix_Tree is essentially another name for a trie return t
def prefix_tree(dyn, trcs) -> PrefixTree: """Encodes i/o traces as sequences of (sys, env) actions.""" trcs = [list(fn.interleave(*trc)) for trc in trcs] trcs = [fn.lmap(pmap, trc) for trc in trcs] tree, root = nx.prefix_tree(trcs) # This tree has a dummy sink tree.remove_node(nx.generators.trees.NIL) # which we don't want. tree.nodes[root]['source'] = pmap(dyn.aigbv.latch2init) annotate(tree, root, dyn, trcs) return PrefixTree(tree, root, dyn)
def from_examples(accepting: list[Word], rejecting: list[Word], alphabet: frozenset = None) -> APTA: """Return Augmented Prefix Tree Automata for accepting, rejecting.""" # Create prefix tree. tree, root = nx.prefix_tree(chain(accepting, rejecting)), 0 tree.remove_node(-1) # <-- sink node added by nx. def access(word: Word) -> Node: node = root for char in word: # Walk tree for node accessed by word. node = transition(tree, node, char) return node # Augment tree with node labels. for label, words in [(True, accepting), (False, rejecting)]: for word in words: tree.nodes[access(word)]['label'] = label # Label nodes with integers. With root = 0. relabels = {n: i + 1 for i, n in enumerate(set(tree.nodes) - {root})} relabels[root] = 0 nx.relabel_nodes(tree, relabels, copy=False) # Construct alphabet for DFA. alphabet2 = {d['source'] for n, d in tree.nodes(data=True) if n != 0} if (alphabet is not None): if alphabet2 - alphabet: raise ValueError("Symbols in examples not in alphabet") alphabet |= alphabet2 else: alphabet = alphabet2 if None in alphabet: raise ValueError("None not allowed in alphabet.") # If possible, respect the alphabet's predefined ordering. try: alphabet = sorted(alphabet) except Exception: pass alphabet = bidict(enumerate(alphabet)).inv return APTA(tree, alphabet)
def cuids_to_bp_auid(cuids, pars="{}", root_name="R", nil_name="$", with_opening_par=False): """ Takes a list of cell unique identifiers (cuids) and returns a tuple with: - A string representation of that list of cuids that can be used as an area unique identifier (AUID), based on a trie created from the sorted(cuids) and expressed as a balanced parenthesis string with or without the opening parenthesis - A blake2b hash of that string. - A compressed version of that string (as a bytes object) - The trie (networkx object) - The root of the trie (networkx object) """ # Sorting the ids is necessary to prevent that for instance ['N21', 'N22'] and ['N22', 'N21'] give # different results sorted_cuids = sorted(cuids) t, r = nx.prefix_tree( sorted_cuids) # A Prefix_Tree is essentially another name for a trie auid = generate_BP(t, r, pars, root_name, nil_name, with_opening_par) hashed = hash_id(auid) auid_compressed = compress_id(auid) return (auid, hashed, auid_compressed, t, r)
def dag_to_branching(G): """Returns a branching representing all (overlapping) paths from root nodes to leaf nodes in the given directed acyclic graph. As described in :mod:`networkx.algorithms.tree.recognition`, a *branching* is a directed forest in which each node has at most one parent. In other words, a branching is a disjoint union of *arborescences*. For this function, each node of in-degree zero in `G` becomes a root of one of the arborescences, and there will be one leaf node for each distinct path from that root to a leaf node in `G`. Each node `v` in `G` with *k* parents becomes *k* distinct nodes in the returned branching, one for each parent, and the sub-DAG rooted at `v` is duplicated for each copy. The algorithm then recurses on the children of each copy of `v`. Parameters ---------- G : NetworkX graph A directed acyclic graph. Returns ------- DiGraph The branching in which there is a bijection between root-to-leaf paths in `G` (in which multiple paths may share the same leaf) and root-to-leaf paths in the branching (in which there is a unique path from a root to a leaf). Each node has an attribute 'source' whose value is the original node to which this node corresponds. No other graph, node, or edge attributes are copied into this new graph. Raises ------ NetworkXNotImplemented If `G` is not directed, or if `G` is a multigraph. HasACycle If `G` is not acyclic. Examples -------- To examine which nodes in the returned branching were produced by which original node in the directed acyclic graph, we can collect the mapping from source node to new nodes into a dictionary. For example, consider the directed diamond graph:: >>> from collections import defaultdict >>> from operator import itemgetter >>> >>> G = nx.DiGraph(nx.utils.pairwise("abd")) >>> G.add_edges_from(nx.utils.pairwise("acd")) >>> B = nx.dag_to_branching(G) >>> >>> sources = defaultdict(set) >>> for v, source in B.nodes(data="source"): ... sources[source].add(v) >>> len(sources["a"]) 1 >>> len(sources["d"]) 2 To copy node attributes from the original graph to the new graph, you can use a dictionary like the one constructed in the above example:: >>> for source, nodes in sources.items(): ... for v in nodes: ... B.nodes[v].update(G.nodes[source]) Notes ----- This function is not idempotent in the sense that the node labels in the returned branching may be uniquely generated each time the function is invoked. In fact, the node labels may not be integers; in order to relabel the nodes to be more readable, you can use the :func:`networkx.convert_node_labels_to_integers` function. The current implementation of this function uses :func:`networkx.prefix_tree`, so it is subject to the limitations of that function. """ if has_cycle(G): msg = "dag_to_branching is only defined for acyclic graphs" raise nx.HasACycle(msg) paths = root_to_leaf_paths(G) B = nx.prefix_tree(paths) # Remove the synthetic `root`(0) and `NIL`(-1) nodes from the tree B.remove_node(0) B.remove_node(-1) return B
def test_implementations_consistent(strings): """Ensure results are consistent between prefix_tree implementations.""" assert graphs_equal(nx.prefix_tree(strings), nx.prefix_tree_recursive(strings))
def dag_to_branching(G): """Returns a branching representing all (overlapping) paths from root nodes to leaf nodes in the given directed acyclic graph. As described in :mod:`networkx.algorithms.tree.recognition`, a *branching* is a directed forest in which each node has at most one parent. In other words, a branching is a disjoint union of *arborescences*. For this function, each node of in-degree zero in `G` becomes a root of one of the arborescences, and there will be one leaf node for each distinct path from that root to a leaf node in `G`. Each node `v` in `G` with *k* parents becomes *k* distinct nodes in the returned branching, one for each parent, and the sub-DAG rooted at `v` is duplicated for each copy. The algorithm then recurses on the children of each copy of `v`. Parameters ---------- G : NetworkX graph A directed acyclic graph. Returns ------- DiGraph The branching in which there is a bijection between root-to-leaf paths in `G` (in which multiple paths may share the same leaf) and root-to-leaf paths in the branching (in which there is a unique path from a root to a leaf). Each node has an attribute 'source' whose value is the original node to which this node corresponds. No other graph, node, or edge attributes are copied into this new graph. Raises ------ NetworkXNotImplemented If `G` is not directed, or if `G` is a multigraph. HasACycle If `G` is not acyclic. Examples -------- To examine which nodes in the returned branching were produced by which original node in the directed acyclic graph, we can collect the mapping from source node to new nodes into a dictionary. For example, consider the directed diamond graph:: >>> from collections import defaultdict >>> from operator import itemgetter >>> >>> G = nx.DiGraph(nx.utils.pairwise('abd')) >>> G.add_edges_from(nx.utils.pairwise('acd')) >>> B = nx.dag_to_branching(G) >>> >>> sources = defaultdict(set) >>> for v, source in B.nodes(data='source'): ... sources[source].add(v) >>> len(sources['a']) 1 >>> len(sources['d']) 2 To copy node attributes from the original graph to the new graph, you can use a dictionary like the one constructed in the above example:: >>> for source, nodes in sources.items(): ... for v in nodes: ... B.node[v].update(G.node[source]) Notes ----- This function is not idempotent in the sense that the node labels in the returned branching may be uniquely generated each time the function is invoked. In fact, the node labels may not be integers; in order to relabel the nodes to be more readable, you can use the :func:`networkx.convert_node_labels_to_integers` function. The current implementation of this function uses :func:`networkx.prefix_tree`, so it is subject to the limitations of that function. """ if has_cycle(G): msg = 'dag_to_branching is only defined for acyclic graphs' raise nx.HasACycle(msg) paths = root_to_leaf_paths(G) B, root = nx.prefix_tree(paths) # Remove the synthetic `root` and `NIL` nodes in the prefix tree. B.remove_node(root) B.remove_node(NIL) return B