automata_core 0.2.1

Deterministic and nondeterministic automata algorithms in Rust
Documentation
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
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::Hash;

use crate::labeled::arbitrary::DeterministicLabeledAutomaton;
use crate::labeled::arbitrary::LabeledAutomaton;
use crate::labeled::finite::DeterministicFiniteLabeledAutomaton;
use crate::labeled::finite::FiniteLabeledAutomaton;

use super::error::SimpleBuildError;
use super::nfa::SimpleLabeledNFA;
use super::state::SimpleLabeledDFAState;

/// Dense deterministic finite automaton with **state labels** (`char` alphabet).
///
/// States are `0..state_count`. Transitions are stored as one `HashMap<char, State>`
/// per row; missing edges mean “undefined” until [`complete`](DeterministicFiniteLabeledAutomaton::complete).
/// Final states are those with [`Some`] label from [`get_label`](LabeledAutomaton::get_label).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SimpleLabeledDFA<Label: Hash + Eq + Clone> {
    pub(crate) initial: SimpleLabeledDFAState,
    pub(crate) labels: HashMap<SimpleLabeledDFAState, Label>,
    pub(crate) alphabet: HashSet<char>,
    pub(crate) transitions: Vec<HashMap<char, SimpleLabeledDFAState>>,
}

impl<Label: Hash + Eq + Clone> SimpleLabeledDFA<Label> {
    /// Construct without validating invariants (tests and internal use).
    ///
    /// Assumes:
    /// - `initial < state_count`
    /// - every state in `labels` is within `0..state_count`
    /// - all transition endpoints are within range
    /// - transition symbols belong to `alphabet`
    /// - at most one transition per `(state, symbol)`
    pub fn new_labeled_unchecked(
        state_count: usize,
        initial: SimpleLabeledDFAState,
        labels: impl IntoIterator<Item = (SimpleLabeledDFAState, Label)>,
        alphabet: impl IntoIterator<Item = char>,
        transitions: impl IntoIterator<Item = (SimpleLabeledDFAState, char, SimpleLabeledDFAState)>,
    ) -> Self {
        let alphabet: HashSet<char> = alphabet.into_iter().collect();
        let labels: HashMap<_, _> = labels.into_iter().collect();
        let mut rows = vec![HashMap::new(); state_count];
        for (q, a, p) in transitions {
            rows[q].insert(a, p);
        }
        Self {
            initial,
            labels,
            alphabet,
            transitions: rows,
        }
    }

    /// Construct with validation.
    ///
    /// See [`SimpleBuildError`] for possible failures.
    pub fn try_new_labeled(
        state_count: usize,
        initial: SimpleLabeledDFAState,
        labels: impl IntoIterator<Item = (SimpleLabeledDFAState, Label)>,
        alphabet: impl IntoIterator<Item = char>,
        transitions: impl IntoIterator<Item = (SimpleLabeledDFAState, char, SimpleLabeledDFAState)>,
    ) -> Result<Self, SimpleBuildError> {
        if initial >= state_count {
            return Err(SimpleBuildError::InitialOutOfRange {
                initial,
                state_count,
            });
        }
        let alphabet: HashSet<char> = alphabet.into_iter().collect();
        let labels: HashMap<_, _> = labels.into_iter().collect();
        for (&s, _) in &labels {
            if s >= state_count {
                return Err(SimpleBuildError::StateOutOfRange {
                    state: s,
                    state_count,
                });
            }
        }
        let mut rows = vec![HashMap::new(); state_count];
        for (q, a, p) in transitions {
            if q >= state_count {
                return Err(SimpleBuildError::TransitionFromOutOfRange {
                    from: q,
                    state_count,
                });
            }
            if p >= state_count {
                return Err(SimpleBuildError::TransitionToOutOfRange { to: p, state_count });
            }
            if !alphabet.contains(&a) {
                return Err(SimpleBuildError::SymbolNotInAlphabet(a));
            }
            if rows[q].insert(a, p).is_some() {
                return Err(SimpleBuildError::DuplicateDeterministicTransition {
                    state: q,
                    symbol: a,
                });
            }
        }
        Ok(Self {
            initial,
            labels,
            alphabet,
            transitions: rows,
        })
    }

    /// Convert this DFA into a dense transition matrix `M[state][input]`.
    ///
    /// Each cell contains `Some(next_state)` if the transition exists for the
    /// symbol, otherwise `None`.
    pub fn to_matrix(&self) -> Vec<Vec<Option<SimpleLabeledDFAState>>> {
        self.states()
            .map(|s| {
                self.alphabet()
                    .map(|a| self.transition(s, &a))
                    .collect::<Vec<Option<SimpleLabeledDFAState>>>()
            })
            .collect()
    }

    /// Get a vector of labels for each state.
    pub fn get_labels_vec(&self) -> Vec<Option<Label>> {
        self.states().map(|s| self.get_label(s)).collect()
    }

    /// Map every stored label through `f`; structure and transitions unchanged.
    pub fn map_labels<NewLabel: Hash + Eq + Clone>(
        &self,
        f: impl Fn(Label) -> NewLabel,
    ) -> SimpleLabeledDFA<NewLabel> {
        SimpleLabeledDFA {
            initial: self.initial,
            labels: self
                .labels
                .iter()
                .map(|(&k, v)| (k, f(v.clone())))
                .collect(),
            alphabet: self.alphabet.clone(),
            transitions: self.transitions.clone(),
        }
    }

    /// Replace all labels with `()` (same accepting states, unit labels).
    pub fn drop_labels(&self) -> SimpleLabeledDFA<()> {
        self.map_labels(|_| ())
    }

    /// Minimize using Hopcroft's algorithm.
    ///
    /// The automaton is completed first. The initial partition groups states by
    /// [`get_label`](LabeledAutomaton::get_label) (`Option<Label>`), not by
    /// accepting vs non-accepting alone.
    fn hopcroft_minimize(&self) -> Self {
        let dfa = self.completed();
        let n = dfa.transitions.len();
        let mut alphabet_sorted: Vec<char> = dfa.alphabet.iter().copied().collect();
        alphabet_sorted.sort_unstable();
        let sym_idx: HashMap<char, usize> = alphabet_sorted
            .iter()
            .enumerate()
            .map(|(i, &c)| (c, i))
            .collect();
        let sigma = alphabet_sorted.len();

        let mut inverse: Vec<Vec<Vec<usize>>> = vec![vec![Vec::new(); sigma]; n];
        for q in 0..n {
            for (&a, &p) in &dfa.transitions[q] {
                if let Some(&i) = sym_idx.get(&a) {
                    inverse[p][i].push(q);
                }
            }
        }

        let mut groups: HashMap<Option<Label>, Vec<usize>> = HashMap::new();
        for q in 0..n {
            let key = dfa.labels.get(&q).cloned();
            groups.entry(key).or_default().push(q);
        }
        let mut blocks: Vec<Vec<usize>> = groups.into_values().collect();
        for b in &mut blocks {
            b.sort_unstable();
        }
        blocks.sort_by_key(|b| b[0]);

        let mut block_of = vec![0usize; n];
        for (bid, states) in blocks.iter().enumerate() {
            for &q in states {
                block_of[q] = bid;
            }
        }

        let mut in_queue = vec![false; blocks.len()];
        let mut waiting = VecDeque::new();

        fn try_enqueue(in_queue: &mut [bool], waiting: &mut VecDeque<usize>, bid: usize) {
            if bid < in_queue.len() && !in_queue[bid] {
                in_queue[bid] = true;
                waiting.push_back(bid);
            }
        }

        for bid in 0..blocks.len() {
            try_enqueue(&mut in_queue, &mut waiting, bid);
        }

        while let Some(b_b) = waiting.pop_front() {
            if b_b >= in_queue.len() || !in_queue[b_b] {
                continue;
            }
            in_queue[b_b] = false;
            if blocks[b_b].is_empty() {
                continue;
            }

            for si in 0..sigma {
                let mut pred_set: HashSet<usize> = HashSet::new();
                for &q in &blocks[b_b] {
                    for &pre in &inverse[q][si] {
                        pred_set.insert(pre);
                    }
                }
                if pred_set.is_empty() {
                    continue;
                }

                let mut s_bid = 0;
                while s_bid < blocks.len() {
                    if blocks[s_bid].is_empty() {
                        s_bid += 1;
                        continue;
                    }
                    let intersects = blocks[s_bid].iter().any(|&q| pred_set.contains(&q));
                    let has_outside = blocks[s_bid].iter().any(|&q| !pred_set.contains(&q));
                    if !intersects || !has_outside {
                        s_bid += 1;
                        continue;
                    }

                    let was_in_w = in_queue[s_bid];
                    in_queue[s_bid] = false;

                    let mut inside = Vec::new();
                    let mut outside = Vec::new();
                    for &q in &blocks[s_bid] {
                        if pred_set.contains(&q) {
                            inside.push(q);
                        } else {
                            outside.push(q);
                        }
                    }
                    inside.sort_unstable();
                    outside.sort_unstable();

                    let new_bid = blocks.len();
                    blocks[s_bid] = outside;
                    blocks.push(inside);
                    in_queue.push(false);

                    for &q in &blocks[new_bid] {
                        block_of[q] = new_bid;
                    }

                    if was_in_w {
                        try_enqueue(&mut in_queue, &mut waiting, s_bid);
                        try_enqueue(&mut in_queue, &mut waiting, new_bid);
                    } else if blocks[s_bid].len() <= blocks[new_bid].len() {
                        try_enqueue(&mut in_queue, &mut waiting, s_bid);
                    } else {
                        try_enqueue(&mut in_queue, &mut waiting, new_bid);
                    }

                    s_bid += 1;
                }
            }
        }

        let k = blocks.len();
        let rep: Vec<usize> = blocks
            .iter()
            .map(|states| *states.iter().min().expect("non-empty block"))
            .collect();

        let mut transitions = vec![HashMap::new(); k];
        let mut labels = HashMap::new();
        for bid in 0..k {
            let q = rep[bid];
            if let Some(l) = dfa.labels.get(&q) {
                labels.insert(bid, l.clone());
            }
            for &a in &alphabet_sorted {
                let p = dfa.transitions[q][&a];
                let nb = block_of[p];
                transitions[bid].insert(a, nb);
            }
        }

        SimpleLabeledDFA {
            initial: block_of[dfa.initial],
            labels,
            alphabet: dfa.alphabet.clone(),
            transitions,
        }
    }

    fn completed(&self) -> Self {
        if self.alphabet.is_empty() {
            return self.clone();
        }
        let n = self.transitions.len();
        let already_total = (0..n).all(|q| {
            self.alphabet
                .iter()
                .all(|&a| self.transitions[q].contains_key(&a))
        });
        if already_total {
            return self.clone();
        }
        let sink = n;
        let mut rows = self.transitions.clone();
        rows.push(HashMap::new());
        for row in rows.iter_mut().take(n) {
            for &a in &self.alphabet {
                row.entry(a).or_insert(sink);
            }
        }
        for &a in &self.alphabet {
            rows[sink].insert(a, sink);
        }
        Self {
            initial: self.initial,
            labels: self.labels.clone(),
            alphabet: self.alphabet.clone(),
            transitions: rows,
        }
    }
}

impl<Label: Hash + Eq + Clone> LabeledAutomaton<Label> for SimpleLabeledDFA<Label> {
    type State = SimpleLabeledDFAState;
    type Input = char;

    fn states<'a>(&'a self) -> impl Iterator<Item = Self::State> + 'a {
        0..self.transitions.len()
    }

    fn alphabet<'a>(&'a self) -> impl Iterator<Item = Self::Input> + 'a {
        self.alphabet.iter().copied()
    }

    fn is_valid_state(&self, state: Self::State) -> bool {
        state < self.transitions.len()
    }

    fn is_initial_state(&self, state: Self::State) -> bool {
        state == self.initial
    }

    fn get_label(&self, state: Self::State) -> Option<Label> {
        self.labels.get(&state).cloned()
    }
}

impl<Label: Hash + Eq + Clone> FiniteLabeledAutomaton<Label> for SimpleLabeledDFA<Label> {
    fn alphabet_set(&self) -> HashSet<Self::Input> {
        self.alphabet.clone()
    }
}

impl<Label: Hash + Eq + Clone> DeterministicLabeledAutomaton<Label> for SimpleLabeledDFA<Label> {
    fn initial_state(&self) -> Self::State {
        self.initial
    }

    fn transition(&self, state: Self::State, input: &Self::Input) -> Option<Self::State> {
        self.transitions.get(state)?.get(input).copied()
    }
}

impl<Label: Hash + Eq + Clone> DeterministicFiniteLabeledAutomaton<Label>
    for SimpleLabeledDFA<Label>
{
    type CorrespondingNFA = SimpleLabeledNFA<Label>;

    fn to_nfa(&self) -> Self::CorrespondingNFA {
        let edges: Vec<(usize, char, usize)> = self
            .transitions
            .iter()
            .enumerate()
            .flat_map(|(q, transition)| transition.iter().map(move |(&a, &p)| (q, a, p)))
            .collect();

        SimpleLabeledNFA::new_labeled_unchecked(
            self.transitions.len(),
            [self.initial],
            self.labels.iter().map(|(s, l)| (*s, l.clone())),
            self.alphabet.iter().copied(),
            edges,
        )
    }

    fn complete(&self) -> Self {
        self.completed()
    }

    fn minimize(&self) -> Self {
        self.hopcroft_minimize()
    }
}