-
-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathgraph.py
More file actions
62 lines (51 loc) · 1.93 KB
/
graph.py
File metadata and controls
62 lines (51 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from collections import deque
from typing import TYPE_CHECKING
from typing import Iterable
from typing import MutableSet
if TYPE_CHECKING:
from .state import State
def visit_connected_states(state: "State"):
visit = deque["State"]()
already_visited = set()
visit.append(state)
while visit:
state = visit.popleft()
if state in already_visited:
continue
already_visited.add(state)
yield state
visit.extend(t.target for t in state.transitions if t.target)
# Traverse the state hierarchy: entering a compound/parallel state
# implicitly enters its initial children (all children for parallel).
for child in state.states:
if child.initial:
visit.append(child)
for child in state.history:
visit.append(child)
# Being in a child state implies being in all ancestor states.
if state.parent:
visit.append(state.parent)
def disconnected_states(starting_state: "State", all_states: MutableSet["State"]):
visitable_states = set(visit_connected_states(starting_state))
return all_states - visitable_states
def iterate_states_and_transitions(states: Iterable["State"]):
for state in states:
yield state
yield from state.transitions
if state.states:
yield from iterate_states_and_transitions(state.states)
if state.history:
yield from iterate_states_and_transitions(state.history)
def iterate_states(states: Iterable["State"]):
for state in states:
yield state
if state.states:
yield from iterate_states(state.states)
if state.history:
yield from iterate_states(state.history)
def states_without_path_to_final_states(states: Iterable["State"]):
return (
state
for state in states
if not state.final and not any(s.final for s in visit_connected_states(state))
)