-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpattern_mining.py
More file actions
2223 lines (1848 loc) · 61.8 KB
/
Copy pathpattern_mining.py
File metadata and controls
2223 lines (1848 loc) · 61.8 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
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
import numpy as np
import graphviz
from scipy.stats import norm
import itertools as it
def _validate_sequences(sequences):
"""
Validates the input sequences for a PPTA.
Parameters
----------
sequences : iterable of str
Sequences from which the alphabet is obtained.
Returns
-------
list of str
The validated list of sequences.
Raises
------
TypeError
If sequences is None, is a single string, or contains
non-string elements.
ValueError
If sequences is empty.
"""
if sequences is None:
raise TypeError(
"sequences must be an iterable of strings."
)
if isinstance(sequences, str):
raise TypeError(
"sequences must be an iterable of strings, "
"not a single string."
)
sequences = list(sequences)
if len(sequences) == 0:
raise ValueError(
"sequences must contain at least one sequence."
)
if not all(
isinstance(sequence, str)
for sequence in sequences
):
raise TypeError(
"every sequence must be a string."
)
return sequences
def _validate_alphabet(alphabet):
"""
Validates the input alphabet for a PPTA.
Parameters
----------
alphabet : iterable of str
Alphabet to validate.
Returns
-------
list of str
The validated list of alphabet symbols.
Raises
------
TypeError
If alphabet is None, is a single string, or contains
non-string elements.
ValueError
If alphabet is empty, contains non-single-character strings,
or contains duplicate symbols.
"""
if alphabet is None:
raise TypeError(
"alphabet must be an iterable of strings."
)
if isinstance(alphabet, str):
raise TypeError(
"alphabet must be an iterable of strings, "
"not a single string."
)
alphabet = list(alphabet)
if len(alphabet) == 0:
raise ValueError(
"alphabet must contain at least one symbol."
)
if not all(
isinstance(symbol, str)
for symbol in alphabet
):
raise TypeError(
"every alphabet symbol must be a string."
)
if not all(
len(symbol) == 1
for symbol in alphabet
):
raise ValueError(
"every alphabet symbol must contain exactly one character."
)
if len(alphabet) != len(set(alphabet)):
raise ValueError(
"alphabet must not contain duplicate symbols."
)
return alphabet
def _validate_transition_matrix(transition_matrix, alphabet, states):
"""
Validate a transition-count matrix and its associated dimensions.
Parameters
----------
transition_matrix : np.ndarray
Three-dimensional transition-count matrix with shape
``(n_symbols, n_states, n_states)``.
alphabet : collection
Alphabet associated with the first dimension of the transition
matrix.
states : collection
State identifiers associated with the final two dimensions of
the transition matrix.
Raises
------
TypeError
If transition_matrix is not a NumPy array.
ValueError
If transition_matrix is not three-dimensional, its final two
dimensions are not equal, its dimensions do not agree with
alphabet or states, or it contains non-finite or negative
values.
"""
if not isinstance(transition_matrix, np.ndarray):
raise TypeError(
"transition_matrix must be a NumPy array."
)
if transition_matrix.ndim != 3:
raise ValueError(
"transition_matrix must be three-dimensional."
)
if transition_matrix.shape[1] != transition_matrix.shape[2]:
raise ValueError(
"The final two transition_matrix dimensions must be equal."
)
if transition_matrix.shape[0] != len(alphabet):
raise ValueError(
"The first transition_matrix dimension must equal len(alphabet)."
)
if transition_matrix.shape[1] != len(states):
raise ValueError(
"The transition_matrix state dimensions must equal len(states)."
)
if not np.all(np.isfinite(transition_matrix)):
raise ValueError(
"transition_matrix must contain only finite values."
)
if np.any(transition_matrix < 0):
raise ValueError(
"transition_matrix must not contain negative values."
)
def _validate_alpha(alpha):
"""
Validate the alpha parameter for Hoeffding bound calculations.
Parameters
----------
alpha : float
Significance level for the Hoeffding bound.
Raises
------
TypeError
If alpha is not a numeric type.
ValueError
If alpha is not in the range (0,2].
"""
if not isinstance(alpha, (int, float, np.number)):
raise TypeError("alpha must be numeric.")
if alpha <= 0 or alpha > 2:
raise ValueError(
"alpha must be in the range (0, 2]."
)
def _validate_states_for_merging(q1, q2, states):
"""
Validate two states before performing a state merge.
Parameters
----------
q1 : int or str
First state proposed for merging.
q2 : int or str
Second state proposed for merging.
states : collection
Valid state identifiers in the automaton.
Raises
------
ValueError
If q1 or q2 is not present in states, if q1 and q2 refer
to the same state, or if either state is the artificial
initial state "*".
"""
if q1 not in states:
raise ValueError(
f"q1 must be a valid state. Unknown state: {q1!r}."
)
if q2 not in states:
raise ValueError(
f"q2 must be a valid state. Unknown state: {q2!r}."
)
if q1 == q2:
raise ValueError(
"q1 and q2 must refer to different states."
)
if q1 == "*" or q2 == "*":
raise ValueError(
"The artificial initial state '*' cannot be merged."
)
def get_alphabet(sequences):
"""
Returns the sorted alphabet across all sequences of a PPTA.
Parameters
----------
sequences : iterable of str
Sequences from which the alphabet is obtained.
Returns
-------
list of str
Sorted unique symbols appearing in the sequences.
Raises
------
TypeError
If sequences is None, is a single string, or contains
non-string elements.
ValueError
If sequences is empty.
"""
sequences = _validate_sequences(sequences)
return sorted(set("".join(sequences)))
def get_state_paths(sequences, build="breadth"):
"""
Return the state paths within a PPTA.
Parameters
----------
sequences : iterable of str
Sequences used to construct the PPTA.
build : {"breadth", "depth"}, default="breadth"
Order in which the state paths are constructed.
Returns
-------
list of str
State paths in the requested construction order.
Raises
------
TypeError
If sequences is None, is a single string, or contains
non-string elements.
ValueError
If sequences is empty or build is not "breadth" or "depth".
"""
sequences = _validate_sequences(sequences)
if build not in {"breadth", "depth"}:
raise ValueError(
"build must be either 'breadth' or 'depth'."
)
if build == "breadth":
all_paths = [""]
all_ordered = [""]
current_node = all_paths[0]
tracker = 0
while tracker < len(all_paths):
this_iter = sorted(
list(
set(
[
x[: len(current_node) + 1]
for x in sequences
if len(x) > len(current_node)
and x.startswith(current_node)
]
)
)
)
for j in range(len(this_iter)):
all_paths.append(this_iter[j])
all_ordered.insert(
all_ordered.index(current_node) + 1 + j,
this_iter[j],
)
tracker += 1
if tracker == len(all_paths):
break
current_node = all_ordered[
all_ordered.index(current_node) + 1
]
return all_paths
else:
all_paths = [""]
current_node = all_paths[0]
tracker = 0
while tracker < len(all_paths):
this_iter = sorted(
list(
set(
[
x[: len(current_node) + 1]
for x in sequences
if (
len(x) > len(current_node)
and x.startswith(current_node)
)
]
)
)
)
for j in range(len(this_iter)):
all_paths.append(this_iter[j])
tracker += 1
if tracker == len(all_paths):
break
current_node = all_paths[
all_paths.index(current_node) + 1
]
return all_paths
def get_transition_matrix(sequences, alphabet, build="breadth"):
"""
Return the transition-count matrix of a PPTA.
Parameters
----------
sequences : iterable of str
Sequences used to construct the PPTA.
alphabet : iterable of str
Symbols represented in the transition matrix.
build : {"breadth", "depth"}, default="breadth"
Order in which the PPTA states are constructed.
Returns
-------
np.ndarray
Three-dimensional transition-count matrix with shape
(number of symbols, number of states, number of states).
Raises
------
TypeError
If sequences or alphabet has an invalid type.
ValueError
If sequences or alphabet is empty, build is invalid, alphabet
contains duplicate symbols, or alphabet omits observed symbols.
"""
alphabet = _validate_alphabet(alphabet)
observed_symbols = set("".join(sequences))
missing_symbols = observed_symbols - set(alphabet)
if missing_symbols:
raise ValueError(
"alphabet is missing symbols found in sequences: "
f"{sorted(missing_symbols)}."
)
all_nodes = get_state_paths(sequences, build=build)
all_nodes.insert(0, "*")
n = len(all_nodes)
pathway_matrix = np.zeros((len(alphabet), n, n), dtype=int)
pathway_matrix[0, 0, 1] = len(sequences)
for i in range(1, n):
for k in range(len(alphabet)):
next_node = all_nodes[i] + alphabet[k]
if next_node in all_nodes:
pathway_matrix[k, i, all_nodes.index(next_node)] = len(
[x for x in sequences if x.startswith(next_node)]
)
return pathway_matrix
def get_initial_states(sequences):
"""
Return the initial state identifiers of a PPTA.
The artificial initial state ``"*"`` is followed by an integer
identifier for each prefix state in the PPTA.
Parameters
----------
sequences : iterable of str
Sequences used to construct the PPTA.
Returns
-------
list
State identifiers, beginning with the artificial initial state
``"*"``.
Raises
------
TypeError
If sequences is None, is a single string, or contains non-string
elements.
ValueError
If sequences is empty.
"""
states = list(range(len(get_state_paths(sequences))))
states.insert(0, "*")
return states
def get_n(q, pathway_matrix, states):
"""
Return the number of sequences entering a state.
This calculates ``n(q)`` by summing all transitions entering the
specified state.
Parameters
----------
q : int or str
State identifier.
pathway_matrix : np.ndarray
Transition-count matrix with shape
``(n_symbols, n_states, n_states)``.
states : list
State identifiers corresponding to the final two dimensions of
pathway_matrix.
Returns
-------
int or float
Number of sequences entering the state.
"""
i = states.index(q)
return pathway_matrix[:, :, i].sum()
def get_endpoint(q, pathway_matrix, states):
"""
Return the number of sequences terminating at a state.
The terminating count is calculated as the number of sequences entering
the state minus the number leaving it.
Parameters
----------
q : int or str
State identifier.
pathway_matrix : np.ndarray
Transition-count matrix with shape
``(n_symbols, n_states, n_states)``.
states : list
State identifiers corresponding to the final two dimensions of
pathway_matrix.
Returns
-------
int or float
Number of sequences terminating at the state.
"""
i = states.index(q)
return pathway_matrix[:, :, i].sum() - pathway_matrix[:, i, :].sum()
def get_pi(q, z, pathway_matrix, states):
"""
Return the probability of leaving a state via a symbol.
This calculates ``pi(q, z)`` for the symbol represented by index z in
the first dimension of the transition-count matrix.
Parameters
----------
q : int or str
State identifier.
z : int
Index of the symbol in the first dimension of pathway_matrix.
pathway_matrix : np.ndarray
Transition-count matrix with shape
``(n_symbols, n_states, n_states)``.
states : list
State identifiers corresponding to the final two dimensions of
pathway_matrix.
Returns
-------
float
Probability of leaving state q via the indexed symbol.
"""
i = states.index(q)
return pathway_matrix[z, i, :].sum() / get_n(q, pathway_matrix, states)
def get_pi_endpoint(q, pathway_matrix, alphabet, states):
"""
Return the probability of terminating at a state.
The terminating probability is one minus the sum of the probabilities
of leaving the state through each symbol in the alphabet.
Parameters
----------
q : int or str
State identifier.
pathway_matrix : np.ndarray
Transition-count matrix with shape
``(n_symbols, n_states, n_states)``.
alphabet : collection of str
Alphabet associated with the first dimension of pathway_matrix.
states : list
State identifiers corresponding to the final two dimensions of
pathway_matrix.
Returns
-------
float
Probability of terminating at state q.
"""
return 1 - sum(
get_pi(
q,
z,
pathway_matrix,
states,
) for z in range(len(alphabet))
)
def hoeffding_bound(q1, q2, alpha, pathway_matrix, alphabet, states):
"""
Determine whether two states satisfy the Hoeffding compatibility bound.
The transition probabilities associated with every symbol, together
with the terminating probabilities, are compared for the two states.
Parameters
----------
q1 : int or str
First state to compare.
q2 : int or str
Second state to compare.
alpha : float
Significance level used to calculate the Hoeffding bound. Expected
to be in the range ``(0, 2]``.
pathway_matrix : np.ndarray
Transition-count matrix with shape
``(n_symbols, n_states, n_states)``.
alphabet : collection of str
Alphabet associated with the first dimension of pathway_matrix.
states : list
State identifiers corresponding to the final two dimensions of
pathway_matrix.
Returns
-------
bool
True if all symbol and terminating probabilities satisfy the
Hoeffding bound; otherwise False.
"""
alpha_constant = (np.log(2 / alpha) / 2) ** 0.5
rhs = alpha_constant * (
(1 / np.sqrt(get_n(q1, pathway_matrix, states)))
+ (1 / np.sqrt(get_n(q2, pathway_matrix, states)))
)
for z in range(len(alphabet)):
lhs = abs(
get_pi(q1, z, pathway_matrix, states)
- get_pi(q2, z, pathway_matrix, states)
)
if lhs > rhs:
return False
lhs = abs(
get_pi_endpoint(q1, pathway_matrix, alphabet, states)
- get_pi_endpoint(q2, pathway_matrix, alphabet, states)
)
if lhs > rhs:
return False
return True
def merge_two_states(
q1,
q2,
pathway_matrix,
states,
alphabet,
red_states=None,
):
"""
Merge two states in a transition-count matrix.
The merged state retains the identifier of whichever state appears
first in the states list. The other state is removed.
Parameters
----------
q1 : int or str
First state to merge.
q2 : int or str
Second state to merge.
pathway_matrix : np.ndarray
Transition-count matrix with shape
``(n_symbols, n_states, n_states)``.
states : list
State identifiers corresponding to the final two dimensions of
pathway_matrix.
alphabet : iterable of str
Alphabet corresponding to the first dimension of pathway_matrix.
red_states : list, optional
Red states to update after the merge.
Returns
-------
pathway_matrix_copy : np.ndarray
Transition-count matrix after merging the states.
states_copy : list
Updated state identifiers.
red_states_copy : list, optional
Updated red states. Returned only when red_states is provided.
Raises
------
TypeError
If pathway_matrix is not a NumPy array or alphabet has an invalid
type.
ValueError
If alphabet or pathway_matrix has invalid contents or dimensions,
q1 or q2 is not present in states, q1 and q2 are identical, or the
artificial initial state is selected for merging.
"""
alphabet = _validate_alphabet(alphabet)
_validate_transition_matrix(
pathway_matrix,
alphabet,
states,
)
_validate_states_for_merging(
q1,
q2,
states,
)
return _merge_two_states(
q1,
q2,
pathway_matrix,
states,
red_states=red_states,
)
def _merge_two_states(q1, q2, pathway_matrix, states, red_states=None):
"""
Internal function that merges two states in a transition-count matrix.
The merged state retains the identifier of whichever state appears
first in the states list. The other state is removed. Assumes that
the input parameters have already been validated.
Parameters
----------
q1 : int or str
First state to merge.
q2 : int or str
Second state to merge.
pathway_matrix : np.ndarray
Transition-count matrix with shape
``(n_symbols, n_states, n_states)``.
states : list
State identifiers corresponding to the final two dimensions of
pathway_matrix.
red_states : list, optional
Red states to update after the merge.
Returns
-------
pathway_matrix_copy : np.ndarray
Transition-count matrix after merging the states.
states_copy : list
Updated state identifiers.
red_states_copy : list, optional
Updated red states. Returned only when red_states is provided.
"""
i1 = states.index(q1)
i2 = states.index(q2)
which_min = min(i1, i2)
which_max = max(i1, i2)
surviving_state = states[which_min]
removed_state = states[which_max]
pathway_matrix_copy = np.copy(pathway_matrix)
states_copy = states.copy()
pathway_matrix_copy[:, :, which_min] = (
pathway_matrix_copy[:, :, i1]
+ pathway_matrix_copy[:, :, i2]
)
pathway_matrix_copy = np.delete(
pathway_matrix_copy,
which_max,
axis=2,
)
pathway_matrix_copy[:, which_min, :] = (
pathway_matrix_copy[:, i1, :]
+ pathway_matrix_copy[:, i2, :]
)
pathway_matrix_copy = np.delete(
pathway_matrix_copy,
which_max,
axis=1,
)
states_copy.remove(removed_state)
if red_states is not None:
red_states_copy = [
surviving_state if state == removed_state else state
for state in red_states
]
return (
pathway_matrix_copy,
states_copy,
red_states_copy,
)
return pathway_matrix_copy, states_copy
def check_is_deterministic(pathway_matrix, states, alphabet):
"""
Identify nondeterministic state pairs in a transition matrix.
A state is considered nondeterministic when it has positive transitions
to more than one destination through the same alphabet symbol. For each
such state-symbol combination, the first pair of destination states is
returned.
Parameters
----------
pathway_matrix : np.ndarray
Transition-count matrix with shape
``(n_symbols, n_states, n_states)``.
states : list
State identifiers corresponding to the final two dimensions of
pathway_matrix.
alphabet : collection of str
Alphabet associated with the first dimension of pathway_matrix.
Returns
-------
list of tuple
Pairs of destination state identifiers involved in
nondeterministic transitions. An empty list indicates that the
transition matrix is deterministic.
"""
nondeterministic_pairs = []
for a in range(len(alphabet)):
rows = np.where(
(pathway_matrix[a, :, :] > 0).sum(axis=1) > 1
)[0]
for row in rows:
where_non_det = np.where(pathway_matrix[a, row, :] > 0)[0]
if len(where_non_det) > 2:
nond_pairs = np.reshape(where_non_det[:2], (1, 2))
else:
nond_pairs = np.reshape(where_non_det, (1, 2))
nondeterministic_pairs += [
tuple(states[i] for i in r) for r in nond_pairs
]
return nondeterministic_pairs
def recursive_merge_two_states(
q1,
q2,
pathway_matrix,
states,
alpha,
alphabet,
red_states=None,
output="Suppressed",
method="Carrasco",
):
"""
Recursively merge states until the resulting automaton is deterministic.
The initial pair is merged and any nondeterministic state pairs created
by that merge are considered recursively. A recursive pair is merged
only when it satisfies the Hoeffding compatibility bound.
Parameters
----------
q1 : int or str
First state to merge.
q2 : int or str
Second state to merge.
pathway_matrix : np.ndarray
Transition-count matrix with shape
``(n_symbols, n_states, n_states)``.
states : list
State identifiers corresponding to the final two dimensions of
pathway_matrix.
alpha : float
Significance level used by the Hoeffding compatibility test.
alphabet : iterable of str
Alphabet corresponding to the first dimension of pathway_matrix.
red_states : list, optional
Red states to update during a Higuera merge. Required when
method is ``"Higuera"``.
output : {"Suppressed", "Truncated", "Full"}, default="Suppressed"
Amount of progress information printed.
method : {"Carrasco", "Higuera"}, default="Carrasco"
State-merging methodology to use.
Returns
-------
new_matrix : np.ndarray
Transition-count matrix after the recursive merge attempt.
new_states : list
State identifiers corresponding to new_matrix.
recursive_merge : bool
True if the complete recursive merge succeeds; otherwise False.
red_states_result : list, optional
Red states produced by the merge. Returned only when method is
``"Higuera"``.
Raises
------
TypeError
If alpha is not numeric, pathway_matrix is not a NumPy array, or
alphabet has an invalid type.
ValueError
If output or method is invalid, red_states is not provided for the
Higuera method, alpha is outside ``(0, 2]``, alphabet or
pathway_matrix is invalid, either state is unknown, the states are
identical, or the artificial initial state is selected.
"""
valid_outputs = {"Suppressed", "Truncated", "Full"}
if output not in valid_outputs:
raise ValueError(
"output must be 'Suppressed', 'Truncated', or 'Full'."
)
valid_methods = {"Carrasco", "Higuera"}
if method not in valid_methods:
raise ValueError(
"method must be either 'Carrasco' or 'Higuera'."
)
if method == "Higuera" and red_states is None:
raise ValueError(
"red_states must be provided when method='Higuera'."
)
_validate_alpha(alpha)
alphabet = _validate_alphabet(alphabet)
_validate_transition_matrix(
pathway_matrix,
alphabet,
states,
)
_validate_states_for_merging(
q1,
q2,
states,
)
return _recursive_merge_two_states(
q1,
q2,
pathway_matrix,
states,
alpha,
alphabet,
red_states=red_states,
output=output,
method=method,
)
def _recursive_merge_two_states(
q1,
q2,
pathway_matrix,
states,
alpha,
alphabet,
red_states=None,
output="Suppressed",
method="Carrasco",
):
"""
Recursively merge previously validated states until determinism is restored.
The function assumes that q1, q2, pathway_matrix, states, alpha, and
alphabet have already been validated. It attempts to resolve each
nondeterministic pair created by the initial merge using the Hoeffding
compatibility bound.
Parameters
----------
q1 : int or str
First state to merge.
q2 : int or str
Second state to merge.
pathway_matrix : np.ndarray
Transition-count matrix with shape
``(n_symbols, n_states, n_states)``.
states : list
State identifiers corresponding to the final two dimensions of
pathway_matrix.
alpha : float
Significance level used by the Hoeffding compatibility test.
alphabet : collection of str