|
| 1 | +from collections.abc import Callable, Iterable, Iterator |
| 2 | +from itertools import chain |
| 3 | +from typing import Any, Literal |
| 4 | + |
| 5 | +import numpy as np |
1 | 6 | import sympy |
2 | 7 |
|
3 | 8 | from devito.symbolics.queries import (q_indexed, q_function, q_terminal, q_leaf, |
|
9 | 14 | 'retrieve_derivatives', 'search'] |
10 | 15 |
|
11 | 16 |
|
12 | | -class Search: |
| 17 | +Expression = sympy.Basic | np.number | int | float |
| 18 | + |
| 19 | + |
| 20 | +class Set(set[Expression]): |
| 21 | + @staticmethod |
| 22 | + def wrap(obj: Expression) -> set[Expression]: |
| 23 | + return {obj} |
13 | 24 |
|
14 | | - class Set(set): |
15 | 25 |
|
16 | | - @staticmethod |
17 | | - def wrap(obj): |
18 | | - return {obj} |
| 26 | +class List(list[Expression]): |
| 27 | + @staticmethod |
| 28 | + def wrap(obj: Expression) -> list[Expression]: |
| 29 | + return [obj] |
19 | 30 |
|
20 | | - class List(list): |
| 31 | + def update(self, obj: Iterable[Expression]) -> None: |
| 32 | + self.extend(obj) |
21 | 33 |
|
22 | | - @staticmethod |
23 | | - def wrap(obj): |
24 | | - return [obj] |
25 | 34 |
|
26 | | - def update(self, obj): |
27 | | - return self.extend(obj) |
| 35 | +Mode = Literal['all', 'unique'] |
| 36 | +modes: dict[Mode, type[List] | type[Set]] = { |
| 37 | + 'all': List, |
| 38 | + 'unique': Set |
| 39 | +} |
28 | 40 |
|
29 | | - modes = { |
30 | | - 'unique': Set, |
31 | | - 'all': List |
32 | | - } |
33 | 41 |
|
34 | | - def __init__(self, query, mode, deep=False): |
| 42 | +class Search: |
| 43 | + def __init__(self, query: Callable[[Expression], bool], deep: bool = False) -> None: |
35 | 44 | """ |
36 | | - Search objects in an expression. This is much quicker than the more |
37 | | - general SymPy's find. |
| 45 | + Search objects in an expression. This is much quicker than the more general |
| 46 | + SymPy's find. |
38 | 47 |
|
39 | 48 | Parameters |
40 | 49 | ---------- |
41 | 50 | query |
42 | 51 | Any query from :mod:`queries`. |
43 | | - mode : str |
44 | | - Either 'unique' or 'all' (catch all instances). |
45 | 52 | deep : bool, optional |
46 | 53 | If True, propagate the search within an Indexed's indices. Defaults to False. |
47 | 54 | """ |
48 | 55 | self.query = query |
49 | | - self.collection = self.modes[mode] |
50 | 56 | self.deep = deep |
51 | 57 |
|
52 | | - def _next(self, expr): |
| 58 | + def _next(self, expr: Expression) -> Iterable[Expression]: |
53 | 59 | if self.deep and expr.is_Indexed: |
54 | 60 | return expr.indices |
55 | 61 | elif q_leaf(expr): |
56 | 62 | return () |
57 | | - else: |
58 | | - return expr.args |
| 63 | + return expr.args |
59 | 64 |
|
60 | | - def dfs(self, expr): |
| 65 | + def visit_postorder(self, expr: Expression) -> Iterator[Expression]: |
61 | 66 | """ |
62 | | - Perform a DFS search. |
63 | | -
|
64 | | - Parameters |
65 | | - ---------- |
66 | | - expr : expr-like |
67 | | - The searched expression. |
| 67 | + Visit the expression with a postorder traversal, yielding all hits. |
68 | 68 | """ |
69 | | - found = self.collection() |
70 | | - for a in self._next(expr): |
71 | | - found.update(self.dfs(a)) |
| 69 | + for i in self._next(expr): |
| 70 | + yield from self.visit_postorder(i) |
72 | 71 | if self.query(expr): |
73 | | - found.update(self.collection.wrap(expr)) |
74 | | - return found |
| 72 | + yield expr |
75 | 73 |
|
76 | | - def bfs(self, expr): |
| 74 | + def visit_preorder(self, expr: Expression) -> Iterator[Expression]: |
77 | 75 | """ |
78 | | - Perform a BFS search. |
79 | | -
|
80 | | - Parameters |
81 | | - ---------- |
82 | | - expr : expr-like |
83 | | - The searched expression. |
| 76 | + Visit the expression with a preorder traversal, yielding all hits. |
84 | 77 | """ |
85 | | - found = self.collection() |
86 | 78 | if self.query(expr): |
87 | | - found.update(self.collection.wrap(expr)) |
88 | | - for a in self._next(expr): |
89 | | - found.update(self.bfs(a)) |
90 | | - return found |
| 79 | + yield expr |
| 80 | + for i in self._next(expr): |
| 81 | + yield from self.visit_preorder(i) |
91 | 82 |
|
92 | | - def bfs_first_hit(self, expr): |
| 83 | + def visit_preorder_first_hit(self, expr: Expression) -> Iterator[Expression]: |
93 | 84 | """ |
94 | | - Perform a BFS search, returning immediately when a node matches the query. |
95 | | -
|
96 | | - Parameters |
97 | | - ---------- |
98 | | - expr : expr-like |
99 | | - The searched expression. |
| 85 | + Visit the expression in preorder and return a tuple containing the first hit, |
| 86 | + if any. This can return more than a single result, as it looks for the first |
| 87 | + hit from any branch but may find a hit in multiple branches. |
100 | 88 | """ |
101 | | - found = self.collection() |
102 | 89 | if self.query(expr): |
103 | | - found.update(self.collection.wrap(expr)) |
104 | | - return found |
105 | | - for a in self._next(expr): |
106 | | - found.update(self.bfs_first_hit(a)) |
107 | | - return found |
| 90 | + yield expr |
| 91 | + return |
| 92 | + for i in self._next(expr): |
| 93 | + yield from self.visit_preorder_first_hit(i) |
108 | 94 |
|
109 | 95 |
|
110 | | -def search(exprs, query, mode='unique', visit='dfs', deep=False): |
| 96 | +def search(exprs: Expression | Iterable[Expression], |
| 97 | + query: type | Callable[[Any], bool], |
| 98 | + mode: Mode = 'unique', |
| 99 | + visit: Literal['dfs', 'bfs', 'bfs_first_hit'] = 'dfs', |
| 100 | + deep: bool = False) -> List | Set: |
111 | 101 | """Interface to Search.""" |
112 | 102 |
|
113 | | - assert mode in Search.modes, "Unknown mode" |
| 103 | + assert mode in ('all', 'unique'), "Unknown mode" |
114 | 104 |
|
115 | 105 | if isinstance(query, type): |
116 | 106 | Q = lambda obj: isinstance(obj, query) |
117 | 107 | else: |
118 | 108 | Q = query |
119 | 109 |
|
120 | | - searcher = Search(Q, mode, deep) |
121 | | - |
122 | | - found = Search.modes[mode]() |
123 | | - for e in as_tuple(exprs): |
124 | | - if not isinstance(e, sympy.Basic): |
125 | | - continue |
126 | | - |
127 | | - if visit == 'dfs': |
128 | | - found.update(searcher.dfs(e)) |
129 | | - elif visit == 'bfs': |
130 | | - found.update(searcher.bfs(e)) |
131 | | - elif visit == "bfs_first_hit": |
132 | | - found.update(searcher.bfs_first_hit(e)) |
133 | | - else: |
134 | | - raise ValueError("Unknown visit type `%s`" % visit) |
| 110 | + # Search doesn't actually use a BFS (rather, a preorder DFS), but the terminology |
| 111 | + # is retained in this function's parameters for backwards compatibility |
| 112 | + searcher = Search(Q, deep) |
| 113 | + if visit == 'dfs': |
| 114 | + _search = searcher.visit_postorder |
| 115 | + elif visit == 'bfs': |
| 116 | + _search = searcher.visit_preorder |
| 117 | + elif visit == 'bfs_first_hit': |
| 118 | + _search = searcher.visit_preorder_first_hit |
| 119 | + else: |
| 120 | + raise ValueError(f"Unknown visit mode '{visit}'") |
| 121 | + |
| 122 | + exprs = filter(lambda e: isinstance(e, sympy.Basic), as_tuple(exprs)) |
| 123 | + found = modes[mode](chain(*map(_search, exprs))) |
135 | 124 |
|
136 | 125 | return found |
137 | 126 |
|
|
0 commit comments