-
Notifications
You must be signed in to change notification settings - Fork 61
/
dfa.py
2468 lines (2135 loc) · 85.1 KB
/
dfa.py
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Classes and methods for working with deterministic finite automata."""
from __future__ import annotations
import array
from collections import defaultdict, deque
from itertools import chain, count
from random import Random
from typing import (
AbstractSet,
Any,
Callable,
DefaultDict,
Deque,
Dict,
FrozenSet,
Generator,
Iterator,
List,
Mapping,
Optional,
Set,
Tuple,
Type,
cast,
)
import networkx as nx
from cached_method import cached_method
from typing_extensions import Self, TypeAlias
import automata.base.exceptions as exceptions
import automata.fa.fa as fa
import automata.fa.nfa as nfa
from automata.base.utils import (
PartitionRefinement,
get_reachable_nodes,
get_renaming_function,
pairwise,
)
DFAStateT = fa.FAStateT
DFASymbolT = str
DFAPathT = Mapping[DFASymbolT, DFAStateT]
DFATransitionsT = Mapping[DFAStateT, DFAPathT]
ExpandStateReturnType = Iterator[Tuple[DFASymbolT, DFAStateT]]
ExpandStateFn = Callable[[DFAStateT], ExpandStateReturnType]
IsFinalStateFn = Callable[[DFAStateT], bool]
TargetStateFn = Callable[[DFAStateT], bool]
class DFA(fa.FA):
"""
The `DFA` class is a subclass of `FA` and represents a deterministic finite
automaton.
Every DFA can be rendered natively inside of a Jupyter notebook
(automatically calling `show_diagram` without any arguments) if installed
with the `visual` optional dependency.
Parameters
----------
states : AbstractSet[DFAStateT]
Set of the DFA's valid states.
input_symbols : AbstractSet[str]
Set of the DFA's valid input symbols, each of which is a singleton
string
transitions : Mapping[DFAStateT, Mapping[str, DFAStateT]]
Dict consisting of the transitions for each state. Each key is a
state name, and each value is another dict which maps a symbol
(the key) to a state (the value).
initial_state : DFAStateT
The initial state for this DFA.
final_states : AbstractSet[DFAStateT]
A set of final states for this DFA
allow_partial : bool, default: True
By default, each DFA state must have a transition to
every input symbol; if this parameter is `True`, you can disable this
characteristic (such that any DFA state can have fewer transitions than input
symbols). Note that a DFA must always have every state represented in the
transition dictionary, even if there are no transitions on input symbols
leaving a state (dictionary is left empty in that case).
"""
__slots__ = (
"states",
"input_symbols",
"transitions",
"initial_state",
"final_states",
"allow_partial",
"_count_cache",
"_word_cache",
# These two entries are to allow for caching methods
"__dict__",
"__weakref__",
)
allow_partial: bool
_word_cache: List[DefaultDict[DFAStateT, List[str]]]
_count_cache: List[DefaultDict[DFAStateT, int]]
def __init__(
self,
*,
states: AbstractSet[DFAStateT],
input_symbols: AbstractSet[str],
transitions: DFATransitionsT,
initial_state: DFAStateT,
final_states: AbstractSet[DFAStateT],
allow_partial: bool = False,
) -> None:
"""Initialize a complete DFA."""
super().__init__(
states=states,
input_symbols=input_symbols,
transitions=transitions,
initial_state=initial_state,
final_states=final_states,
allow_partial=allow_partial,
)
self.clear_cache()
def clear_cache(self) -> None:
"""
Resets the word and count caches.
Can be called if too much memory is being used.
"""
object.__setattr__(self, "_word_cache", [])
object.__setattr__(self, "_count_cache", [])
def __eq__(self, other: Any) -> bool:
"""
Return True if two DFAs are equivalent. Uses an optimized version of
the Hopcroft-Karp algorithm. See https://arxiv.org/abs/0907.5058
"""
DFAStatePairT = Tuple[DFAStateT, int]
# Must be another DFA and have equal alphabets
if not isinstance(other, DFA) or self.input_symbols != other.input_symbols:
return NotImplemented
operand_dfas = (self, other)
initial_state_a = (self.initial_state, 0)
initial_state_b = (other.initial_state, 1)
def is_final_state(state_pair: DFAStatePairT) -> bool:
state, operand_index = state_pair
return state in operand_dfas[operand_index].final_states
def transition(state_pair: DFAStatePairT, symbol: str) -> DFAStatePairT:
state, operand_index = state_pair
return (
operand_dfas[operand_index]._get_next_current_state(state, symbol),
operand_index,
)
# Get data structures
state_sets = nx.utils.union_find.UnionFind((initial_state_a, initial_state_b))
pair_stack: Deque[Tuple[DFAStatePairT, DFAStatePairT]] = deque()
# Do union find
state_sets.union(initial_state_a, initial_state_b)
pair_stack.append((initial_state_a, initial_state_b))
while pair_stack:
q_a, q_b = pair_stack.pop()
if is_final_state(q_a) ^ is_final_state(q_b):
return False
for symbol in self.input_symbols:
r_1 = state_sets[transition(q_a, symbol)]
r_2 = state_sets[transition(q_b, symbol)]
if r_1 != r_2:
state_sets.union(r_1, r_2)
pair_stack.append((r_1, r_2))
return True
def __le__(self, other: DFA) -> bool:
"""Return True if this DFA is a subset of (or equal to) another DFA."""
if isinstance(other, DFA):
return self.issubset(other)
else:
return NotImplemented
def __ge__(self, other: DFA) -> bool:
"""Return True if this DFA is a superset of another DFA."""
if isinstance(other, DFA):
return self.issuperset(other)
else:
return NotImplemented
def __lt__(self, other: DFA) -> bool:
"""Return True if this DFA is a strict subset of another DFA."""
if isinstance(other, DFA):
return self <= other and self != other
else:
return NotImplemented
def __gt__(self, other: DFA) -> bool:
"""Return True if this DFA is a strict superset of another DFA."""
if isinstance(other, DFA):
return self >= other and self != other
else:
return NotImplemented
def __sub__(self, other: DFA) -> Self:
"""Return a DFA that is the difference of this DFA and another DFA."""
if isinstance(other, DFA):
return self.difference(other)
else:
return NotImplemented
def __or__(self, other: DFA) -> Self:
"""Return the union of this DFA and another DFA."""
if isinstance(other, DFA):
return self.union(other)
else:
return NotImplemented
def __and__(self, other: DFA) -> Self:
"""Return the intersection of this DFA and another DFA."""
if isinstance(other, DFA):
return self.intersection(other)
else:
return NotImplemented
def __xor__(self, other: DFA) -> Self:
"""Return the symmetric difference of this DFA and another DFA."""
if isinstance(other, DFA):
return self.symmetric_difference(other)
else:
return NotImplemented
def __invert__(self) -> Self:
"""Return the complement of this DFA and another DFA."""
return self.complement()
def __iter__(self) -> Iterator[str]:
"""
Iterates through all words in the language represented by the DFA. The
words are ordered first by length and then by the order of the input
symbol set.
"""
i = self.minimum_word_length()
limit = self.maximum_word_length()
while limit is None or i <= limit:
yield from self.words_of_length(i)
i += 1
def __len__(self) -> int:
"""Returns the cardinality of the language represented by the DFA."""
return self.cardinality()
def to_partial(self, *, retain_names: bool = False, minify: bool = True) -> Self:
"""
Turns a DFA (complete or not) into a partial DFA.
Removes dead states and trap states (except the initial state)
and all edges leading to them.
Parameters
----------
minify : bool, default: True
Whether to perform a minify operation while converting to
a partial DFA.
retain_names : bool, default: True
Whether to retain state names during minification.
Returns
-------
Self
An equivalent partial DFA.
"""
if self.allow_partial:
return self.copy()
graph = self._get_digraph()
live_states = get_reachable_nodes(graph, [self.initial_state])
non_trap_states = get_reachable_nodes(graph, self.final_states, reversed=True)
new_states = live_states & non_trap_states
new_states.add(self.initial_state)
if minify:
# No need to alter transitions here, since unused entries in
# that dict are removed automatically by the minify call
return self.__class__._minify(
reachable_states=new_states,
input_symbols=self.input_symbols,
transitions=self.transitions,
initial_state=self.initial_state,
reachable_final_states=self.final_states & new_states,
retain_names=retain_names,
)
return self.__class__(
states=new_states,
input_symbols=self.input_symbols,
transitions={
src_state: {
symbol: tgt_state
for symbol, tgt_state in lookup.items()
if tgt_state in non_trap_states
}
for src_state, lookup in self.transitions.items()
if src_state in new_states
},
initial_state=self.initial_state,
final_states=self.final_states & new_states,
allow_partial=True,
)
def _get_trap_state_id(self) -> DFAStateT:
return next(x for x in count(-1, -1) if x not in self.states)
def to_complete(self, trap_state: Optional[DFAStateT] = None) -> Self:
"""
Creates an equivalent complete DFA with trap_state used as the name
for an added trap state. If trap_state is not passed in, defaults to
the largest negative integer which is not already a state name.
If the DFA is already complete, just returns a copy.
Parameters
----------
trap_state : Optional[DFAStateT], default: None
Name for custom trap state to be used.
Returns
-------
Self
An equivalent complete DFA.
"""
if not self.allow_partial:
return self.copy()
if trap_state is None:
trap_state = self._get_trap_state_id()
elif trap_state in self.states:
raise exceptions.InvalidStateError(
f"state {trap_state} is already in the state set and "
"cannot be used as a label for the trap state."
)
return self._to_complete(
input_symbols=self.input_symbols,
transitions=self.transitions,
initial_state=self.initial_state,
final_states=self.final_states,
trap_state=trap_state,
)
@classmethod
def _to_complete(
cls: Type[Self],
*,
input_symbols: AbstractSet[str],
transitions: DFATransitionsT,
initial_state: DFAStateT,
final_states: AbstractSet[DFAStateT],
trap_state: DFAStateT,
) -> Self:
"""
Internal helper function taking in a description of a partial DFA and
returning a corresponding complete DFA.
Note: This will not work with the description of a complete DFA,
so be sure the input describes a partial one.
"""
default_to_trap = {symbol: trap_state for symbol in input_symbols}
transitions = {
state: {**default_to_trap, **lookup}
for state, lookup in transitions.items()
}
transitions[trap_state] = default_to_trap
return cls(
states=frozenset(transitions.keys()),
input_symbols=input_symbols,
transitions=transitions,
initial_state=initial_state,
final_states=final_states,
allow_partial=False,
)
def _validate_transition_missing_symbols(
self, start_state: DFAStateT, paths: DFAPathT
) -> None:
"""Raise an error if the transition input_symbols are missing."""
if self.allow_partial:
return
for input_symbol in self.input_symbols:
if input_symbol not in paths:
raise exceptions.MissingSymbolError(
f"state {start_state} is missing transitions "
f'for symbol "{input_symbol}"'
)
def _validate_transition_invalid_symbols(
self, start_state: DFAStateT, paths: DFAPathT
) -> None:
"""Raise an error if transition input symbols are invalid."""
for input_symbol in paths.keys():
if input_symbol not in self.input_symbols:
raise exceptions.InvalidSymbolError(
f"state {start_state} has invalid transition symbol"
f' "{input_symbol}"'
)
def _validate_transition_start_states(self) -> None:
"""Raise an error if transition start states are missing."""
for state in self.states:
if state not in self.transitions:
raise exceptions.MissingStateError(
f"transition start state {state} is missing"
)
def _validate_transition_end_states(
self, start_state: DFAStateT, paths: DFAPathT
) -> None:
"""Raise an error if transition end states are invalid."""
for end_state in paths.values():
if end_state not in self.states:
raise exceptions.InvalidStateError(
f"end state {end_state} for transition on "
f"{start_state} is not valid"
)
def _validate_transitions(self, start_state: DFAStateT, paths: DFAPathT) -> None:
"""Raise an error if transitions are missing or invalid."""
self._validate_transition_missing_symbols(start_state, paths)
self._validate_transition_invalid_symbols(start_state, paths)
self._validate_transition_end_states(start_state, paths)
def validate(self) -> None:
"""
Raises an exception if this automaton is not internally consistent.
Raises
------
InvalidStateError
If this DFA has invalid states in the transition dictionary.
MissingStateError
If this DFA has states missing from the transition dictionary.
InvalidSymbolError
If this DFA has invalid symbols in the transition dictionary.
MissingSymbolError
If this DFA is missing transitions on certain symbols.
"""
self._validate_transition_start_states()
for start_state, paths in self.transitions.items():
self._validate_transitions(start_state, paths)
self._validate_initial_state()
self._validate_final_states()
def _get_next_current_state(
self, current_state: DFAStateT, input_symbol: str
) -> Optional[DFAStateT]:
"""
Follow the transition for the given input symbol on the current state.
Return None if transition does not exist.
"""
if (
current_state is not None
and input_symbol in self.transitions[current_state]
):
return self.transitions[current_state][input_symbol]
return None
def _check_for_input_rejection(self, current_state: DFAStateT) -> None:
"""Raise an error if the given config indicates rejected input."""
if current_state not in self.final_states:
raise exceptions.RejectionException(
f"the DFA stopped on a non-final state ({current_state})"
)
def read_input_stepwise(
self, input_str: str, ignore_rejection: bool = False
) -> Generator[DFAStateT, None, None]:
"""
Return a generator that yields each step while reading input.
Parameters
----------
input_str : str
The input string to read.
ignore_rejection : bool, default: False
Whether to throw an exception if the input string is rejected.
Yields
------
Generator[DFAStateT, None, None]
A generator that yields the current configuration of the DFA
after each step of reading input.
Raises
------
RejectionException
Raised if this DFA does not accept the input string.
"""
current_state = self.initial_state
yield current_state
for input_symbol in input_str:
current_state = self._get_next_current_state(current_state, input_symbol)
yield current_state
if not ignore_rejection:
self._check_for_input_rejection(current_state)
@cached_method
def _get_digraph(self) -> nx.DiGraph:
"""Return a digraph corresponding to this DFA with transition symbols ignored"""
graph = nx.DiGraph()
graph.add_nodes_from(self.states)
graph.add_edges_from(
(start_state, end_state)
for start_state, transition in self.transitions.items()
for end_state in transition.values()
)
return graph
def minify(self, retain_names: bool = False) -> Self:
"""
Create a minimal DFA which accepts the same inputs as this DFA.
First, non-reachable states are removed.
Then, indistinguishable states are merged using Hopcroft's Algorithm.
Parameters
----------
retain_names : bool, default: False
Whether to retain original names when merging states.
New names are from 0 to n-1.
Returns
------
Self
A state-minimal equivalent DFA. May be complete in some cases
if the input is partial.
"""
if self.allow_partial:
# In the case of a partial DFA, we want to try to condense
# possible trap states before the main minify operation.
graph = self._get_digraph()
live_states = get_reachable_nodes(graph, [self.initial_state])
non_trap_states = get_reachable_nodes(
graph, self.final_states, reversed=True
)
reachable_states = live_states & non_trap_states
reachable_states.add(self.initial_state)
else:
# Compute reachable states and final states
bfs_states = self.__class__._bfs_states(
self.initial_state, lambda state: iter(self.transitions[state].items())
)
reachable_states = set(bfs_states)
reachable_final_states = self.final_states & reachable_states
return self.__class__._minify(
reachable_states=reachable_states,
input_symbols=self.input_symbols,
transitions=self.transitions,
initial_state=self.initial_state,
reachable_final_states=reachable_final_states,
retain_names=retain_names,
)
@classmethod
def _minify(
cls: Type[Self],
*,
reachable_states: AbstractSet[DFAStateT],
input_symbols: AbstractSet[str],
transitions: DFATransitionsT,
initial_state: DFAStateT,
reachable_final_states: AbstractSet[DFAStateT],
retain_names: bool,
) -> Self:
"""
Minify helper function. DFA data passed in must have no unreachable states.
If the input DFA is partial, then the result is also a partial DFA
"""
reachable_states = set(reachable_states)
# Per input-symbol backmap (tgt -> origin states)
transition_back_map: Dict[str, Dict[DFAStateT, List[DFAStateT]]] = {
symbol: {end_state: [] for end_state in reachable_states}
for symbol in input_symbols
}
trap_state = None
for start_state, path in transitions.items():
if start_state in reachable_states:
for symbol in input_symbols:
end_state = path.get(symbol)
if end_state is not None:
symbol_dict = transition_back_map[symbol]
# If statement here needed to ignore certain transitions
# for non-reachable states
if end_state in symbol_dict:
symbol_dict[end_state].append(start_state)
else:
# Add trap state if needed
if trap_state is None:
trap_state = next(
x for x in count(-1, -1) if x not in reachable_states
)
for trap_symbol in input_symbols:
transition_back_map[trap_symbol][trap_state] = []
reachable_states.add(trap_state)
transition_back_map[symbol][trap_state].append(start_state)
# Set up equivalence class data structure
eq_classes = PartitionRefinement(reachable_states)
refinement = eq_classes.refine(reachable_final_states)
final_states_id = (
refinement[0][0] if refinement else next(iter(eq_classes.get_set_ids()))
)
origin_dicts = tuple(transition_back_map.values())
processing = {final_states_id}
while processing:
# Save a copy of the set, since it could get modified while executing
active_state = tuple(eq_classes.get_set_by_id(processing.pop()))
for origin_dict in origin_dicts:
states_that_move_into_active_state = chain.from_iterable(
origin_dict[end_state] for end_state in active_state
)
# Refine set partition by states moving into current active one
new_eq_class_pairs = eq_classes.refine(
states_that_move_into_active_state
)
for YintX_id, YdiffX_id in new_eq_class_pairs:
# Only adding one id to processing, since the other is already there
if YdiffX_id in processing:
processing.add(YintX_id)
else:
if len(eq_classes.get_set_by_id(YintX_id)) <= len(
eq_classes.get_set_by_id(YdiffX_id)
):
processing.add(YintX_id)
else:
processing.add(YdiffX_id)
# now eq_classes are good to go, make them a list for ordering
eq_class_name_pairs: List[Tuple[DFAStateT, Set[DFAStateT]]] = (
[(frozenset(eq), eq) for eq in eq_classes.get_sets()]
if retain_names
else list(enumerate(eq_classes.get_sets()))
)
# need a backmap to prevent constant calls to index
back_map = {
state: name
for name, eq in eq_class_name_pairs
for state in eq
if trap_state not in eq
}
new_input_symbols = input_symbols
new_states = frozenset(back_map.values())
new_initial_state = back_map[initial_state]
new_final_states = frozenset(back_map[acc] for acc in reachable_final_states)
new_transitions = {}
for name, eq in eq_class_name_pairs:
# For trap state, can just leave out
if trap_state in eq:
continue
eq_class_rep = next(iter(eq))
inner_transition_dict_old = transitions[eq_class_rep]
new_transitions[name] = {
letter: back_map[inner_transition_dict_old[letter]]
for letter in inner_transition_dict_old.keys()
if inner_transition_dict_old[letter] in back_map.keys()
}
allow_partial = any(
len(lookup) != len(input_symbols) for lookup in new_transitions.values()
)
return cls(
states=new_states,
input_symbols=new_input_symbols,
transitions=new_transitions,
initial_state=new_initial_state,
final_states=new_final_states,
allow_partial=allow_partial,
)
def union(
self, other: DFA, *, retain_names: bool = False, minify: bool = True
) -> Self:
"""
Takes as input two DFAs M1 and M2 which
accept languages L1 and L2 respectively.
Returns a DFA which accepts the union of L1 and L2.
Minifies by default. Unreachable states are always removed.
If either input DFA is partial, the result is partial.
Parameters
----------
other : DFA
The DFA we want to take a union with.
retain_names : bool, default: False
Whether to retain state names through the union and optional minify.
minify : bool, default: True
Whether to minify the result of the union of the two DFAs.
Returns
------
Self
A DFA accepting the union of the two input DFAs. State minimal by
default.
"""
def union_function(state_pair: Tuple[DFAStateT, DFAStateT]) -> bool:
q_a, q_b = state_pair
return q_a in self.final_states or q_b in other.final_states
initial_state, expand_state_fn = self.__class__._cross_product(
self, other, lhs_relevant=True, rhs_relevant=True
)
return self.__class__._expand_dfa(
union_function,
initial_state,
expand_state_fn,
self.input_symbols,
retain_names=retain_names,
minify=minify,
)
def intersection(
self, other: DFA, *, retain_names: bool = False, minify: bool = True
) -> Self:
"""
Takes as input two DFAs M1 and M2 which
accept languages L1 and L2 respectively.
Returns a DFA which accepts the intersection of L1 and L2.
Minifies by default. Unreachable states are always removed.
If either input DFA is partial, the result is partial.
Parameters
----------
other : DFA
The DFA we want to take a intersection with.
retain_names : bool, default: False
Whether to retain state names through the intersection and optional minify.
minify : bool, default: True
Whether to minify the result of the intersection of the two DFAs.
Returns
------
Self
A DFA accepting the intersection of the two input DFAs. State minimal by
default.
"""
def intersection_function(state_pair: Tuple[DFAStateT, DFAStateT]) -> bool:
q_a, q_b = state_pair
return q_a in self.final_states and q_b in other.final_states
initial_state, expand_state_fn = self.__class__._cross_product(
self, other, lhs_relevant=False, rhs_relevant=False
)
return self.__class__._expand_dfa(
intersection_function,
initial_state,
expand_state_fn,
self.input_symbols,
retain_names=retain_names,
minify=minify,
)
def difference(
self, other: DFA, *, retain_names: bool = False, minify: bool = True
) -> Self:
"""
Takes as input two DFAs M1 and M2 which
accept languages L1 and L2 respectively.
Returns a DFA which accepts the difference of L1 and L2.
Minifies by default. Unreachable states are always removed.
If either input DFA is partial, the result is partial.
Parameters
----------
other : DFA
The DFA we want to take a difference with.
retain_names : bool, default: False
Whether to retain state names through the difference and optional minify.
minify : bool, default: True
Whether to minify the result of the difference of the two DFAs.
Returns
------
Self
A DFA accepting the difference of the two input DFAs. State minimal by
default.
"""
def difference_function(state_pair: Tuple[DFAStateT, DFAStateT]) -> bool:
q_a, q_b = state_pair
return q_a in self.final_states and q_b not in other.final_states
initial_state, expand_state_fn = self.__class__._cross_product(
self, other, lhs_relevant=False, rhs_relevant=True
)
return self.__class__._expand_dfa(
difference_function,
initial_state,
expand_state_fn,
self.input_symbols,
retain_names=retain_names,
minify=minify,
)
def symmetric_difference(
self, other: DFA, *, retain_names: bool = False, minify: bool = True
) -> Self:
"""
Takes as input two DFAs M1 and M2 which
accept languages L1 and L2 respectively.
Returns a DFA which accepts the symmetric difference of L1 and L2.
Minifies by default. Unreachable states are always removed.
If either input DFA is partial, the result is partial.
Parameters
----------
other : DFA
The DFA we want to take a symmetric difference with.
retain_names : bool, default: False
Whether to retain state names through the symmetric difference and optional
minify.
minify : bool, default: True
Whether to minify the result of the symmetric difference of the two DFAs.
Returns
------
Self
A DFA accepting the symmetric difference of the two input DFAs. State
minimal by default.
"""
def symmetric_difference_function(
state_pair: Tuple[DFAStateT, DFAStateT]
) -> bool:
q_a, q_b = state_pair
return (q_a in self.final_states) ^ (q_b in other.final_states)
initial_state, expand_state_fn = self.__class__._cross_product(
self, other, lhs_relevant=True, rhs_relevant=True
)
return self.__class__._expand_dfa(
symmetric_difference_function,
initial_state,
expand_state_fn,
self.input_symbols,
retain_names=retain_names,
minify=minify,
)
def complement(self, *, retain_names: bool = False, minify: bool = True) -> Self:
"""
Creates a DFA which accepts an input if and only if the old one does not.
Minifies by default. Unreachable states are always removed. Partial DFAs
are converted into complete ones.
Parameters
----------
retain_names : bool, default: False
Whether to retain state names through the complement and optional
minify.
minify : bool, default: True
Whether to minify the result of the complement of the input DFA.
Returns
------
Self
A DFA accepting the complement of the input DFA. State
minimal by default.
"""
# We can't do much here, we must turn it into a complete DFA
complete_dfa: Self = self.to_complete() if self.allow_partial else self
if minify:
bfs_states = self.__class__._bfs_states(
complete_dfa.initial_state,
lambda state: iter(complete_dfa.transitions[state].items()),
)
reachable_states = set(bfs_states)
reachable_final_states = complete_dfa.final_states & reachable_states
return complete_dfa.__class__._minify(
reachable_states=reachable_states,
input_symbols=complete_dfa.input_symbols,
transitions=complete_dfa.transitions,
initial_state=complete_dfa.initial_state,
reachable_final_states=reachable_states - reachable_final_states,
retain_names=retain_names,
)
return complete_dfa.__class__(
states=complete_dfa.states,
input_symbols=complete_dfa.input_symbols,
transitions=complete_dfa.transitions,
initial_state=complete_dfa.initial_state,
final_states=complete_dfa.states - complete_dfa.final_states,
)
@staticmethod
def _bfs_edges(
initial_state: DFAStateT,
expand_state_fn: ExpandStateFn,
) -> Generator[Tuple[DFAStateT, DFASymbolT, DFAStateT], None, None]:
"""
Emits the edges (src_state, label, tgt_state) visited by BFS from the
initial_state. Computes subsequent states using the function expand_state_fn.
"""
visited_set = {initial_state}
queue: Deque[Tuple[DFAStateT, DFAStateT]] = deque([initial_state])
while queue:
curr_state = queue.popleft()
for chr, tgt_state in expand_state_fn(curr_state):
yield curr_state, chr, tgt_state
if tgt_state not in visited_set:
visited_set.add(tgt_state)
queue.append(tgt_state)
@staticmethod
def _bfs_states(
initial_state: DFAStateT, expand_state_fn: ExpandStateFn
) -> Generator[DFAStateT, None, None]:
"""
Emits the states visited by BFS from the initial_state.
Computes subsequent states using the function expand_state_fn.
"""
yield initial_state
visited_set = {initial_state}
queue = deque([initial_state])
while queue:
curr_state = queue.popleft()
for _, tgt_state in expand_state_fn(curr_state):
if tgt_state not in visited_set:
yield tgt_state
visited_set.add(tgt_state)
queue.append(tgt_state)
@classmethod
def _expand_dfa(
cls: Type[Self],
final_state_fn: IsFinalStateFn,
initial_state: DFAStateT,
expand_state_fn: ExpandStateFn,
input_symbols: AbstractSet[DFASymbolT],
retain_names: bool = False,
minify: bool = True,
) -> Self:
"""
Constructs the DFA by expanding from the initial_state using the expand_state_fn
function. The function final_state_fn must return True for the final states.