Vinyeh commited on
Commit
418013d
·
verified ·
1 Parent(s): 1e7b972

Add pinned source: pm4py-process (part 5)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/to_embeddings/variants/cases_transformers.py +33 -0
  2. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/to_embeddings/variants/events_transformers.py +33 -0
  3. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/__init__.py +22 -0
  4. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/algorithm.py +122 -0
  5. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/__init__.py +22 -0
  6. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/embed_sentence.py +57 -0
  7. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/locally_linear_embedding.py +135 -0
  8. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/petri_net.py +107 -0
  9. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/similarity.py +58 -0
  10. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/sklearn_vectorization.py +169 -0
  11. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/trace_text.py +201 -0
  12. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/__init__.py +38 -0
  13. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/alignments.py +153 -0
  14. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/bert.py +117 -0
  15. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/cases_transformers.py +161 -0
  16. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/count2vec.py +96 -0
  17. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/doc2vec.py +138 -0
  18. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/event_based.py +227 -0
  19. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/events_transformers.py +173 -0
  20. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/n_grams.py +98 -0
  21. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/one_hot.py +96 -0
  22. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/temporal.py +245 -0
  23. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/temporal_lazy.py +325 -0
  24. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/tf_idf.py +94 -0
  25. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/token_replay.py +145 -0
  26. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/trace_based.py +1669 -0
  27. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/word2vec.py +149 -0
  28. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/analysis.py +980 -0
  29. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/cli.py +450 -0
  30. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/conformance.py +1578 -0
  31. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/connectors.py +661 -0
  32. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/convert.py +713 -0
  33. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/discovery.py +1790 -0
  34. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/filtering.py +2230 -0
  35. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/hof.py +170 -0
  36. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/llm.py +971 -0
  37. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/meta.py +29 -0
  38. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/ml.py +543 -0
  39. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/__init__.py +43 -0
  40. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/__init__.py +29 -0
  41. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/__init__.py +22 -0
  42. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/exporter.py +83 -0
  43. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/variants/__init__.py +22 -0
  44. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/variants/etree.py +369 -0
  45. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/__init__.py +22 -0
  46. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/importer.py +84 -0
  47. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/variants/__init__.py +22 -0
  48. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/variants/lxml.py +736 -0
  49. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/__init__.py +22 -0
  50. source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/layouter.py +57 -0
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/to_embeddings/variants/cases_transformers.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ import warnings
23
+
24
+ warnings.warn(
25
+ "pm4py.algo.transformation.to_embeddings.variants.cases_transformers is "
26
+ "deprecated; use "
27
+ "pm4py.algo.transformation.trace_encodings.variants.cases_transformers "
28
+ "instead.",
29
+ FutureWarning,
30
+ stacklevel=2,
31
+ )
32
+
33
+ from pm4py.algo.transformation.trace_encodings.variants.cases_transformers import * # noqa
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/to_embeddings/variants/events_transformers.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ import warnings
23
+
24
+ warnings.warn(
25
+ "pm4py.algo.transformation.to_embeddings.variants.events_transformers is "
26
+ "deprecated; use "
27
+ "pm4py.algo.transformation.trace_encodings.variants.events_transformers "
28
+ "instead.",
29
+ FutureWarning,
30
+ stacklevel=2,
31
+ )
32
+
33
+ from pm4py.algo.transformation.trace_encodings.variants.events_transformers import * # noqa
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.algo.transformation.trace_encodings import algorithm, variants, util
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/algorithm.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from enum import Enum
23
+ from typing import Any, Optional, Dict, Union, List, Tuple
24
+
25
+ import pandas as pd
26
+
27
+ from pm4py.objects.log.obj import EventLog, EventStream
28
+ from pm4py.util import exec_utils
29
+ from pm4py.algo.transformation.trace_encodings.variants import (
30
+ alignments,
31
+ bert,
32
+ cases_transformers,
33
+ count2vec,
34
+ doc2vec,
35
+ event_based,
36
+ events_transformers,
37
+ n_grams,
38
+ one_hot,
39
+ trace_based,
40
+ temporal,
41
+ temporal_lazy,
42
+ tf_idf,
43
+ token_replay,
44
+ word2vec,
45
+ )
46
+
47
+
48
+ class Variants(Enum):
49
+ ALIGNMENTS = alignments
50
+ BERT = bert
51
+ COUNT2VEC = count2vec
52
+ DOC2VEC = doc2vec
53
+ EVENT_BASED = event_based
54
+ CASES_TRANSFORMERS = cases_transformers
55
+ EVENTS_TRANSFORMERS = events_transformers
56
+ N_GRAMS = n_grams
57
+ ONE_HOT = one_hot
58
+ TRACE_BASED = trace_based
59
+ TEMPORAL = temporal
60
+ TEMPORAL_LAZY = temporal_lazy
61
+ TF_IDF = tf_idf
62
+ TOKEN_REPLAY = token_replay
63
+ WORD2VEC = word2vec
64
+
65
+
66
+ def apply(
67
+ log: Union[EventLog, pd.DataFrame, EventStream],
68
+ variant: Any = Variants.TRACE_BASED,
69
+ parameters: Optional[Dict[Any, Any]] = None,
70
+ ) -> Tuple[Any, List[str]]:
71
+ """
72
+ Encodes traces from a log object.
73
+
74
+ Parameters
75
+ ---------------
76
+ log
77
+ Event log
78
+ variant
79
+ Variant of the feature extraction to use:
80
+
81
+ - Variants.ALIGNMENTS => encodes Petri-net alignment diagnostics
82
+ - Variants.BERT => embeds trace sentences using sentence-transformers
83
+ - Variants.COUNT2VEC => counts trace token occurrences using scikit-learn
84
+ - Variants.DOC2VEC => embeds traces as gensim Doc2Vec document vectors
85
+ - Variants.EVENT_BASED => extracts, for each trace, a list of numerical vectors containing for each event the corresponding features
86
+ - Variants.CASES_TRANSFORMERS => computes sentence-transformer embeddings at the case level
87
+ - Variants.EVENTS_TRANSFORMERS => computes sentence-transformer embeddings at the event level
88
+ - Variants.N_GRAMS => counts contiguous trace token n-grams using scikit-learn
89
+ - Variants.ONE_HOT => extracts binary trace token occurrence vectors using scikit-learn
90
+ - Variants.TRACE_BASED => extracts for each trace a single numerical vector containing the features of the trace
91
+ - Variants.TEMPORAL => extracts temporal features from the traditional event log
92
+ - Variants.TEMPORAL_LAZY => extracts temporal features from a Polars LazyFrame
93
+ - Variants.TF_IDF => weights trace tokens/n-grams using scikit-learn TF-IDF
94
+ - Variants.TOKEN_REPLAY => encodes token-replay diagnostics
95
+ - Variants.WORD2VEC => aggregates gensim Word2Vec token vectors per trace
96
+
97
+ Returns
98
+ ---------------
99
+ data
100
+ Data to provide for decision tree learning
101
+ feature_names
102
+ Names of the features, in order
103
+ """
104
+ if parameters is None:
105
+ parameters = {}
106
+
107
+ return exec_utils.get_variant(variant).apply(log, parameters=parameters)
108
+
109
+
110
+ def keep_top_k_per_similarity(
111
+ log: pd.DataFrame,
112
+ target_sentence: str,
113
+ k: int,
114
+ variant=Variants.CASES_TRANSFORMERS,
115
+ parameters: Optional[Dict[Any, Any]] = None,
116
+ ) -> pd.DataFrame:
117
+ """
118
+ Keeps the top K events/cases per embedding similarity.
119
+ """
120
+ return exec_utils.get_variant(variant).keep_top_k_per_similarity(
121
+ log, target_sentence, k, parameters=parameters
122
+ )
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.algo.transformation.trace_encodings.util import petri_net
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/embed_sentence.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from typing import List, Optional, Dict, Any
23
+ from enum import Enum
24
+ from pm4py.util import exec_utils, constants
25
+
26
+
27
+ class Parameters(Enum):
28
+ EMBEDDING_MODEL = "embedding_model"
29
+
30
+
31
+ def apply(sentence: str, parameters: Optional[Dict[Any, Any]] = None) -> List[float]:
32
+ """
33
+ Encodes a sentence to embeddings
34
+
35
+ Parameters
36
+ ----------
37
+ sentence
38
+ Sentence to be encoded
39
+ parameters
40
+ Parameters of the method, including:
41
+ - Parameters.EMBEDDING_MODEL => embedding model to be used (default: all-MiniLM-L6-v2)
42
+
43
+ Returns
44
+ -------
45
+ embeddings
46
+ List of numerical embeddings
47
+ """
48
+ if parameters is None:
49
+ parameters = {}
50
+
51
+ embedding_model = exec_utils.get_param_value(Parameters.EMBEDDING_MODEL, parameters,
52
+ constants.DEFAULT_EMBEDDING_MODEL)
53
+
54
+ from sentence_transformers import SentenceTransformer
55
+ model = SentenceTransformer(embedding_model)
56
+
57
+ return model.encode([sentence])[0]
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/locally_linear_embedding.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ import math
23
+ from datetime import datetime
24
+ from enum import Enum
25
+ from typing import Optional, Dict, Any, Tuple, List
26
+
27
+ import numpy as np
28
+ from pm4py.util import ml_utils
29
+
30
+ from pm4py.objects.conversion.log import converter as log_converter
31
+ from pm4py.objects.log.obj import EventLog
32
+ from pm4py.algo.transformation.trace_encodings import (
33
+ algorithm as trace_encodings,
34
+ )
35
+ from pm4py.objects.log.util import sorting
36
+ from pm4py.util import constants, xes_constants
37
+ from pm4py.util import exec_utils, pandas_utils
38
+
39
+
40
+ class Parameters(Enum):
41
+ ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
42
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
43
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
44
+
45
+
46
+ def smooth(y: np.ndarray, box_pts: int) -> np.ndarray:
47
+ """
48
+ Smooths the points in y with a weighted average.
49
+
50
+ Parameters
51
+ ----------------
52
+ y
53
+ Points
54
+ box_pts
55
+ Size of the weighted average
56
+
57
+ Returns
58
+ ----------------
59
+ y_smooth
60
+ Smoothened y
61
+ """
62
+ box = np.ones(box_pts) / box_pts
63
+ y_smooth = np.convolve(y, box, mode="same")
64
+ return y_smooth
65
+
66
+
67
+ def apply(
68
+ log: EventLog, parameters: Optional[Dict[str, Any]] = None
69
+ ) -> Tuple[List[datetime], np.ndarray]:
70
+ """
71
+ Analyse the evolution of the features over the time using a locally linear embedding.
72
+
73
+ Parameters
74
+ -----------------
75
+ log
76
+ Event log
77
+ parameters
78
+ Variant-specific parameters, including:
79
+ - Parameters.ACTIVITY_KEY => the activity key
80
+ - Parameters.TIMESTAMP_KEY => the timestamp key
81
+ - Parameters.CASE_ID_KEY => the case ID key
82
+
83
+ Returns
84
+ ----------------
85
+ x
86
+ Date attributes (starting points of the cases)
87
+ y
88
+ Deviation from the standard behavior (higher absolute values of y signal a higher deviation
89
+ from the standard behavior)
90
+ """
91
+ if parameters is None:
92
+ parameters = {}
93
+
94
+ activity_key = exec_utils.get_param_value(
95
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
96
+ )
97
+ timestamp_key = exec_utils.get_param_value(
98
+ Parameters.TIMESTAMP_KEY,
99
+ parameters,
100
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
101
+ )
102
+
103
+ if pandas_utils.check_is_pandas_dataframe(log):
104
+ # keep only the needed columns
105
+ case_id_key = exec_utils.get_param_value(
106
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
107
+ )
108
+ log = log[[case_id_key, activity_key, timestamp_key]]
109
+
110
+ log = log_converter.apply(
111
+ log, variant=log_converter.Variants.TO_EVENT_LOG, parameters=parameters
112
+ )
113
+ log = sorting.sort_timestamp(log, timestamp_key)
114
+
115
+ x = [trace[0][timestamp_key] for trace in log]
116
+ data, feature_names = trace_encodings.apply(
117
+ log,
118
+ parameters={
119
+ "str_ev_attr": [activity_key],
120
+ "str_evsucc_attr": [activity_key],
121
+ },
122
+ )
123
+ data = np.array([np.array(x) for x in data])
124
+
125
+ tsne = ml_utils.LocallyLinearEmbedding(
126
+ n_components=1, eigen_solver="dense"
127
+ )
128
+ data = tsne.fit_transform(data)
129
+ data = np.ndarray.flatten(data)
130
+
131
+ y = data
132
+ smooth_amount = 1 + math.floor(math.sqrt(len(y)))
133
+ y = smooth(y, smooth_amount)
134
+
135
+ return x, y
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/petri_net.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from enum import Enum
23
+ from typing import Any, Dict, Optional, Tuple, Union
24
+
25
+ import pandas as pd
26
+
27
+ from pm4py.objects.conversion.log import converter as log_converter
28
+ from pm4py.objects.log.obj import EventLog, EventStream
29
+ from pm4py.objects.petri_net.obj import Marking, PetriNet
30
+ from pm4py.util import constants, exec_utils, xes_constants
31
+
32
+
33
+ class Parameters(Enum):
34
+ NET = "net"
35
+ PETRI_NET = "petri_net"
36
+ INITIAL_MARKING = "initial_marking"
37
+ FINAL_MARKING = "final_marking"
38
+ DISCOVER_MODEL = "discover_model"
39
+ DISCOVERY_VARIANT = "discovery_variant"
40
+ ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
41
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
42
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
43
+
44
+
45
+ def get_log_and_model(
46
+ log: Union[EventLog, EventStream, pd.DataFrame],
47
+ parameters: Optional[Dict[Any, Any]] = None,
48
+ ) -> Tuple[EventLog, PetriNet, Marking, Marking]:
49
+ """
50
+ Resolves an EventLog and Petri net for PM-based trace encodings.
51
+ """
52
+ if parameters is None:
53
+ parameters = {}
54
+
55
+ event_log = log_converter.apply(
56
+ log, variant=log_converter.Variants.TO_EVENT_LOG, parameters=parameters
57
+ )
58
+
59
+ net = exec_utils.get_param_value(Parameters.NET, parameters, None)
60
+ if net is None:
61
+ net = exec_utils.get_param_value(Parameters.PETRI_NET, parameters, None)
62
+ initial_marking = exec_utils.get_param_value(
63
+ Parameters.INITIAL_MARKING, parameters, None
64
+ )
65
+ final_marking = exec_utils.get_param_value(
66
+ Parameters.FINAL_MARKING, parameters, None
67
+ )
68
+
69
+ if net is not None and initial_marking is not None and final_marking is not None:
70
+ return event_log, net, initial_marking, final_marking
71
+
72
+ discover_model = exec_utils.get_param_value(
73
+ Parameters.DISCOVER_MODEL, parameters, True
74
+ )
75
+ if not discover_model:
76
+ raise ValueError(
77
+ "PM-based trace encodings require net, initial_marking, and "
78
+ "final_marking when discover_model is False."
79
+ )
80
+
81
+ from pm4py.algo.discovery.inductive import algorithm as inductive_miner
82
+ from pm4py.objects.conversion.process_tree import converter as pt_converter
83
+
84
+ activity_key = exec_utils.get_param_value(
85
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
86
+ )
87
+ timestamp_key = exec_utils.get_param_value(
88
+ Parameters.TIMESTAMP_KEY, parameters, xes_constants.DEFAULT_TIMESTAMP_KEY
89
+ )
90
+ case_id_key = exec_utils.get_param_value(
91
+ Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME
92
+ )
93
+ discovery_variant = exec_utils.get_param_value(
94
+ Parameters.DISCOVERY_VARIANT, parameters, inductive_miner.Variants.IM
95
+ )
96
+
97
+ discovery_parameters = dict(parameters)
98
+ discovery_parameters[Parameters.ACTIVITY_KEY] = activity_key
99
+ discovery_parameters[Parameters.TIMESTAMP_KEY] = timestamp_key
100
+ discovery_parameters[Parameters.CASE_ID_KEY] = case_id_key
101
+
102
+ process_tree = inductive_miner.apply(
103
+ event_log, parameters=discovery_parameters, variant=discovery_variant
104
+ )
105
+ net, initial_marking, final_marking = pt_converter.apply(process_tree)
106
+
107
+ return event_log, net, initial_marking, final_marking
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/similarity.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ import numpy as np
23
+ from typing import List, Union, Optional, Dict, Any
24
+ from pm4py.algo.transformation.trace_encodings.util import embed_sentence
25
+
26
+
27
+ def cosine_similarity(a, b):
28
+ return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
29
+
30
+
31
+ def apply(target_embedding: Union[str, List[float]], embeddings_list: List[List[float]], parameters: Optional[Dict[Any, Any]] = None) -> List[float]:
32
+ """
33
+ Computes the cosine similarity between the embeddings of a target sentence and a list of embeddings
34
+ (at the case or event level)
35
+
36
+ Parameters
37
+ -----------------
38
+ target_embedding
39
+ Target sentence (embeddings)
40
+ embeddings_list
41
+ List of embeddings (at the case or event level)
42
+ parameters
43
+ Parameters of the method
44
+
45
+ Returns
46
+ ------------------
47
+ similarity_list
48
+ List containing the cosine similarities between each entry and the target sentence
49
+ """
50
+ if parameters is None:
51
+ parameters = {}
52
+
53
+ if isinstance(target_embedding, str):
54
+ target_embedding = embed_sentence.apply(target_embedding, parameters=parameters)
55
+
56
+ similarity_list = [cosine_similarity(target_embedding, emb) for emb in embeddings_list]
57
+
58
+ return similarity_list
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/sklearn_vectorization.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from enum import Enum
23
+ from typing import Any, Dict, List, Optional, Tuple, Union
24
+
25
+ import pandas as pd
26
+
27
+ from pm4py.objects.log.obj import EventLog, EventStream
28
+ from pm4py.util import exec_utils
29
+ from pm4py.algo.transformation.trace_encodings.util.trace_text import (
30
+ log_to_trace_tokens,
31
+ )
32
+
33
+
34
+ class Parameters(Enum):
35
+ NGRAM_RANGE = "ngram_range"
36
+ RETURN_SPARSE = "return_sparse"
37
+ VECTORIZER = "vectorizer"
38
+ FIT_VECTORIZER = "fit_vectorizer"
39
+
40
+
41
+ def _ngrams(tokens: List[str], ngram_range: Tuple[int, int]) -> List[str]:
42
+ terms = []
43
+ min_n, max_n = ngram_range
44
+ for n in range(min_n, max_n + 1):
45
+ if n <= 0:
46
+ continue
47
+ for i in range(0, len(tokens) - n + 1):
48
+ terms.append(" >> ".join(tokens[i : i + n]))
49
+ return terms
50
+
51
+
52
+ def apply(
53
+ log: Union[EventLog, EventStream, pd.DataFrame],
54
+ binary: bool = False,
55
+ ngram_range: Tuple[int, int] = (1, 1),
56
+ parameters: Optional[Dict[Any, Any]] = None,
57
+ ):
58
+ """
59
+ Vectorizes trace token sequences through scikit-learn CountVectorizer.
60
+ """
61
+ if parameters is None:
62
+ parameters = {}
63
+
64
+ return_sparse = exec_utils.get_param_value(
65
+ Parameters.RETURN_SPARSE, parameters, False
66
+ )
67
+ vectorizer = exec_utils.get_param_value(
68
+ Parameters.VECTORIZER, parameters, None
69
+ )
70
+ fit_vectorizer = exec_utils.get_param_value(
71
+ Parameters.FIT_VECTORIZER, parameters, True
72
+ )
73
+ ngram_range = exec_utils.get_param_value(
74
+ Parameters.NGRAM_RANGE, parameters, ngram_range
75
+ )
76
+
77
+ _, traces = log_to_trace_tokens(log, parameters=parameters)
78
+
79
+ if vectorizer is None:
80
+ try:
81
+ from sklearn.feature_extraction.text import CountVectorizer
82
+ except ImportError as exc:
83
+ raise ImportError(
84
+ "The selected trace encoding uses scikit-learn. Please install "
85
+ "scikit-learn to use this variant."
86
+ ) from exc
87
+
88
+ vectorizer = CountVectorizer(
89
+ analyzer=lambda tokens: _ngrams(tokens, ngram_range),
90
+ binary=binary,
91
+ lowercase=False,
92
+ )
93
+
94
+ if not traces:
95
+ return [], []
96
+
97
+ try:
98
+ if fit_vectorizer:
99
+ matrix = vectorizer.fit_transform(traces)
100
+ else:
101
+ matrix = vectorizer.transform(traces)
102
+ except ValueError as exc:
103
+ if "empty vocabulary" not in str(exc):
104
+ raise
105
+ return [[] for _ in traces], []
106
+
107
+ feature_names = list(vectorizer.get_feature_names_out())
108
+ data = matrix if return_sparse else matrix.toarray().tolist()
109
+
110
+ return data, feature_names
111
+
112
+
113
+ def apply_tfidf(
114
+ log: Union[EventLog, EventStream, pd.DataFrame],
115
+ ngram_range: Tuple[int, int] = (1, 1),
116
+ parameters: Optional[Dict[Any, Any]] = None,
117
+ ):
118
+ """
119
+ Vectorizes trace token sequences through scikit-learn TfidfVectorizer.
120
+ """
121
+ if parameters is None:
122
+ parameters = {}
123
+
124
+ return_sparse = exec_utils.get_param_value(
125
+ Parameters.RETURN_SPARSE, parameters, False
126
+ )
127
+ vectorizer = exec_utils.get_param_value(
128
+ Parameters.VECTORIZER, parameters, None
129
+ )
130
+ fit_vectorizer = exec_utils.get_param_value(
131
+ Parameters.FIT_VECTORIZER, parameters, True
132
+ )
133
+ ngram_range = exec_utils.get_param_value(
134
+ Parameters.NGRAM_RANGE, parameters, ngram_range
135
+ )
136
+
137
+ _, traces = log_to_trace_tokens(log, parameters=parameters)
138
+
139
+ if vectorizer is None:
140
+ try:
141
+ from sklearn.feature_extraction.text import TfidfVectorizer
142
+ except ImportError as exc:
143
+ raise ImportError(
144
+ "The selected trace encoding uses scikit-learn. Please install "
145
+ "scikit-learn to use this variant."
146
+ ) from exc
147
+
148
+ vectorizer = TfidfVectorizer(
149
+ analyzer=lambda tokens: _ngrams(tokens, ngram_range),
150
+ lowercase=False,
151
+ )
152
+
153
+ if not traces:
154
+ return [], []
155
+
156
+ try:
157
+ if fit_vectorizer:
158
+ matrix = vectorizer.fit_transform(traces)
159
+ else:
160
+ matrix = vectorizer.transform(traces)
161
+ except ValueError as exc:
162
+ if "empty vocabulary" not in str(exc):
163
+ raise
164
+ return [[] for _ in traces], []
165
+
166
+ feature_names = list(vectorizer.get_feature_names_out())
167
+ data = matrix if return_sparse else matrix.toarray().tolist()
168
+
169
+ return data, feature_names
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/util/trace_text.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from enum import Enum
23
+ from typing import Any, Dict, List, Optional, Tuple, Union
24
+
25
+ import pandas as pd
26
+
27
+ from pm4py.objects.conversion.log import converter as log_converter
28
+ from pm4py.objects.log.obj import EventLog, EventStream, Trace, Event
29
+ from pm4py.util import constants, exec_utils, xes_constants
30
+
31
+
32
+ class Parameters(Enum):
33
+ ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
34
+ ATTRIBUTE_KEY = constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY
35
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
36
+ EVENT_ATTRIBUTES = "event_attributes"
37
+ TRACE_ATTRIBUTES = "trace_attributes"
38
+ INCLUDE_ATTRIBUTE_NAMES = "include_attribute_names"
39
+ COMBINE_EVENT_ATTRIBUTES = "combine_event_attributes"
40
+ MISSING_VALUE = "missing_value"
41
+
42
+
43
+ def get_event_attributes(
44
+ parameters: Optional[Dict[Any, Any]] = None,
45
+ ) -> List[str]:
46
+ """
47
+ Gets the event attributes used to build each event token.
48
+ """
49
+ if parameters is None:
50
+ parameters = {}
51
+
52
+ activity_key = exec_utils.get_param_value(
53
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
54
+ )
55
+ attribute_key = exec_utils.get_param_value(
56
+ Parameters.ATTRIBUTE_KEY, parameters, activity_key
57
+ )
58
+ event_attributes = exec_utils.get_param_value(
59
+ Parameters.EVENT_ATTRIBUTES, parameters, None
60
+ )
61
+
62
+ if event_attributes is None:
63
+ event_attributes = [attribute_key]
64
+ elif isinstance(event_attributes, str):
65
+ event_attributes = [event_attributes]
66
+ else:
67
+ event_attributes = list(event_attributes)
68
+
69
+ return event_attributes
70
+
71
+
72
+ def get_trace_attributes(
73
+ parameters: Optional[Dict[Any, Any]] = None,
74
+ ) -> List[str]:
75
+ """
76
+ Gets trace-level attributes to add as case context tokens.
77
+ """
78
+ if parameters is None:
79
+ parameters = {}
80
+
81
+ trace_attributes = exec_utils.get_param_value(
82
+ Parameters.TRACE_ATTRIBUTES, parameters, []
83
+ )
84
+ if isinstance(trace_attributes, str):
85
+ trace_attributes = [trace_attributes]
86
+
87
+ return list(trace_attributes)
88
+
89
+
90
+ def format_event_tokens(
91
+ event: Event,
92
+ event_attributes: List[str],
93
+ parameters: Optional[Dict[Any, Any]] = None,
94
+ ) -> List[str]:
95
+ """
96
+ Formats one event as one or more textual tokens.
97
+ """
98
+ if parameters is None:
99
+ parameters = {}
100
+
101
+ include_attribute_names = exec_utils.get_param_value(
102
+ Parameters.INCLUDE_ATTRIBUTE_NAMES, parameters, len(event_attributes) > 1
103
+ )
104
+ combine_event_attributes = exec_utils.get_param_value(
105
+ Parameters.COMBINE_EVENT_ATTRIBUTES, parameters, True
106
+ )
107
+ missing_value = exec_utils.get_param_value(
108
+ Parameters.MISSING_VALUE, parameters, "UNDEFINED"
109
+ )
110
+
111
+ tokens = []
112
+ for attr in event_attributes:
113
+ value = event[attr] if attr in event else missing_value
114
+ if include_attribute_names:
115
+ tokens.append(str(attr) + "=" + str(value))
116
+ else:
117
+ tokens.append(str(value))
118
+
119
+ if combine_event_attributes:
120
+ return ["|".join(tokens)]
121
+ return tokens
122
+
123
+
124
+ def trace_to_tokens(
125
+ trace: Trace,
126
+ parameters: Optional[Dict[Any, Any]] = None,
127
+ ) -> List[str]:
128
+ """
129
+ Converts a trace to a sequence of tokens.
130
+ """
131
+ if parameters is None:
132
+ parameters = {}
133
+
134
+ event_attributes = get_event_attributes(parameters)
135
+ trace_attributes = get_trace_attributes(parameters)
136
+ missing_value = exec_utils.get_param_value(
137
+ Parameters.MISSING_VALUE, parameters, "UNDEFINED"
138
+ )
139
+
140
+ tokens = []
141
+ for attr in trace_attributes:
142
+ if attr in trace.attributes:
143
+ value = trace.attributes[attr]
144
+ elif attr.startswith(constants.CASE_ATTRIBUTE_PREFIX) and attr[
145
+ len(constants.CASE_ATTRIBUTE_PREFIX) :
146
+ ] in trace.attributes:
147
+ value = trace.attributes[
148
+ attr[len(constants.CASE_ATTRIBUTE_PREFIX) :]
149
+ ]
150
+ else:
151
+ value = missing_value
152
+ tokens.append("trace:" + str(attr) + "=" + str(value))
153
+
154
+ for event in trace:
155
+ tokens.extend(format_event_tokens(event, event_attributes, parameters))
156
+
157
+ return tokens
158
+
159
+
160
+ def log_to_trace_tokens(
161
+ log: Union[EventLog, EventStream, pd.DataFrame],
162
+ parameters: Optional[Dict[Any, Any]] = None,
163
+ ) -> Tuple[List[Any], List[List[str]]]:
164
+ """
165
+ Converts a log to case identifiers and trace token sequences.
166
+ """
167
+ if parameters is None:
168
+ parameters = {}
169
+
170
+ case_id_key = exec_utils.get_param_value(
171
+ Parameters.CASE_ID_KEY, parameters, xes_constants.DEFAULT_TRACEID_KEY
172
+ )
173
+
174
+ log = log_converter.apply(
175
+ log, variant=log_converter.Variants.TO_EVENT_LOG, parameters=parameters
176
+ )
177
+
178
+ case_ids = []
179
+ trace_tokens = []
180
+ for index, trace in enumerate(log):
181
+ case_id = trace.attributes.get(case_id_key, None)
182
+ if case_id is None and str(case_id_key).startswith(
183
+ constants.CASE_ATTRIBUTE_PREFIX
184
+ ):
185
+ case_id = trace.attributes.get(
186
+ str(case_id_key)[len(constants.CASE_ATTRIBUTE_PREFIX) :],
187
+ None,
188
+ )
189
+ if case_id is None:
190
+ case_id = trace.attributes.get(xes_constants.DEFAULT_TRACEID_KEY, index)
191
+ case_ids.append(case_id)
192
+ trace_tokens.append(trace_to_tokens(trace, parameters=parameters))
193
+
194
+ return case_ids, trace_tokens
195
+
196
+
197
+ def tokens_to_sentence(tokens: List[str]) -> str:
198
+ """
199
+ Converts trace tokens to a sentence consumed by text embedding models.
200
+ """
201
+ return " ".join(tokens)
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/__init__.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.algo.transformation.trace_encodings.variants import (
23
+ alignments,
24
+ bert,
25
+ cases_transformers,
26
+ count2vec,
27
+ doc2vec,
28
+ event_based,
29
+ events_transformers,
30
+ n_grams,
31
+ one_hot,
32
+ temporal,
33
+ temporal_lazy,
34
+ tf_idf,
35
+ token_replay,
36
+ trace_based,
37
+ word2vec,
38
+ )
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/alignments.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ """
23
+ Alignment-based trace encoding.
24
+
25
+ From an event-log point of view, each trace is aligned with a Petri net. The
26
+ alignment finds a least-cost explanation of how the trace can be matched to
27
+ the model through synchronous moves, log moves, and model moves. The
28
+ alignment diagnostics become the trace vector: is-fit, fitness, cost,
29
+ best-worst cost, visited states, queued states, and traversed arcs.
30
+
31
+ Example with a model A -> B -> C:
32
+ case 1: A, B, C
33
+ case 2: A, C
34
+
35
+ case 1 aligns synchronously with the model and receives zero alignment cost.
36
+ case 2 needs a model move for B or a related deviation, so its cost is
37
+ greater than zero and its fitness is lower.
38
+
39
+ The Petri net can be passed with net, initial_marking, and final_marking. If
40
+ no model is passed, the variant discovers one from the log using PM4Py's
41
+ Inductive Miner.
42
+
43
+ Reference:
44
+ Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
45
+ "Trace encoding in process mining: A survey and benchmarking."
46
+ Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
47
+ https://doi.org/10.1016/j.engappai.2023.107028
48
+
49
+ The survey lists alignments as a PM-based encoding and points to PM4Py as the
50
+ maintained implementation. This variant delegates alignment computation to
51
+ PM4Py's Petri-net alignments and exposes per-trace diagnostics as vectors.
52
+ """
53
+
54
+ from enum import Enum
55
+ from typing import Any, Dict, Optional, Union
56
+
57
+ import pandas as pd
58
+
59
+ from pm4py.objects.log.obj import EventLog, EventStream
60
+ from pm4py.algo.transformation.trace_encodings.util import petri_net
61
+
62
+
63
+ class Parameters(Enum):
64
+ NET = "net"
65
+ PETRI_NET = "petri_net"
66
+ INITIAL_MARKING = "initial_marking"
67
+ FINAL_MARKING = "final_marking"
68
+ DISCOVER_MODEL = "discover_model"
69
+ ALIGNMENT_VARIANT = "alignment_variant"
70
+
71
+
72
+ FEATURE_NAMES = [
73
+ "@@alignment_is_fit",
74
+ "@@alignment_fitness",
75
+ "@@alignment_cost",
76
+ "@@alignment_bwc",
77
+ "@@alignment_visited_states",
78
+ "@@alignment_queued_states",
79
+ "@@alignment_traversed_arcs",
80
+ ]
81
+
82
+
83
+ def apply(
84
+ log: Union[EventLog, EventStream, pd.DataFrame],
85
+ parameters: Optional[Dict[Any, Any]] = None,
86
+ ):
87
+ """
88
+ Encodes each trace with alignment conformance diagnostics.
89
+
90
+ Parameters
91
+ ----------
92
+ log
93
+ Event log, event stream, or dataframe containing traces.
94
+ parameters
95
+ Parameters of the encoding. Common options:
96
+ - NET/PETRI_NET, INITIAL_MARKING, FINAL_MARKING: existing Petri net
97
+ model to align against.
98
+ - DISCOVER_MODEL: if True, discover a Petri net when no model is
99
+ supplied.
100
+ - ALIGNMENT_VARIANT: PM4Py Petri-net alignment variant.
101
+
102
+ Returns
103
+ -------
104
+ data
105
+ One row per trace with alignment diagnostics.
106
+ feature_names
107
+ Diagnostic names corresponding to the columns of data.
108
+ """
109
+ if parameters is None:
110
+ parameters = {}
111
+
112
+ from pm4py.algo.conformance.alignments.petri_net import (
113
+ algorithm as alignments,
114
+ )
115
+ from pm4py.util import exec_utils
116
+
117
+ event_log, net, initial_marking, final_marking = petri_net.get_log_and_model(
118
+ log, parameters=parameters
119
+ )
120
+ variant = exec_utils.get_param_value(
121
+ Parameters.ALIGNMENT_VARIANT,
122
+ parameters,
123
+ alignments.DEFAULT_VARIANT,
124
+ )
125
+
126
+ alignment_results = alignments.apply(
127
+ event_log,
128
+ net,
129
+ initial_marking,
130
+ final_marking,
131
+ parameters=parameters,
132
+ variant=variant,
133
+ )
134
+
135
+ data = []
136
+ for alignment in alignment_results:
137
+ if alignment is None:
138
+ data.append([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
139
+ else:
140
+ fitness = float(alignment.get("fitness", 0.0))
141
+ data.append(
142
+ [
143
+ 1.0 if fitness == 1.0 else 0.0,
144
+ fitness,
145
+ float(alignment.get("cost", 0.0)),
146
+ float(alignment.get("bwc", 0.0)),
147
+ float(alignment.get("visited_states", 0.0)),
148
+ float(alignment.get("queued_states", 0.0)),
149
+ float(alignment.get("traversed_arcs", 0.0)),
150
+ ]
151
+ )
152
+
153
+ return data, FEATURE_NAMES
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/bert.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ """
23
+ Trace-level BERT-style sentence embedding.
24
+
25
+ From an event-log point of view, each case is converted to a sentence and
26
+ then embedded by a transformer model. By default, the sentence is the
27
+ activity sequence, but additional event and trace attributes can be included
28
+ to embed a richer perspective.
29
+
30
+ Example with activity-only encoding:
31
+ case 1: A, B, C -> "A B C"
32
+ case 2: A, C -> "A C"
33
+
34
+ A BERT/sentence-transformer model maps each sentence to a dense vector. The
35
+ output has one row per trace and one column per embedding dimension.
36
+
37
+ Reference:
38
+ Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
39
+ "Trace encoding in process mining: A survey and benchmarking."
40
+ Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
41
+ https://doi.org/10.1016/j.engappai.2023.107028
42
+
43
+ This variant delegates embedding computation to sentence-transformers. The
44
+ default model name is intentionally configurable because model availability is
45
+ environment-specific.
46
+ """
47
+
48
+ from enum import Enum
49
+ from typing import Any, Dict, Optional, Union
50
+
51
+ import pandas as pd
52
+
53
+ from pm4py.objects.log.obj import EventLog, EventStream
54
+ from pm4py.algo.transformation.trace_encodings.util import trace_text
55
+ from pm4py.util import exec_utils
56
+
57
+
58
+ class Parameters(Enum):
59
+ EVENT_ATTRIBUTES = "event_attributes"
60
+ TRACE_ATTRIBUTES = "trace_attributes"
61
+ BERT_MODEL = "bert_model"
62
+ EMBEDDING_MODEL = "embedding_model"
63
+
64
+
65
+ def apply(
66
+ log: Union[EventLog, EventStream, pd.DataFrame],
67
+ parameters: Optional[Dict[Any, Any]] = None,
68
+ ):
69
+ """
70
+ Encodes each trace as a dense transformer/BERT-style sentence vector.
71
+
72
+ Parameters
73
+ ----------
74
+ log
75
+ Event log, event stream, or dataframe containing traces.
76
+ parameters
77
+ Parameters of the encoding. Common options:
78
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
79
+ the activity attribute.
80
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
81
+ - BERT_MODEL/EMBEDDING_MODEL: sentence-transformers model name or path.
82
+
83
+ Returns
84
+ -------
85
+ data
86
+ One row per trace, containing transformer embedding dimensions.
87
+ feature_names
88
+ Dimension names corresponding to the columns of data.
89
+ """
90
+ if parameters is None:
91
+ parameters = {}
92
+
93
+ try:
94
+ from sentence_transformers import SentenceTransformer
95
+ except ImportError as exc:
96
+ raise ImportError(
97
+ "The BERT trace encoding uses sentence-transformers. Please "
98
+ "install sentence-transformers to use this variant."
99
+ ) from exc
100
+
101
+ model_name = exec_utils.get_param_value(
102
+ Parameters.BERT_MODEL,
103
+ parameters,
104
+ exec_utils.get_param_value(
105
+ Parameters.EMBEDDING_MODEL, parameters, "bert-base-nli-mean-tokens"
106
+ ),
107
+ )
108
+
109
+ _, traces = trace_text.log_to_trace_tokens(log, parameters=parameters)
110
+ sentences = [trace_text.tokens_to_sentence(trace) for trace in traces]
111
+ model = SentenceTransformer(model_name)
112
+ embeddings = model.encode(sentences)
113
+ data = [embedding.tolist() for embedding in embeddings]
114
+
115
+ vector_size = len(data[0]) if data else 0
116
+ feature_names = ["@@bert_dim_" + str(i) for i in range(vector_size)]
117
+ return data, feature_names
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/cases_transformers.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.util import exec_utils, constants, xes_constants
23
+ from typing import Optional, Dict, Any, List, Tuple
24
+ from pm4py.objects.conversion.log import converter as log_converter
25
+ import pandas as pd
26
+ from enum import Enum
27
+ from pm4py.algo.transformation.trace_encodings.util import similarity
28
+ from pm4py.algo.transformation.trace_encodings.util import trace_text
29
+
30
+
31
+ class Parameters(Enum):
32
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
33
+ EMBEDDING_MODEL = "embedding_model"
34
+ ATTRIBUTE_KEY = constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY
35
+ EVENT_ATTRIBUTES = "event_attributes"
36
+ TRACE_ATTRIBUTES = "trace_attributes"
37
+
38
+
39
+ def apply(log: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None) -> Tuple[List[str], List[List[float]]]:
40
+ """
41
+ Computes one text embedding per case.
42
+
43
+ From an event-log point of view, each trace is converted to a sentence and
44
+ then embedded by a sentence-transformers model. By default, the sentence is
45
+ the sequence of activity names. Additional event attributes and trace
46
+ attributes can be included to represent a richer perspective.
47
+
48
+ Example with activity-only encoding:
49
+ case 1: A, B, C -> "A B C"
50
+ case 2: A, C -> "A C"
51
+
52
+ Example with event_attributes=["concept:name", "org:resource"]:
53
+ event A by R1 becomes "concept:name=A|org:resource=R1"
54
+
55
+ The output is a list of case identifiers and a list of dense embedding
56
+ vectors, one vector per case.
57
+
58
+ Parameters
59
+ -----------------
60
+ log
61
+ Pandas dataframe
62
+ parameters
63
+ Parameters of the algorithm, including:
64
+ - Parameters.CASE_ID_KEY => the case identifier column
65
+ - Parameters.EMBEDDING_MODEL => the embedding to be used (default: all-MiniLM-L6-v2)
66
+ - Parameters.ATTRIBUTE_KEY => the attribute to be used for the concatenation
67
+ - Parameters.EVENT_ATTRIBUTES => event attributes to include in the case sentence. If omitted, ATTRIBUTE_KEY is used.
68
+ - Parameters.TRACE_ATTRIBUTES => trace attributes to include as case context tokens.
69
+
70
+ Returns
71
+ ----------------
72
+ cases_identifiers
73
+ The list of all the case identifiers
74
+ embeddings_list
75
+ The list of embeddings for the considered cases
76
+ """
77
+ if parameters is None:
78
+ parameters = {}
79
+
80
+ case_id_key = exec_utils.get_param_value(Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME)
81
+ attribute_key = exec_utils.get_param_value(Parameters.ATTRIBUTE_KEY, parameters, xes_constants.DEFAULT_NAME_KEY)
82
+ embedding_model = exec_utils.get_param_value(Parameters.EMBEDDING_MODEL, parameters,
83
+ constants.DEFAULT_EMBEDDING_MODEL)
84
+
85
+ cases_identifiers = []
86
+ sentences = []
87
+
88
+ from sentence_transformers import SentenceTransformer
89
+ model = SentenceTransformer(embedding_model)
90
+
91
+ event_attributes = exec_utils.get_param_value(
92
+ Parameters.EVENT_ATTRIBUTES, parameters, None
93
+ )
94
+ trace_attributes = exec_utils.get_param_value(
95
+ Parameters.TRACE_ATTRIBUTES, parameters, []
96
+ )
97
+
98
+ if event_attributes is not None or trace_attributes:
99
+ cases_identifiers, traces = trace_text.log_to_trace_tokens(
100
+ log, parameters=parameters
101
+ )
102
+ sentences = [trace_text.tokens_to_sentence(x) for x in traces]
103
+ else:
104
+ log = log_converter.apply(log, variant=log_converter.Variants.TO_DATA_FRAME)
105
+ cases = log.groupby(case_id_key)[attribute_key].agg(list)
106
+ cases = cases.to_dict()
107
+
108
+ for k, v in cases.items():
109
+ cases_identifiers.append(k)
110
+ sentences.append(" ".join(str(x) for x in v))
111
+
112
+ embeddings_list = list(model.encode(sentences))
113
+
114
+ return cases_identifiers, embeddings_list
115
+
116
+
117
+ def keep_top_k_per_similarity(log: pd.DataFrame, target_sentence: str, k: int, cases_identifiers: Optional[List[str]] = None, embeddings_list: Optional[List[List[float]]] = None, parameters: Optional[Dict[Any, Any]] = None) -> pd.DataFrame:
118
+ """
119
+ Keeps the top K cases by embedding similarity with the given sentence.
120
+
121
+ For example, after encoding cases as activity sentences, the query
122
+ "rejected cases" is embedded with the same model and compared with each
123
+ case embedding using cosine similarity.
124
+
125
+ Parameters
126
+ ----------------
127
+ log
128
+ Pandas dataframe
129
+ target_sentence
130
+ Target sentence
131
+ k
132
+ Number of similar cases to retain
133
+ cases_identifiers
134
+ (Optional) the list of cases identifiers in the log, as returned by the 'apply' method
135
+ embeddings_list
136
+ (Optional) the list of embeddings for such cases, as returned by the 'apply' method
137
+ parameters
138
+ Other parameters of the method
139
+
140
+ Returns
141
+ -----------------
142
+ filtered_log
143
+ Event log filtered on the top K cases according to the similarity metric.
144
+ """
145
+ if parameters is None:
146
+ parameters = {}
147
+
148
+ case_id_key = exec_utils.get_param_value(Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME)
149
+
150
+ if cases_identifiers is None or embeddings_list is None:
151
+ cases_identifiers, embeddings_list = apply(log, parameters=parameters)
152
+
153
+ sim = similarity.apply(target_sentence, embeddings_list)
154
+ cases = [(cases_identifiers[i], sim[i]) for i in range(len(cases_identifiers))]
155
+ cases.sort(key=lambda x: (x[1], x[0]), reverse=True)
156
+ cases = cases[:k]
157
+ cases = [x[0] for x in cases]
158
+
159
+ log = log[log[case_id_key].isin(cases)]
160
+
161
+ return log
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/count2vec.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ """
23
+ Trace-level count2vec encoding.
24
+
25
+ From an event-log point of view, each case is read as a sequence of tokens.
26
+ By default, the token of an event is its activity name. The output has one
27
+ row per trace and one column per token; the cell is the number of times the
28
+ token appears in that trace.
29
+
30
+ Example with the activity attribute:
31
+ case 1: A, B, A
32
+ case 2: A, C
33
+
34
+ The vocabulary is [A, B, C], and the encoded matrix is:
35
+ case 1 -> [2, 1, 0]
36
+ case 2 -> [1, 0, 1]
37
+
38
+ If event_attributes includes additional columns, each event token can include
39
+ context such as activity, resource, and amount before counts are computed.
40
+
41
+ Reference:
42
+ Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
43
+ "Trace encoding in process mining: A survey and benchmarking."
44
+ Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
45
+ https://doi.org/10.1016/j.engappai.2023.107028
46
+
47
+ The survey lists count2vec as a baseline encoding and uses sklearn as the
48
+ open-source implementation source. This variant uses scikit-learn's
49
+ CountVectorizer over trace tokens.
50
+ """
51
+
52
+ from enum import Enum
53
+ from typing import Any, Dict, Optional, Union
54
+
55
+ import pandas as pd
56
+
57
+ from pm4py.objects.log.obj import EventLog, EventStream
58
+ from pm4py.algo.transformation.trace_encodings.util import sklearn_vectorization
59
+
60
+
61
+ class Parameters(Enum):
62
+ EVENT_ATTRIBUTES = "event_attributes"
63
+ TRACE_ATTRIBUTES = "trace_attributes"
64
+ RETURN_SPARSE = "return_sparse"
65
+ VECTORIZER = "vectorizer"
66
+ FIT_VECTORIZER = "fit_vectorizer"
67
+
68
+
69
+ def apply(
70
+ log: Union[EventLog, EventStream, pd.DataFrame],
71
+ parameters: Optional[Dict[Any, Any]] = None,
72
+ ):
73
+ """
74
+ Encodes each trace as token frequency counts.
75
+
76
+ Parameters
77
+ ----------
78
+ log
79
+ Event log, event stream, or dataframe containing traces.
80
+ parameters
81
+ Parameters of the encoding. Common options:
82
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
83
+ the activity attribute.
84
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
85
+ - RETURN_SPARSE: if True, returns the sklearn sparse matrix.
86
+
87
+ Returns
88
+ -------
89
+ data
90
+ One row per trace, one count per discovered token.
91
+ feature_names
92
+ Token names corresponding to the columns of data.
93
+ """
94
+ return sklearn_vectorization.apply(
95
+ log, binary=False, ngram_range=(1, 1), parameters=parameters
96
+ )
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/doc2vec.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ """
23
+ Trace-level Doc2Vec encoding.
24
+
25
+ From an event-log point of view, each case is treated as one document and
26
+ each event token is treated as one word in that document. A Doc2Vec model
27
+ learns a dense vector directly for each trace/document.
28
+
29
+ Example with activity tokens:
30
+ case 1: A, B, C
31
+ case 2: A, B, D
32
+
33
+ Doc2Vec learns one vector for "A B C" and one vector for "A B D". Unlike
34
+ Word2Vec, no explicit mean over event-token vectors is needed because the
35
+ document vector is trained directly.
36
+
37
+ Reference:
38
+ Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
39
+ "Trace encoding in process mining: A survey and benchmarking."
40
+ Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
41
+ https://doi.org/10.1016/j.engappai.2023.107028
42
+
43
+ This variant delegates model training/inference to gensim's maintained
44
+ Doc2Vec implementation.
45
+ """
46
+
47
+ from enum import Enum
48
+ from typing import Any, Dict, Optional, Union
49
+
50
+ import pandas as pd
51
+
52
+ from pm4py.objects.log.obj import EventLog, EventStream
53
+ from pm4py.algo.transformation.trace_encodings.util import trace_text
54
+ from pm4py.util import exec_utils
55
+
56
+
57
+ class Parameters(Enum):
58
+ EVENT_ATTRIBUTES = "event_attributes"
59
+ TRACE_ATTRIBUTES = "trace_attributes"
60
+ MODEL = "model"
61
+ VECTOR_SIZE = "vector_size"
62
+ WINDOW = "window"
63
+ MIN_COUNT = "min_count"
64
+ WORKERS = "workers"
65
+ EPOCHS = "epochs"
66
+ DM = "dm"
67
+
68
+
69
+ def apply(
70
+ log: Union[EventLog, EventStream, pd.DataFrame],
71
+ parameters: Optional[Dict[Any, Any]] = None,
72
+ ):
73
+ """
74
+ Encodes each trace as a gensim Doc2Vec document vector.
75
+
76
+ Parameters
77
+ ----------
78
+ log
79
+ Event log, event stream, or dataframe containing traces.
80
+ parameters
81
+ Parameters of the encoding. Common options:
82
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
83
+ the activity attribute.
84
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
85
+ - MODEL: pre-trained gensim Doc2Vec model. If omitted, a model is
86
+ trained on the provided log.
87
+ - VECTOR_SIZE, WINDOW, MIN_COUNT, WORKERS, EPOCHS, DM: gensim Doc2Vec
88
+ training parameters.
89
+
90
+ Returns
91
+ -------
92
+ data
93
+ One row per trace, containing Doc2Vec dimensions.
94
+ feature_names
95
+ Dimension names corresponding to the columns of data.
96
+ """
97
+ if parameters is None:
98
+ parameters = {}
99
+
100
+ try:
101
+ from gensim.models.doc2vec import Doc2Vec, TaggedDocument
102
+ except ImportError as exc:
103
+ raise ImportError(
104
+ "The DOC2VEC trace encoding uses gensim. Please install gensim "
105
+ "to use this variant."
106
+ ) from exc
107
+
108
+ _, traces = trace_text.log_to_trace_tokens(log, parameters=parameters)
109
+ vector_size = exec_utils.get_param_value(
110
+ Parameters.VECTOR_SIZE, parameters, 100
111
+ )
112
+ epochs = exec_utils.get_param_value(Parameters.EPOCHS, parameters, 20)
113
+ model = exec_utils.get_param_value(Parameters.MODEL, parameters, None)
114
+
115
+ if model is None:
116
+ documents = [
117
+ TaggedDocument(words=trace, tags=[str(index)])
118
+ for index, trace in enumerate(traces)
119
+ ]
120
+ model = Doc2Vec(
121
+ documents=documents,
122
+ vector_size=vector_size,
123
+ window=exec_utils.get_param_value(Parameters.WINDOW, parameters, 5),
124
+ min_count=exec_utils.get_param_value(Parameters.MIN_COUNT, parameters, 1),
125
+ workers=exec_utils.get_param_value(Parameters.WORKERS, parameters, 1),
126
+ dm=exec_utils.get_param_value(Parameters.DM, parameters, 1),
127
+ epochs=epochs,
128
+ )
129
+ data = [model.dv[str(index)].tolist() for index in range(len(traces))]
130
+ else:
131
+ vector_size = int(model.vector_size)
132
+ data = [
133
+ model.infer_vector(trace, epochs=epochs).tolist()
134
+ for trace in traces
135
+ ]
136
+
137
+ feature_names = ["@@doc2vec_dim_" + str(i) for i in range(vector_size)]
138
+ return data, feature_names
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/event_based.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from collections import Counter
23
+ from enum import Enum
24
+ from typing import Optional, List, Dict, Any, Tuple, Union
25
+
26
+ import numpy as np
27
+
28
+ from pm4py.objects.log.obj import EventLog
29
+ from pm4py.util import exec_utils
30
+ from pm4py.objects.conversion.log import converter
31
+
32
+
33
+ class Parameters(Enum):
34
+ STR_EVENT_ATTRIBUTES = "str_ev_attr"
35
+ NUM_EVENT_ATTRIBUTES = "num_ev_attr"
36
+ FEATURE_NAMES = "feature_names"
37
+ MIN_NUM_DIFF_STR_VALUES = "min_num_diff_str_values"
38
+ MAX_NUM_DIFF_STR_VALUES = "max_num_diff_str_values"
39
+
40
+
41
+ def extract_all_ev_features_names_from_log(
42
+ log: EventLog,
43
+ str_ev_attr: List[str],
44
+ num_ev_attr: List[str],
45
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
46
+ ) -> List[str]:
47
+ """
48
+ Extracts the feature names from an event log.
49
+
50
+ Parameters
51
+ ---------------
52
+ log
53
+ Event log
54
+ str_ev_attr
55
+ (if provided) list of string event attributes to consider in extracting the feature names
56
+ num_ev_attr
57
+ (if provided) list of integer event attributes to consider in extracting the feature names
58
+ parameters
59
+ Parameters, including:
60
+ - MIN_NUM_DIFF_STR_VALUES => minimum number of distinct values to include an attribute as feature(s)
61
+ - MAX_NUM_DIFF_STR_VALUES => maximum number of distinct values to include an attribute as feature(s)
62
+
63
+ Returns
64
+ ----------------
65
+ feature_names
66
+ List of feature names
67
+ """
68
+ if parameters is None:
69
+ parameters = {}
70
+
71
+ min_num_diff_str_values = exec_utils.get_param_value(
72
+ Parameters.MIN_NUM_DIFF_STR_VALUES, parameters, 2
73
+ )
74
+ max_num_diff_str_values = exec_utils.get_param_value(
75
+ Parameters.MAX_NUM_DIFF_STR_VALUES, parameters, 500
76
+ )
77
+
78
+ str_features = {}
79
+ num_features = Counter()
80
+ count_events = 0
81
+ for trace in log:
82
+ for event in trace:
83
+ count_events += 1
84
+ for attr_name in event:
85
+ attr_value = event[attr_name]
86
+ if isinstance(attr_value, str) and (
87
+ str_ev_attr is None or attr_name in str_ev_attr
88
+ ):
89
+ if attr_name not in str_features:
90
+ str_features[attr_name] = set()
91
+ str_features[attr_name].add(
92
+ "event:" + attr_name + "@" + attr_value
93
+ )
94
+ elif isinstance(attr_value, int) or isinstance(
95
+ attr_value, float
96
+ ):
97
+ if num_ev_attr is None or attr_name in num_ev_attr:
98
+ num_features["event:" + attr_name] += 1
99
+ num_features = list(
100
+ {x for x, y in num_features.items() if y == count_events}
101
+ )
102
+ str_features = list(
103
+ {
104
+ z
105
+ for x, y in str_features.items()
106
+ for z in y
107
+ if min_num_diff_str_values <= len(y) <= max_num_diff_str_values
108
+ }
109
+ )
110
+
111
+ feature_names = str_features + num_features
112
+ feature_names = sorted(feature_names)
113
+
114
+ return feature_names
115
+
116
+
117
+ def extract_features(
118
+ log: EventLog,
119
+ feature_names: List[str],
120
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
121
+ ) -> Tuple[Any, List[str]]:
122
+ """
123
+ Extracts the matrix of the features from an event log
124
+
125
+ Parameters
126
+ ---------------
127
+ log
128
+ Event log
129
+ feature_names
130
+ Features to consider (in the given order)
131
+
132
+ Returns
133
+ -------------
134
+ data
135
+ Data to provide for decision tree learning
136
+ feature_names
137
+ Names of the features, in order
138
+ """
139
+ v1 = max(len(trace) for trace in log)
140
+ v2 = len(feature_names)
141
+ data = np.zeros((len(log), v1, v2), dtype=np.float32)
142
+
143
+ for i1, trace in enumerate(log):
144
+ for i2, event in enumerate(trace):
145
+ str_features = set()
146
+ num_features = {}
147
+ for attr_name in event:
148
+ attr_value = event[attr_name]
149
+ if isinstance(attr_value, str):
150
+ str_features.add("event:" + attr_name + "@" + attr_value)
151
+ elif isinstance(attr_value, int) or isinstance(
152
+ attr_value, float
153
+ ):
154
+ num_features["event:" + attr_name] = float(attr_value)
155
+ for attr in str_features:
156
+ if attr in feature_names:
157
+ data[i1, i2, feature_names.index(attr)] = 1.0
158
+ for attr in num_features:
159
+ if attr in feature_names:
160
+ data[i1, i2, feature_names.index(attr)] = float(
161
+ num_features[attr]
162
+ )
163
+
164
+ return data, feature_names
165
+
166
+
167
+ def apply(
168
+ log: EventLog,
169
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
170
+ ) -> Tuple[Any, List[str]]:
171
+ """
172
+ Encodes each event in each trace as a feature vector.
173
+
174
+ From an event-log point of view, the result keeps the trace/event grid:
175
+ each trace becomes a sequence of event vectors, padded to the maximum trace
176
+ length in the log. String event attributes are one-hot encoded; numeric
177
+ event attributes are copied as numeric values.
178
+
179
+ Example with event attribute "concept:name":
180
+ case 1: A, B
181
+ case 2: A
182
+
183
+ The vocabulary is [event:concept:name@A, event:concept:name@B]. If the
184
+ maximum trace length is 2, the encoded tensor is:
185
+ case 1 -> [[1, 0], [0, 1]]
186
+ case 2 -> [[1, 0], [0, 0]]
187
+
188
+ Parameters
189
+ -----------------
190
+ log
191
+ Event log
192
+ parameters
193
+ Parameters of the algorithm, including:
194
+ - STR_EVENT_ATTRIBUTES => string event attributes to consider in the features extraction
195
+ - NUM_EVENT_ATTRIBUTES => numeric event attributes to consider in the features extraction
196
+ - FEATURE_NAMES => features to consider (in the given order)
197
+
198
+ Returns
199
+ -------------
200
+ data
201
+ Data to provide for decision tree learning
202
+ feature_names
203
+ Names of the features, in order
204
+ """
205
+ if parameters is None:
206
+ parameters = {}
207
+
208
+ str_ev_attr = exec_utils.get_param_value(
209
+ Parameters.STR_EVENT_ATTRIBUTES, parameters, None
210
+ )
211
+ num_ev_attr = exec_utils.get_param_value(
212
+ Parameters.NUM_EVENT_ATTRIBUTES, parameters, None
213
+ )
214
+ feature_names = exec_utils.get_param_value(
215
+ Parameters.FEATURE_NAMES, parameters, None
216
+ )
217
+
218
+ log = converter.apply(
219
+ log, variant=converter.Variants.TO_EVENT_LOG, parameters=parameters
220
+ )
221
+
222
+ if feature_names is None:
223
+ feature_names = extract_all_ev_features_names_from_log(
224
+ log, str_ev_attr, num_ev_attr, parameters=parameters
225
+ )
226
+
227
+ return extract_features(log, feature_names, parameters=parameters)
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/events_transformers.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.util import exec_utils, constants, xes_constants
23
+ from typing import Optional, Dict, Any, List, Tuple
24
+ from pm4py.objects.conversion.log import converter as log_converter
25
+ import pandas as pd
26
+ from enum import Enum
27
+ from pm4py.algo.transformation.trace_encodings.util import similarity
28
+ from pm4py.algo.transformation.trace_encodings.util import trace_text
29
+
30
+
31
+ class Parameters(Enum):
32
+ EVENT_ID_KEY = "event_id_key"
33
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
34
+ EMBEDDING_MODEL = "embedding_model"
35
+ ATTRIBUTE_KEY = constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY
36
+ EVENT_ATTRIBUTES = "event_attributes"
37
+ KEEP_CASES = "keep_cases"
38
+
39
+
40
+ def apply(log: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None) -> Tuple[List[str], List[List[float]]]:
41
+ """
42
+ Computes one text embedding per event.
43
+
44
+ From an event-log point of view, each event is converted to a short
45
+ sentence and then embedded by a sentence-transformers model. By default,
46
+ the sentence is the activity name. Additional event attributes can be
47
+ included to represent a richer event perspective.
48
+
49
+ Example with activity-only encoding:
50
+ event {concept:name: "A"} -> "A"
51
+
52
+ Example with event_attributes=["concept:name", "org:resource"]:
53
+ event {concept:name: "A", org:resource: "R1"}
54
+ -> "concept:name=A|org:resource=R1"
55
+
56
+ The output is a list of event identifiers and a list of dense embedding
57
+ vectors, one vector per event.
58
+
59
+ Parameters
60
+ -----------------
61
+ log
62
+ Pandas dataframe
63
+ Parameters
64
+ Parameters of the algorithm, including:
65
+ - Parameters.EVENT_ID_KEY => an attribute unique per event
66
+ - Parameters.EMBEDDING_MODEL => the embedding to be used (default: all-MiniLM-L6-v2)
67
+ - Parameters.ATTRIBUTE_KEY => the attribute to be used
68
+ - Parameters.EVENT_ATTRIBUTES => event attributes to include in the event sentence. If omitted, ATTRIBUTE_KEY is used.
69
+
70
+ Returns
71
+ ----------------
72
+ event_identifiers
73
+ The list of all the event identifiers
74
+ embeddings_list
75
+ The list of embeddings for the considered events
76
+ """
77
+ if parameters is None:
78
+ parameters = {}
79
+
80
+ event_id_key = exec_utils.get_param_value(Parameters.EVENT_ID_KEY, parameters, constants.DEFAULT_INDEX_KEY)
81
+ attribute_key = exec_utils.get_param_value(Parameters.ATTRIBUTE_KEY, parameters, xes_constants.DEFAULT_NAME_KEY)
82
+ embedding_model = exec_utils.get_param_value(Parameters.EMBEDDING_MODEL, parameters,
83
+ constants.DEFAULT_EMBEDDING_MODEL)
84
+ event_attributes = exec_utils.get_param_value(
85
+ Parameters.EVENT_ATTRIBUTES, parameters, None
86
+ )
87
+ if event_attributes is None:
88
+ event_attributes = [attribute_key]
89
+ elif isinstance(event_attributes, str):
90
+ event_attributes = [event_attributes]
91
+ else:
92
+ event_attributes = list(event_attributes)
93
+
94
+ log = log_converter.apply(log, variant=log_converter.Variants.TO_DATA_FRAME)
95
+
96
+ event_identifiers = []
97
+ sentences = []
98
+
99
+ from sentence_transformers import SentenceTransformer
100
+ model = SentenceTransformer(embedding_model)
101
+
102
+ log = log[[event_id_key] + event_attributes].to_dict(orient="records")
103
+
104
+ for entry in log:
105
+ event_identifiers.append(entry[event_id_key])
106
+ if event_attributes == [attribute_key]:
107
+ sentences.append(str(entry[attribute_key]))
108
+ else:
109
+ tokens = trace_text.format_event_tokens(
110
+ entry, event_attributes, parameters=parameters
111
+ )
112
+ sentences.append(trace_text.tokens_to_sentence(tokens))
113
+
114
+ embeddings_list = list(model.encode(sentences))
115
+
116
+ return event_identifiers, embeddings_list
117
+
118
+
119
+ def keep_top_k_per_similarity(log: pd.DataFrame, target_sentence: str, k: int,
120
+ event_identifiers: Optional[List[str]] = None,
121
+ embeddings_list: Optional[List[List[float]]] = None,
122
+ parameters: Optional[Dict[Any, Any]] = None) -> pd.DataFrame:
123
+ """
124
+ Keeps the top K events by embedding similarity with the given sentence.
125
+
126
+ For example, after encoding events as activity/resource sentences, the
127
+ query "pay compensation" is embedded with the same model and compared with
128
+ each event embedding using cosine similarity.
129
+
130
+ Parameters
131
+ ----------------
132
+ log
133
+ Pandas dataframe
134
+ target_sentence
135
+ Target sentence
136
+ k
137
+ Number of similar events to retain
138
+ event_identifiers
139
+ (Optional) the list of event identifiers in the log, as returned by the 'apply' method
140
+ embeddings_list
141
+ (Optional) the list of embeddings for such events, as returned by the 'apply' method
142
+ parameters
143
+ Other parameters of the method:
144
+ - Parameters.KEEP_CASES => If True, keep the cases containing such events, instead of the events themselves (default: False)
145
+
146
+ Returns
147
+ -----------------
148
+ filtered_log
149
+ Event log filtered on the top K events (or cases) according to the similarity metric.
150
+ """
151
+ if parameters is None:
152
+ parameters = {}
153
+
154
+ event_id_key = exec_utils.get_param_value(Parameters.EVENT_ID_KEY, parameters, constants.DEFAULT_INDEX_KEY)
155
+ keep_cases = exec_utils.get_param_value(Parameters.KEEP_CASES, parameters, False)
156
+
157
+ if event_identifiers is None or embeddings_list is None:
158
+ event_identifiers, embeddings_list = apply(log, parameters=parameters)
159
+
160
+ sim = similarity.apply(target_sentence, embeddings_list)
161
+ events = [(event_identifiers[i], sim[i]) for i in range(len(event_identifiers))]
162
+ events.sort(key=lambda x: (x[1], x[0]), reverse=True)
163
+ events = events[:k]
164
+ events = [x[0] for x in events]
165
+
166
+ filt_log = log[log[event_id_key].isin(events)]
167
+
168
+ if keep_cases:
169
+ case_id_key = exec_utils.get_param_value(Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME)
170
+ filt_log2 = log[log[case_id_key].isin(filt_log[case_id_key])]
171
+ return filt_log2
172
+
173
+ return filt_log
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/n_grams.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ """
23
+ Trace-level n-gram encoding.
24
+
25
+ From an event-log point of view, each case is read as an ordered sequence of
26
+ tokens. By default, the token of an event is its activity name. The output
27
+ has one row per trace and one column per contiguous token pattern of length n.
28
+ The cell is the number of times that pattern appears in the trace.
29
+
30
+ Example with ngram_range=(2, 2):
31
+ case 1: A, B, A
32
+ case 2: A, C
33
+
34
+ The 2-gram vocabulary is [A >> B, A >> C, B >> A], and the encoded matrix is:
35
+ case 1 -> [1, 0, 1]
36
+ case 2 -> [0, 1, 0]
37
+
38
+ With ngram_range=(1, 2), the vocabulary includes both single activities and
39
+ directly-follows pairs.
40
+
41
+ Reference:
42
+ Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
43
+ "Trace encoding in process mining: A survey and benchmarking."
44
+ Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
45
+ https://doi.org/10.1016/j.engappai.2023.107028
46
+
47
+ The survey lists n-grams as a baseline encoding and points to maintained text
48
+ tooling for implementation. This variant delegates vector construction to
49
+ scikit-learn's CountVectorizer with a trace-token n-gram analyzer.
50
+ """
51
+
52
+ from enum import Enum
53
+ from typing import Any, Dict, Optional, Union
54
+
55
+ import pandas as pd
56
+
57
+ from pm4py.objects.log.obj import EventLog, EventStream
58
+ from pm4py.algo.transformation.trace_encodings.util import sklearn_vectorization
59
+
60
+
61
+ class Parameters(Enum):
62
+ EVENT_ATTRIBUTES = "event_attributes"
63
+ TRACE_ATTRIBUTES = "trace_attributes"
64
+ NGRAM_RANGE = "ngram_range"
65
+ RETURN_SPARSE = "return_sparse"
66
+ VECTORIZER = "vectorizer"
67
+ FIT_VECTORIZER = "fit_vectorizer"
68
+
69
+
70
+ def apply(
71
+ log: Union[EventLog, EventStream, pd.DataFrame],
72
+ parameters: Optional[Dict[Any, Any]] = None,
73
+ ):
74
+ """
75
+ Encodes each trace as frequency counts of contiguous token n-grams.
76
+
77
+ Parameters
78
+ ----------
79
+ log
80
+ Event log, event stream, or dataframe containing traces.
81
+ parameters
82
+ Parameters of the encoding. Common options:
83
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
84
+ the activity attribute.
85
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
86
+ - NGRAM_RANGE: tuple such as (2, 2) or (1, 3).
87
+ - RETURN_SPARSE: if True, returns the sklearn sparse matrix.
88
+
89
+ Returns
90
+ -------
91
+ data
92
+ One row per trace, one count per discovered n-gram.
93
+ feature_names
94
+ N-gram names corresponding to the columns of data.
95
+ """
96
+ return sklearn_vectorization.apply(
97
+ log, binary=False, ngram_range=(2, 2), parameters=parameters
98
+ )
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/one_hot.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ """
23
+ Trace-level one-hot occurrence encoding.
24
+
25
+ From an event-log point of view, each case is read as a sequence of tokens.
26
+ By default, the token of an event is its activity name. The output has one
27
+ row per trace and one column per token; the cell is 1.0 when the trace
28
+ contains the token at least once and 0.0 otherwise.
29
+
30
+ Example with the activity attribute:
31
+ case 1: A, B, A
32
+ case 2: A, C
33
+
34
+ The vocabulary is [A, B, C], and the encoded matrix is:
35
+ case 1 -> [1, 1, 0]
36
+ case 2 -> [1, 0, 1]
37
+
38
+ If event_attributes=["concept:name", "org:resource"], the event token can
39
+ include both the activity and resource, e.g. "concept:name=A|org:resource=R1".
40
+
41
+ Reference:
42
+ Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
43
+ "Trace encoding in process mining: A survey and benchmarking."
44
+ Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
45
+ https://doi.org/10.1016/j.engappai.2023.107028
46
+
47
+ The survey lists one-hot as a baseline encoding and uses sklearn as the
48
+ open-source implementation source. This variant uses scikit-learn's
49
+ CountVectorizer with binary counts over trace tokens.
50
+ """
51
+
52
+ from enum import Enum
53
+ from typing import Any, Dict, Optional, Union
54
+
55
+ import pandas as pd
56
+
57
+ from pm4py.objects.log.obj import EventLog, EventStream
58
+ from pm4py.algo.transformation.trace_encodings.util import sklearn_vectorization
59
+
60
+
61
+ class Parameters(Enum):
62
+ EVENT_ATTRIBUTES = "event_attributes"
63
+ TRACE_ATTRIBUTES = "trace_attributes"
64
+ RETURN_SPARSE = "return_sparse"
65
+ VECTORIZER = "vectorizer"
66
+ FIT_VECTORIZER = "fit_vectorizer"
67
+
68
+
69
+ def apply(
70
+ log: Union[EventLog, EventStream, pd.DataFrame],
71
+ parameters: Optional[Dict[Any, Any]] = None,
72
+ ):
73
+ """
74
+ Encodes each trace as a binary vector of present trace tokens.
75
+
76
+ Parameters
77
+ ----------
78
+ log
79
+ Event log, event stream, or dataframe containing traces.
80
+ parameters
81
+ Parameters of the encoding. Common options:
82
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
83
+ the activity attribute.
84
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
85
+ - RETURN_SPARSE: if True, returns the sklearn sparse matrix.
86
+
87
+ Returns
88
+ -------
89
+ data
90
+ One row per trace, one binary value per discovered token.
91
+ feature_names
92
+ Token names corresponding to the columns of data.
93
+ """
94
+ return sklearn_vectorization.apply(
95
+ log, binary=True, ngram_range=(1, 1), parameters=parameters
96
+ )
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/temporal.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.objects.log.obj import EventLog, EventStream
23
+ import pandas as pd
24
+ from typing import Union, Optional, Dict, Any
25
+ from pm4py.objects.conversion.log import converter as log_converter
26
+ from enum import Enum
27
+ from pm4py.util import exec_utils, constants, xes_constants, pandas_utils
28
+
29
+
30
+ class Parameters(Enum):
31
+ ARRIVAL_RATE = "arrival_rate"
32
+ FINISH_RATE = "finish_rate"
33
+ CASE_ID_COLUMN = constants.PARAMETER_CONSTANT_CASEID_KEY
34
+ START_TIMESTAMP_COLUMN = constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY
35
+ TIMESTAMP_COLUMN = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
36
+ RESOURCE_COLUMN = constants.PARAMETER_CONSTANT_RESOURCE_KEY
37
+ ACTIVITY_COLUMN = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
38
+ GROUPER_FREQ = "grouper_freq"
39
+ SERVICE_TIME = "service_time"
40
+ WAITING_TIME = "waiting_time"
41
+ SOJOURN_TIME = "sojourn_time"
42
+ DIFF_START_END = "diff_start_end"
43
+
44
+
45
+ def apply(
46
+ log: Union[EventLog, EventStream, pd.DataFrame],
47
+ parameters: Optional[Dict[Any, Any]] = None,
48
+ ) -> pd.DataFrame:
49
+ """
50
+ Aggregates an event log into temporal windows and computes window-level
51
+ process features.
52
+
53
+ From an event-log point of view, events are grouped by a timestamp
54
+ frequency such as weekly ("W") or daily ("D"). Each output row describes
55
+ one time window, not one trace. The columns include counts and averages
56
+ such as unique resources, unique activities, number of events, average
57
+ arrival rate, average finish rate, waiting time, service time, rework
58
+ count, cases per resource, events per case, number of cases, and resources
59
+ per case.
60
+
61
+ Example with GROUPER_FREQ="D":
62
+ day 2024-01-01 has 2 cases and 5 events
63
+ day 2024-01-02 has 1 case and 2 events
64
+
65
+ The result has two rows, one for each day, with columns such as
66
+ number_of_cases=[2, 1] and num_events=[5, 2].
67
+
68
+ Implements the approach described in the paper:
69
+ Pourbafrani, Mahsa, Sebastiaan J. van Zelst, and Wil MP van der Aalst.
70
+ "Supporting automatic system dynamics model generation for simulation
71
+ in the context of process mining." International Conference on Business
72
+ Information Systems. Springer, Cham, 2020.
73
+
74
+ Parameters
75
+ ---------------
76
+ log
77
+ Event log / Event stream / Pandas dataframe
78
+ parameters
79
+ Parameters of the algorithm, including:
80
+
81
+ - Parameters.GROUPER_FREQ => the time interval to be used for the grouping (default: "W")
82
+ - Parameters.ARRIVAL_RATE => column of the dataframe which is going to host the arrival rate
83
+ - Parameters.FINISH_RATE => column of the dataframe which is going to host the finishing rate
84
+ - Parameters.SERVICE_TIME => column of the dataframe which is going to host the service time
85
+ - Parameters.WAITING_TIME => column of the dataframe which is going to host the waiting time
86
+ - Parameters.SOJOURN_TIME => column of the dataframe which is going to host the sojourn time
87
+ - Parameters.CASE_ID_COLUMN => case ID column in the dataframe (default: case:concept:name)
88
+ - Parameters.ACTIVITY_COLUMN => activity column in the dataframe (default: concept:name)
89
+ - Parameters.TIMESTAMP_COLUMN => timestamp column in the dataframe (default: time:timestamp)
90
+ - Parameters.RESOURCE_COLUMN => resource column in the dataframe (default: org:resource)
91
+ - Parameters.START_TIMESTAMP_COLUMN => start timestamp column in the dataframe (if not provided, the timestamp column is used)
92
+
93
+ Returns
94
+ ----------------
95
+ features_df
96
+ Dataframe with temporal features, aggregated per time window
97
+ """
98
+ if parameters is None:
99
+ parameters = {}
100
+
101
+ grouper_freq = exec_utils.get_param_value(
102
+ Parameters.GROUPER_FREQ, parameters, "W"
103
+ )
104
+ timestamp_column = exec_utils.get_param_value(
105
+ Parameters.TIMESTAMP_COLUMN,
106
+ parameters,
107
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
108
+ )
109
+ start_timestamp_column = exec_utils.get_param_value(
110
+ Parameters.START_TIMESTAMP_COLUMN, parameters, None
111
+ )
112
+ if start_timestamp_column is None:
113
+ start_timestamp_column = timestamp_column
114
+
115
+ case_id_column = exec_utils.get_param_value(
116
+ Parameters.CASE_ID_COLUMN, parameters, constants.CASE_CONCEPT_NAME
117
+ )
118
+ diff_start_end = exec_utils.get_param_value(
119
+ Parameters.DIFF_START_END, parameters, "@@diff_start_end"
120
+ )
121
+ arrival_rate = exec_utils.get_param_value(
122
+ Parameters.ARRIVAL_RATE, parameters, "@@arrival_rate"
123
+ )
124
+ finish_rate = exec_utils.get_param_value(
125
+ Parameters.FINISH_RATE, parameters, "@@finish_rate"
126
+ )
127
+ service_time = exec_utils.get_param_value(
128
+ Parameters.SERVICE_TIME, parameters, "@@service_time"
129
+ )
130
+ waiting_time = exec_utils.get_param_value(
131
+ Parameters.WAITING_TIME, parameters, "@@waiting_time"
132
+ )
133
+ sojourn_time = exec_utils.get_param_value(
134
+ Parameters.SOJOURN_TIME, parameters, "@@sojourn_time"
135
+ )
136
+ resource_column = exec_utils.get_param_value(
137
+ Parameters.RESOURCE_COLUMN,
138
+ parameters,
139
+ xes_constants.DEFAULT_RESOURCE_KEY,
140
+ )
141
+ activity_column = exec_utils.get_param_value(
142
+ Parameters.ACTIVITY_COLUMN, parameters, xes_constants.DEFAULT_NAME_KEY
143
+ )
144
+
145
+ # Convert input event log to a DataFrame if necessary
146
+ log_df = log_converter.apply(
147
+ log,
148
+ variant=log_converter.Variants.TO_DATA_FRAME,
149
+ parameters=parameters,
150
+ )
151
+
152
+ # Insert arrival and finish rate columns
153
+ log_df = pandas_utils.insert_case_arrival_finish_rate(
154
+ log_df,
155
+ case_id_column=case_id_column,
156
+ timestamp_column=timestamp_column,
157
+ arrival_rate_column=arrival_rate,
158
+ finish_rate_column=finish_rate,
159
+ )
160
+
161
+ # Insert service, waiting, sojourn times
162
+ log_df = pandas_utils.insert_case_service_waiting_time(
163
+ log_df,
164
+ case_id_column=case_id_column,
165
+ timestamp_column=timestamp_column,
166
+ diff_start_end_column=diff_start_end,
167
+ service_time_column=service_time,
168
+ sojourn_time_column=sojourn_time,
169
+ waiting_time_column=waiting_time,
170
+ )
171
+
172
+ # Group the log by time windows
173
+ grouped_log = log_df.groupby(
174
+ pandas_utils.get_grouper(key=start_timestamp_column, freq=grouper_freq)
175
+ )
176
+
177
+ final_values = []
178
+
179
+ for gkey, gval in grouped_log:
180
+ dct = {}
181
+ dct["timestamp"] = gkey
182
+
183
+ # Group by case to get one row per case (first arrival_rate, etc.)
184
+ gval_first = gval.groupby(case_id_column).first()
185
+
186
+ # Keep existing features (if desired)
187
+ dct["unique_resources"] = gval[resource_column].nunique()
188
+ dct["unique_activities"] = gval[activity_column].nunique()
189
+ dct["num_events"] = len(gval)
190
+
191
+ dct["average_arrival_rate"] = gval_first[arrival_rate].mean()
192
+ dct["average_finish_rate"] = gval_first[finish_rate].mean()
193
+ dct["average_waiting_time"] = gval_first[waiting_time].mean()
194
+ dct["average_sojourn_time"] = gval_first[sojourn_time].mean()
195
+ dct["average_service_time"] = gval_first[service_time].mean()
196
+
197
+ # -----------------------------------------------------------------
198
+ # NEW FEATURES
199
+ # -----------------------------------------------------------------
200
+ # (1) Total number of reworked activities
201
+ # For each case: (number_of_events) - (unique_activities)
202
+ # Then sum across all cases in the window.
203
+ if len(gval) > 0:
204
+ reworks_series = gval.groupby(case_id_column)[activity_column].apply(
205
+ lambda series: series.size - series.nunique()
206
+ )
207
+ dct["total_number_of_reworked_activities"] = reworks_series.sum()
208
+
209
+ # (2) Average number of cases per resource
210
+ # For each resource, count distinct cases, then average over resources
211
+ cases_per_resource = gval.groupby(resource_column)[case_id_column].nunique()
212
+ dct["avg_cases_per_resource"] = (
213
+ cases_per_resource.mean() if not pd.isna(cases_per_resource.mean()) else 0
214
+ )
215
+
216
+ # (3) Average number of events per case
217
+ # For each case, count events, then average
218
+ events_per_case = gval.groupby(case_id_column).size()
219
+ dct["avg_events_per_case"] = (
220
+ events_per_case.mean() if not pd.isna(events_per_case.mean()) else 0
221
+ )
222
+
223
+ # (4) Number of cases
224
+ dct["number_of_cases"] = gval[case_id_column].nunique()
225
+
226
+ # (5) Average number of resources per case
227
+ # For each case, count distinct resources, then average
228
+ resources_per_case = gval.groupby(case_id_column)[resource_column].nunique()
229
+ dct["avg_resources_per_case"] = (
230
+ resources_per_case.mean() if not pd.isna(resources_per_case.mean()) else 0
231
+ )
232
+ # -----------------------------------------------------------------
233
+ else:
234
+ dct["total_number_of_reworked_activities"] = 0
235
+ dct["avg_cases_per_resource"] = 0
236
+ dct["avg_events_per_case"] = 0
237
+ dct["avg_resources_per_case"] = 0
238
+
239
+ final_values.append(dct)
240
+
241
+ dataframe = pandas_utils.instantiate_dataframe(final_values)
242
+ # Fill any remaining NaNs with 0
243
+ dataframe = dataframe.fillna(0)
244
+
245
+ return dataframe
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/temporal_lazy.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from enum import Enum
23
+ from typing import Optional, Dict, Any
24
+
25
+ from pm4py.util import exec_utils, constants, xes_constants, pandas_utils
26
+
27
+
28
+ class Parameters(Enum):
29
+ ARRIVAL_RATE = "arrival_rate"
30
+ FINISH_RATE = "finish_rate"
31
+ CASE_ID_COLUMN = constants.PARAMETER_CONSTANT_CASEID_KEY
32
+ START_TIMESTAMP_COLUMN = constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY
33
+ TIMESTAMP_COLUMN = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
34
+ RESOURCE_COLUMN = constants.PARAMETER_CONSTANT_RESOURCE_KEY
35
+ ACTIVITY_COLUMN = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
36
+ GROUPER_FREQ = "grouper_freq"
37
+ SERVICE_TIME = "service_time"
38
+ WAITING_TIME = "waiting_time"
39
+ SOJOURN_TIME = "sojourn_time"
40
+ DIFF_START_END = "diff_start_end"
41
+
42
+
43
+ _WINDOW_START_COL = "__window_start"
44
+
45
+
46
+ def _freq_to_polars_duration(freq: str) -> str:
47
+ """
48
+ Convert a pandas-style frequency string to a Polars duration string.
49
+ """
50
+ if not freq:
51
+ raise ValueError("grouper frequency must be a non-empty string")
52
+
53
+ freq = freq.strip()
54
+ freq_upper = freq.upper()
55
+ # Remove timezone/day designators (e.g., W-MON -> W)
56
+ if "-" in freq_upper:
57
+ freq_upper = freq_upper.split("-", 1)[0]
58
+
59
+ numbers = "".join(ch for ch in freq_upper if ch.isdigit())
60
+ letters = "".join(ch for ch in freq_upper if ch.isalpha())
61
+
62
+ if not letters:
63
+ raise ValueError(f"cannot infer unit from grouper frequency '{freq}'")
64
+
65
+ if not numbers:
66
+ numbers = "1"
67
+
68
+ normalized_unit = letters
69
+ if normalized_unit in {"MIN"}:
70
+ normalized_unit = "MIN"
71
+ else:
72
+ # Drop suffixes such as S, E (month/quarter/year start/end)
73
+ normalized_unit = normalized_unit.rstrip("S").rstrip("E")
74
+ if not normalized_unit:
75
+ normalized_unit = letters
76
+
77
+ unit_mapping = {
78
+ "S": "s",
79
+ "SEC": "s",
80
+ "SECOND": "s",
81
+ "MIN": "m",
82
+ "T": "m",
83
+ "H": "h",
84
+ "D": "d",
85
+ "W": "w",
86
+ "M": "mo",
87
+ "Q": "q",
88
+ "Y": "y",
89
+ "A": "y",
90
+ }
91
+
92
+ if normalized_unit not in unit_mapping:
93
+ raise ValueError(
94
+ f"grouper frequency '{freq}' is not supported when using the temporal_lazy variant."
95
+ )
96
+
97
+ return f"{numbers}{unit_mapping[normalized_unit]}"
98
+
99
+
100
+ def apply(
101
+ log,
102
+ parameters: Optional[Dict[Any, Any]] = None,
103
+ ):
104
+ """
105
+ Aggregates a Polars LazyFrame event log into temporal windows.
106
+
107
+ This is the lazy Polars equivalent of the temporal variant. From an
108
+ event-log point of view, events are grouped by timestamp windows and each
109
+ output row describes one window. The returned LazyFrame contains the same
110
+ feature semantics as the pandas temporal variant, such as unique
111
+ resources, unique activities, number of events, average waiting/service
112
+ times, rework counts, and cases/resources per window.
113
+
114
+ Example with GROUPER_FREQ="D":
115
+ day 2024-01-01 has 2 cases and 5 events
116
+ day 2024-01-02 has 1 case and 2 events
117
+
118
+ The result is a lazy query that, when collected, yields two rows with
119
+ window-level feature values.
120
+
121
+ Parameters
122
+ ----------------
123
+ log
124
+ Polars LazyFrame containing the event log
125
+ parameters
126
+ Parameters of the algorithm (same semantics as the pandas-based temporal variant)
127
+
128
+ Returns
129
+ ----------------
130
+ pl.DataFrame
131
+ Dataframe with temporal features, aggregated per time window
132
+ """
133
+ if parameters is None:
134
+ parameters = {}
135
+
136
+ import polars as pl
137
+
138
+ if not pandas_utils.is_polars_lazyframe(log):
139
+ raise TypeError(
140
+ "temporal_lazy.apply expects a Polars LazyFrame as input."
141
+ )
142
+
143
+ grouper_freq = exec_utils.get_param_value(
144
+ Parameters.GROUPER_FREQ, parameters, "W"
145
+ )
146
+ timestamp_column = exec_utils.get_param_value(
147
+ Parameters.TIMESTAMP_COLUMN,
148
+ parameters,
149
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
150
+ )
151
+ start_timestamp_column = exec_utils.get_param_value(
152
+ Parameters.START_TIMESTAMP_COLUMN, parameters, None
153
+ )
154
+ if start_timestamp_column is None:
155
+ start_timestamp_column = timestamp_column
156
+
157
+ case_id_column = exec_utils.get_param_value(
158
+ Parameters.CASE_ID_COLUMN, parameters, constants.CASE_CONCEPT_NAME
159
+ )
160
+ diff_start_end = exec_utils.get_param_value(
161
+ Parameters.DIFF_START_END, parameters, "@@diff_start_end"
162
+ )
163
+ arrival_rate = exec_utils.get_param_value(
164
+ Parameters.ARRIVAL_RATE, parameters, "@@arrival_rate"
165
+ )
166
+ finish_rate = exec_utils.get_param_value(
167
+ Parameters.FINISH_RATE, parameters, "@@finish_rate"
168
+ )
169
+ service_time = exec_utils.get_param_value(
170
+ Parameters.SERVICE_TIME, parameters, "@@service_time"
171
+ )
172
+ waiting_time = exec_utils.get_param_value(
173
+ Parameters.WAITING_TIME, parameters, "@@waiting_time"
174
+ )
175
+ sojourn_time = exec_utils.get_param_value(
176
+ Parameters.SOJOURN_TIME, parameters, "@@sojourn_time"
177
+ )
178
+ resource_column = exec_utils.get_param_value(
179
+ Parameters.RESOURCE_COLUMN,
180
+ parameters,
181
+ xes_constants.DEFAULT_RESOURCE_KEY,
182
+ )
183
+ activity_column = exec_utils.get_param_value(
184
+ Parameters.ACTIVITY_COLUMN, parameters, xes_constants.DEFAULT_NAME_KEY
185
+ )
186
+
187
+ lazy_log = pandas_utils.insert_case_arrival_finish_rate(
188
+ log,
189
+ case_id_column=case_id_column,
190
+ timestamp_column=timestamp_column,
191
+ start_timestamp_column=start_timestamp_column,
192
+ arrival_rate_column=arrival_rate,
193
+ finish_rate_column=finish_rate,
194
+ )
195
+
196
+ lazy_log = pandas_utils.insert_case_service_waiting_time(
197
+ lazy_log,
198
+ case_id_column=case_id_column,
199
+ timestamp_column=timestamp_column,
200
+ start_timestamp_column=start_timestamp_column,
201
+ diff_start_end_column=diff_start_end,
202
+ service_time_column=service_time,
203
+ sojourn_time_column=sojourn_time,
204
+ waiting_time_column=waiting_time,
205
+ )
206
+
207
+ duration = _freq_to_polars_duration(grouper_freq)
208
+
209
+ lazy_log = lazy_log.with_columns(
210
+ pl.col(start_timestamp_column)
211
+ .dt.truncate(duration)
212
+ .alias(_WINDOW_START_COL)
213
+ )
214
+
215
+ case_agg = (
216
+ lazy_log.group_by([_WINDOW_START_COL, case_id_column])
217
+ .agg(
218
+ pl.len().alias("__events_per_case"),
219
+ pl.col(activity_column)
220
+ .drop_nulls()
221
+ .n_unique()
222
+ .alias("__unique_acts_per_case"),
223
+ pl.col(resource_column)
224
+ .drop_nulls()
225
+ .n_unique()
226
+ .alias("__unique_res_per_case"),
227
+ pl.col(arrival_rate).first().alias("__arrival_rate"),
228
+ pl.col(finish_rate).first().alias("__finish_rate"),
229
+ pl.col(waiting_time).first().alias("__waiting_time"),
230
+ pl.col(sojourn_time).first().alias("__sojourn_time"),
231
+ pl.col(service_time).first().alias("__service_time"),
232
+ )
233
+ .with_columns(
234
+ (
235
+ pl.col("__events_per_case")
236
+ - pl.col("__unique_acts_per_case")
237
+ ).alias("__reworks_per_case")
238
+ )
239
+ )
240
+
241
+ case_window = case_agg.group_by(_WINDOW_START_COL).agg(
242
+ pl.col("__reworks_per_case")
243
+ .sum()
244
+ .alias("total_number_of_reworked_activities"),
245
+ pl.col("__events_per_case").mean().alias("avg_events_per_case"),
246
+ pl.col("__unique_res_per_case").mean().alias("avg_resources_per_case"),
247
+ pl.col(case_id_column).n_unique().alias("number_of_cases"),
248
+ pl.col("__arrival_rate").mean().alias("average_arrival_rate"),
249
+ pl.col("__finish_rate").mean().alias("average_finish_rate"),
250
+ pl.col("__waiting_time").mean().alias("average_waiting_time"),
251
+ pl.col("__sojourn_time").mean().alias("average_sojourn_time"),
252
+ pl.col("__service_time").mean().alias("average_service_time"),
253
+ )
254
+
255
+ resource_agg = (
256
+ lazy_log.filter(pl.col(resource_column).is_not_null())
257
+ .group_by([_WINDOW_START_COL, resource_column])
258
+ .agg(
259
+ pl.col(case_id_column)
260
+ .n_unique()
261
+ .alias("__cases_per_resource")
262
+ )
263
+ )
264
+
265
+ resource_window = resource_agg.group_by(_WINDOW_START_COL).agg(
266
+ pl.col("__cases_per_resource")
267
+ .mean()
268
+ .alias("avg_cases_per_resource")
269
+ )
270
+
271
+ basic_window = lazy_log.group_by(_WINDOW_START_COL).agg(
272
+ pl.col(resource_column)
273
+ .drop_nulls()
274
+ .n_unique()
275
+ .alias("unique_resources"),
276
+ pl.col(activity_column)
277
+ .drop_nulls()
278
+ .n_unique()
279
+ .alias("unique_activities"),
280
+ pl.len().alias("num_events"),
281
+ )
282
+
283
+ result_lazy = (
284
+ basic_window.join(case_window, on=_WINDOW_START_COL, how="left", maintain_order="left")
285
+ .join(resource_window, on=_WINDOW_START_COL, how="left", maintain_order="left")
286
+ .sort(_WINDOW_START_COL)
287
+ .rename({_WINDOW_START_COL: "timestamp"})
288
+ .with_columns(
289
+ [
290
+ pl.col("total_number_of_reworked_activities").fill_null(0),
291
+ pl.col("avg_events_per_case").fill_null(0),
292
+ pl.col("avg_resources_per_case").fill_null(0),
293
+ pl.col("average_arrival_rate").fill_null(0),
294
+ pl.col("average_finish_rate").fill_null(0),
295
+ pl.col("average_waiting_time").fill_null(0),
296
+ pl.col("average_sojourn_time").fill_null(0),
297
+ pl.col("average_service_time").fill_null(0),
298
+ pl.col("avg_cases_per_resource").fill_null(0),
299
+ pl.col("number_of_cases").fill_null(0),
300
+ pl.col("unique_resources").fill_null(0),
301
+ pl.col("unique_activities").fill_null(0),
302
+ pl.col("num_events").fill_null(0),
303
+ ]
304
+ )
305
+ .select(
306
+ [
307
+ "timestamp",
308
+ "unique_resources",
309
+ "unique_activities",
310
+ "num_events",
311
+ "average_arrival_rate",
312
+ "average_finish_rate",
313
+ "average_waiting_time",
314
+ "average_sojourn_time",
315
+ "average_service_time",
316
+ "total_number_of_reworked_activities",
317
+ "avg_cases_per_resource",
318
+ "avg_events_per_case",
319
+ "number_of_cases",
320
+ "avg_resources_per_case",
321
+ ]
322
+ )
323
+ )
324
+
325
+ return result_lazy
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/tf_idf.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ """
23
+ Trace-level TF-IDF encoding.
24
+
25
+ From an event-log point of view, each case is read as a sequence of tokens.
26
+ By default, the token of an event is its activity name. The output has one
27
+ row per trace and one column per token or n-gram. The cell is the TF-IDF
28
+ weight of that token in that trace: tokens that are frequent in one trace
29
+ but rare across the log receive higher weights.
30
+
31
+ Example with activity tokens:
32
+ case 1: A, B, A
33
+ case 2: A, C
34
+
35
+ The vocabulary is [A, B, C]. A appears in both traces, so it receives a lower
36
+ inverse-document-frequency weight than B or C, which are more trace-specific.
37
+
38
+ Reference:
39
+ Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
40
+ "Trace encoding in process mining: A survey and benchmarking."
41
+ Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
42
+ https://doi.org/10.1016/j.engappai.2023.107028
43
+
44
+ This variant delegates vector construction to scikit-learn's maintained
45
+ TfidfVectorizer using PM4Py trace tokens.
46
+ """
47
+
48
+ from enum import Enum
49
+ from typing import Any, Dict, Optional, Union
50
+
51
+ import pandas as pd
52
+
53
+ from pm4py.objects.log.obj import EventLog, EventStream
54
+ from pm4py.algo.transformation.trace_encodings.util import sklearn_vectorization
55
+
56
+
57
+ class Parameters(Enum):
58
+ EVENT_ATTRIBUTES = "event_attributes"
59
+ TRACE_ATTRIBUTES = "trace_attributes"
60
+ NGRAM_RANGE = "ngram_range"
61
+ RETURN_SPARSE = "return_sparse"
62
+ VECTORIZER = "vectorizer"
63
+ FIT_VECTORIZER = "fit_vectorizer"
64
+
65
+
66
+ def apply(
67
+ log: Union[EventLog, EventStream, pd.DataFrame],
68
+ parameters: Optional[Dict[Any, Any]] = None,
69
+ ):
70
+ """
71
+ Encodes each trace as TF-IDF weights over trace tokens or n-grams.
72
+
73
+ Parameters
74
+ ----------
75
+ log
76
+ Event log, event stream, or dataframe containing traces.
77
+ parameters
78
+ Parameters of the encoding. Common options:
79
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
80
+ the activity attribute.
81
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
82
+ - NGRAM_RANGE: tuple such as (1, 1) or (1, 2).
83
+ - RETURN_SPARSE: if True, returns the sklearn sparse matrix.
84
+
85
+ Returns
86
+ -------
87
+ data
88
+ One row per trace, one TF-IDF weight per discovered token/n-gram.
89
+ feature_names
90
+ Token or n-gram names corresponding to the columns of data.
91
+ """
92
+ return sklearn_vectorization.apply_tfidf(
93
+ log, ngram_range=(1, 1), parameters=parameters
94
+ )
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/token_replay.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ """
23
+ Token-replay trace encoding.
24
+
25
+ From an event-log point of view, each trace is replayed on a Petri net and
26
+ the replay diagnostics become the trace vector. The vector contains:
27
+ is-fit, fitness, missing tokens, consumed tokens, remaining tokens, and
28
+ produced tokens.
29
+
30
+ Example with a model A -> B -> C:
31
+ case 1: A, B, C
32
+ case 2: A, C
33
+
34
+ case 1 can be replayed without adding or leaving tokens, so it receives a
35
+ fit vector such as [1, 1.0, 0, consumed, 0, produced]. case 2 skips B, so
36
+ token replay has to add or compensate for tokens and the missing-token
37
+ count and fitness reflect that deviation.
38
+
39
+ The Petri net can be passed with net, initial_marking, and final_marking. If
40
+ no model is passed, the variant discovers one from the log using PM4Py's
41
+ Inductive Miner.
42
+
43
+ Reference:
44
+ Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
45
+ "Trace encoding in process mining: A survey and benchmarking."
46
+ Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
47
+ https://doi.org/10.1016/j.engappai.2023.107028
48
+
49
+ The survey lists token-replay as a PM-based encoding and points to PM4Py as
50
+ the maintained implementation. This variant delegates replay computation to
51
+ PM4Py's token replay and exposes per-trace replay diagnostics as vectors.
52
+ """
53
+
54
+ from enum import Enum
55
+ from typing import Any, Dict, Optional, Union
56
+
57
+ import pandas as pd
58
+
59
+ from pm4py.objects.log.obj import EventLog, EventStream
60
+ from pm4py.algo.transformation.trace_encodings.util import petri_net
61
+
62
+
63
+ class Parameters(Enum):
64
+ NET = "net"
65
+ PETRI_NET = "petri_net"
66
+ INITIAL_MARKING = "initial_marking"
67
+ FINAL_MARKING = "final_marking"
68
+ DISCOVER_MODEL = "discover_model"
69
+ TOKEN_REPLAY_VARIANT = "token_replay_variant"
70
+
71
+
72
+ FEATURE_NAMES = [
73
+ "@@token_replay_is_fit",
74
+ "@@token_replay_fitness",
75
+ "@@token_replay_missing_tokens",
76
+ "@@token_replay_consumed_tokens",
77
+ "@@token_replay_remaining_tokens",
78
+ "@@token_replay_produced_tokens",
79
+ ]
80
+
81
+
82
+ def apply(
83
+ log: Union[EventLog, EventStream, pd.DataFrame],
84
+ parameters: Optional[Dict[Any, Any]] = None,
85
+ ):
86
+ """
87
+ Encodes each trace with token-replay conformance diagnostics.
88
+
89
+ Parameters
90
+ ----------
91
+ log
92
+ Event log, event stream, or dataframe containing traces.
93
+ parameters
94
+ Parameters of the encoding. Common options:
95
+ - NET/PETRI_NET, INITIAL_MARKING, FINAL_MARKING: existing Petri net
96
+ model to replay on.
97
+ - DISCOVER_MODEL: if True, discover a Petri net when no model is
98
+ supplied.
99
+ - TOKEN_REPLAY_VARIANT: PM4Py token replay variant.
100
+
101
+ Returns
102
+ -------
103
+ data
104
+ One row per trace with token-replay diagnostics.
105
+ feature_names
106
+ Diagnostic names corresponding to the columns of data.
107
+ """
108
+ if parameters is None:
109
+ parameters = {}
110
+
111
+ from pm4py.algo.conformance.tokenreplay import algorithm as token_replay
112
+ from pm4py.util import exec_utils
113
+
114
+ event_log, net, initial_marking, final_marking = petri_net.get_log_and_model(
115
+ log, parameters=parameters
116
+ )
117
+ variant = exec_utils.get_param_value(
118
+ Parameters.TOKEN_REPLAY_VARIANT,
119
+ parameters,
120
+ token_replay.DEFAULT_VARIANT,
121
+ )
122
+
123
+ replayed_traces = token_replay.apply(
124
+ event_log,
125
+ net,
126
+ initial_marking,
127
+ final_marking,
128
+ parameters=parameters,
129
+ variant=variant,
130
+ )
131
+
132
+ data = []
133
+ for replayed_trace in replayed_traces:
134
+ data.append(
135
+ [
136
+ 1.0 if replayed_trace.get("trace_is_fit", False) else 0.0,
137
+ float(replayed_trace.get("trace_fitness", 0.0)),
138
+ float(replayed_trace.get("missing_tokens", 0.0)),
139
+ float(replayed_trace.get("consumed_tokens", 0.0)),
140
+ float(replayed_trace.get("remaining_tokens", 0.0)),
141
+ float(replayed_trace.get("produced_tokens", 0.0)),
142
+ ]
143
+ )
144
+
145
+ return data, FEATURE_NAMES
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/trace_based.py ADDED
@@ -0,0 +1,1669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from enum import Enum
23
+ from typing import Optional, Dict, Any, Union, Tuple, List, Set
24
+
25
+ from pm4py.objects.conversion.log import converter
26
+ from pm4py.objects.log.obj import EventLog, Trace, Event
27
+ from pm4py.objects.log.util import dataframe_utils
28
+ from pm4py.util import constants, pandas_utils
29
+ from pm4py.util import exec_utils
30
+ from pm4py.util import xes_constants as xes
31
+ from pm4py.util import xes_constants
32
+ from pm4py.utils import is_polars_lazyframe
33
+
34
+
35
+ class Parameters(Enum):
36
+ ENABLE_ACTIVITY_DEF_REPRESENTATION = "enable_activity_def_representation"
37
+ ENABLE_SUCC_DEF_REPRESENTATION = "enable_succ_def_representation"
38
+ STR_TRACE_ATTRIBUTES = "str_tr_attr"
39
+ STR_EVENT_ATTRIBUTES = "str_ev_attr"
40
+ NUM_TRACE_ATTRIBUTES = "num_tr_attr"
41
+ NUM_EVENT_ATTRIBUTES = "num_ev_attr"
42
+ STR_EVSUCC_ATTRIBUTES = "str_evsucc_attr"
43
+ FEATURE_NAMES = "feature_names"
44
+ ACTIVITY_KEY = constants.PARAMETER_CONSTANT_ACTIVITY_KEY
45
+ START_TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY
46
+ TIMESTAMP_KEY = constants.PARAMETER_CONSTANT_TIMESTAMP_KEY
47
+ CASE_ID_KEY = constants.PARAMETER_CONSTANT_CASEID_KEY
48
+ RESOURCE_KEY = constants.PARAMETER_CONSTANT_RESOURCE_KEY
49
+ EPSILON = "epsilon"
50
+ DEFAULT_NOT_PRESENT = "default_not_present"
51
+ ENABLE_ALL_EXTRA_FEATURES = "enable_all_extra_features"
52
+ ENABLE_CASE_DURATION = "enable_case_duration"
53
+ ADD_CASE_IDENTIFIER_COLUMN = "add_case_identifier_column"
54
+ ENABLE_TIMES_FROM_FIRST_OCCURRENCE = "enable_times_from_first_occurrence"
55
+ ENABLE_TIMES_FROM_LAST_OCCURRENCE = "enable_times_from_last_occurrence"
56
+ ENABLE_DIRECT_PATHS_TIMES_LAST_OCC = "enable_direct_paths_times_last_occ"
57
+ ENABLE_INDIRECT_PATHS_TIMES_LAST_OCC = (
58
+ "enable_indirect_paths_times_last_occ"
59
+ )
60
+ ENABLE_WORK_IN_PROGRESS = "enable_work_in_progress"
61
+ ENABLE_RESOURCE_WORKLOAD = "enable_resource_workload"
62
+ ENABLE_FIRST_LAST_ACTIVITY_INDEX = "enable_first_last_activity_index"
63
+ ENABLE_MAX_CONCURRENT_EVENTS = "enable_max_concurrent_events"
64
+ ENABLE_MAX_CONCURRENT_EVENTS_PER_ACTIVITY = (
65
+ "enable_max_concurrent_events_per_activity"
66
+ )
67
+ ENABLE_NUMERIC_ATTRIBUTE_STATISTICS = "enable_numeric_attribute_statistics"
68
+ NUMERIC_ATTRIBUTE_AGGREGATIONS = "numeric_attribute_aggregations"
69
+ CASE_ATTRIBUTE_PREFIX = constants.CASE_ATTRIBUTE_PREFIX
70
+
71
+
72
+ def max_concurrent_events(
73
+ log: EventLog,
74
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
75
+ ) -> Tuple[Any, List[str]]:
76
+ """
77
+ Counts for every trace the maximum number of events (of any activity) that happen concurrently
78
+ (e.g., their time intervals [st1, ct1] and [st2, ct2] have non-empty intersection).
79
+
80
+ Parameters
81
+ -----------------
82
+ log
83
+ Event log
84
+ parameters
85
+ Parameters of the algorithm
86
+
87
+ Returns
88
+ ----------------
89
+ data
90
+ Numeric value of the features
91
+ feature_names
92
+ Names of the features
93
+ """
94
+ if parameters is None:
95
+ parameters = {}
96
+
97
+ start_timestamp_key = exec_utils.get_param_value(
98
+ Parameters.START_TIMESTAMP_KEY,
99
+ parameters,
100
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
101
+ )
102
+ timestamp_key = exec_utils.get_param_value(
103
+ Parameters.TIMESTAMP_KEY,
104
+ parameters,
105
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
106
+ )
107
+
108
+ data = []
109
+ feature_names = ["@@max_concurrent_activities_general"]
110
+
111
+ for trace in log:
112
+ max_conc = 0
113
+ i = 0
114
+ while i < len(trace) - 1:
115
+ conc = 0
116
+ ct = trace[i][timestamp_key].timestamp()
117
+ j = i + 1
118
+ while j < len(trace):
119
+ st = trace[j][start_timestamp_key].timestamp()
120
+ if st > ct:
121
+ break
122
+ conc = conc + 1
123
+ j = j + 1
124
+ if conc > max_conc:
125
+ max_conc = conc
126
+ i = i + 1
127
+ data.append([float(max_conc)])
128
+
129
+ return data, feature_names
130
+
131
+
132
+ def max_concurrent_events_per_activity(
133
+ log: EventLog,
134
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
135
+ ) -> Tuple[Any, List[str]]:
136
+ """
137
+ Counts for every trace and every activity the maximum number of events of the given activity that happen concurrently
138
+ (e.g., their time intervals [st1, ct1] and [st2, ct2] have non-empty intersection).
139
+
140
+ Parameters
141
+ -----------------
142
+ log
143
+ Event log
144
+ parameters
145
+ Parameters of the algorithm
146
+
147
+ Returns
148
+ ----------------
149
+ data
150
+ Numeric value of the features
151
+ feature_names
152
+ Names of the features
153
+ """
154
+ if parameters is None:
155
+ parameters = {}
156
+
157
+ start_timestamp_key = exec_utils.get_param_value(
158
+ Parameters.START_TIMESTAMP_KEY,
159
+ parameters,
160
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
161
+ )
162
+ timestamp_key = exec_utils.get_param_value(
163
+ Parameters.TIMESTAMP_KEY,
164
+ parameters,
165
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
166
+ )
167
+ activity_key = exec_utils.get_param_value(
168
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
169
+ )
170
+
171
+ activities = list(set(y[activity_key] for x in log for y in x))
172
+
173
+ data = []
174
+ feature_names = [
175
+ "@@max_concurrent_activities_like_" + x for x in activities
176
+ ]
177
+
178
+ for trace in log:
179
+ max_conc_act = {act: 0 for act in activities}
180
+ i = 0
181
+ while i < len(trace) - 1:
182
+ conc = 0
183
+ act = trace[i][activity_key]
184
+ ct = trace[i][timestamp_key].timestamp()
185
+ j = i + 1
186
+ while j < len(trace):
187
+ st = trace[j][start_timestamp_key].timestamp()
188
+ actj = trace[j][activity_key]
189
+ if st > ct:
190
+ break
191
+ if act == actj:
192
+ conc = conc + 1
193
+ j = j + 1
194
+ i = i + 1
195
+ max_conc_act[act] = max(max_conc_act[act], conc)
196
+ arr = []
197
+ for act in activities:
198
+ arr.append(float(max_conc_act[act]))
199
+ data.append(arr)
200
+
201
+ return data, feature_names
202
+
203
+
204
+ def resource_workload(
205
+ log: EventLog,
206
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
207
+ ) -> Tuple[Any, List[str]]:
208
+ """
209
+ Calculates for each case, and for each resource of the log, the workload of the resource during
210
+ the lead time of a case. Defaults if a resource is not contained in a case.
211
+
212
+ Parameters
213
+ -----------------
214
+ log
215
+ Event log
216
+ parameters
217
+ Parameters of the algorithm
218
+
219
+ Returns
220
+ ----------------
221
+ data
222
+ Numeric value of the features
223
+ feature_names
224
+ Names of the features
225
+ """
226
+ if parameters is None:
227
+ parameters = {}
228
+
229
+ from pm4py.util.intervaltree import IntervalTree, Interval
230
+
231
+ start_timestamp_key = exec_utils.get_param_value(
232
+ Parameters.START_TIMESTAMP_KEY,
233
+ parameters,
234
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
235
+ )
236
+ timestamp_key = exec_utils.get_param_value(
237
+ Parameters.TIMESTAMP_KEY,
238
+ parameters,
239
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
240
+ )
241
+ resource_key = exec_utils.get_param_value(
242
+ Parameters.RESOURCE_KEY, parameters, xes_constants.DEFAULT_RESOURCE_KEY
243
+ )
244
+ epsilon = exec_utils.get_param_value(
245
+ Parameters.EPSILON, parameters, 0.000001
246
+ )
247
+ default_not_present = exec_utils.get_param_value(
248
+ Parameters.DEFAULT_NOT_PRESENT, parameters, 0
249
+ )
250
+
251
+ tree_dict = {}
252
+ for case in log:
253
+ if case:
254
+ resources = set(x[resource_key] for x in case if resource_key in x)
255
+ st = case[0][start_timestamp_key].timestamp() - epsilon
256
+ ct = case[-1][timestamp_key].timestamp() + epsilon
257
+ for res in resources:
258
+ if res not in tree_dict:
259
+ tree_dict[res] = IntervalTree()
260
+ tree_dict[res].add(Interval(st, ct))
261
+
262
+ resources_list = sorted(list(tree_dict))
263
+
264
+ data = []
265
+ feature_names = ["resource_workload@@" + r for r in resources_list]
266
+
267
+ for case in log:
268
+ data.append([])
269
+ resources = set(x[resource_key] for x in case if resource_key in x)
270
+ st = case[0][start_timestamp_key].timestamp() - epsilon
271
+ ct = case[-1][timestamp_key].timestamp() + epsilon
272
+ for res in resources_list:
273
+ if res in resources:
274
+ data[-1].append(float(len(tree_dict[res][st:ct])))
275
+ else:
276
+ data[-1].append(float(default_not_present))
277
+
278
+ return data, feature_names
279
+
280
+
281
+ def work_in_progress(
282
+ log: EventLog,
283
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
284
+ ) -> Tuple[Any, List[str]]:
285
+ """
286
+ Calculates for each case, and for each resource of the log, the number of cases which are open during
287
+ the lead time of the case.
288
+
289
+ Parameters
290
+ -----------------
291
+ log
292
+ Event log
293
+ parameters
294
+ Parameters of the algorithm
295
+
296
+ Returns
297
+ ----------------
298
+ data
299
+ Numeric value of the features
300
+ feature_names
301
+ Names of the features
302
+ """
303
+ if parameters is None:
304
+ parameters = {}
305
+
306
+ from pm4py.util.intervaltree import IntervalTree, Interval
307
+
308
+ start_timestamp_key = exec_utils.get_param_value(
309
+ Parameters.START_TIMESTAMP_KEY,
310
+ parameters,
311
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
312
+ )
313
+ timestamp_key = exec_utils.get_param_value(
314
+ Parameters.TIMESTAMP_KEY,
315
+ parameters,
316
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
317
+ )
318
+ epsilon = exec_utils.get_param_value(
319
+ Parameters.EPSILON, parameters, 0.000001
320
+ )
321
+ default_not_present = exec_utils.get_param_value(
322
+ Parameters.DEFAULT_NOT_PRESENT, parameters, 0
323
+ )
324
+
325
+ tree = IntervalTree()
326
+ for case in log:
327
+ if case:
328
+ st = case[0][start_timestamp_key].timestamp() - epsilon
329
+ ct = case[-1][timestamp_key].timestamp() + epsilon
330
+ tree.add(Interval(st, ct))
331
+
332
+ data = []
333
+ feature_names = ["@@work_in_progress"]
334
+
335
+ for case in log:
336
+ if case:
337
+ st = case[0][start_timestamp_key].timestamp() - epsilon
338
+ ct = case[-1][timestamp_key].timestamp() + epsilon
339
+ data.append([float(len(tree[st:ct]))])
340
+ else:
341
+ data.append([float(default_not_present)])
342
+
343
+ return data, feature_names
344
+
345
+
346
+ def indirect_paths_times_last_occ(
347
+ log: EventLog,
348
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
349
+ ) -> Tuple[Any, List[str]]:
350
+ """
351
+ Calculates for each case, and for each indirect path of the case, the difference between the start timestamp
352
+ of the later event and the completion timestamp of the first event. Defaults if a path is not present in a case.
353
+
354
+ Parameters
355
+ -----------------
356
+ log
357
+ Event log
358
+ parameters
359
+ Parameters of the algorithm
360
+
361
+ Returns
362
+ ----------------
363
+ data
364
+ Numeric value of the features
365
+ feature_names
366
+ Names of the features
367
+ """
368
+ if parameters is None:
369
+ parameters = {}
370
+
371
+ activity_key = exec_utils.get_param_value(
372
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
373
+ )
374
+ start_timestamp_key = exec_utils.get_param_value(
375
+ Parameters.START_TIMESTAMP_KEY,
376
+ parameters,
377
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
378
+ )
379
+ timestamp_key = exec_utils.get_param_value(
380
+ Parameters.TIMESTAMP_KEY,
381
+ parameters,
382
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
383
+ )
384
+ default_not_present = exec_utils.get_param_value(
385
+ Parameters.DEFAULT_NOT_PRESENT, parameters, 0
386
+ )
387
+
388
+ all_paths = set()
389
+ for trace in log:
390
+ for i in range(len(trace) - 1):
391
+ for j in range(i + 2, len(trace)):
392
+ all_paths.add((trace[i][activity_key], trace[j][activity_key]))
393
+ all_paths = sorted(list(all_paths))
394
+
395
+ data = []
396
+ feature_names = []
397
+ for p in all_paths:
398
+ feature_names.append(
399
+ "indirectPathPerformanceLastOcc@@" + p[0] + "##" + p[1]
400
+ )
401
+
402
+ for trace in log:
403
+ data.append([])
404
+ trace_paths_perf = {}
405
+ for i in range(len(trace) - 1):
406
+ for j in range(i + 2, len(trace)):
407
+ p = (trace[i][activity_key], trace[j][activity_key])
408
+ tc = trace[i][timestamp_key].timestamp()
409
+ ts = trace[j][start_timestamp_key].timestamp()
410
+ if ts > tc:
411
+ trace_paths_perf[p] = ts - tc
412
+ for p in all_paths:
413
+ if p in trace_paths_perf:
414
+ data[-1].append(float(trace_paths_perf[p]))
415
+ else:
416
+ data[-1].append(float(default_not_present))
417
+
418
+ return data, feature_names
419
+
420
+
421
+ def direct_paths_times_last_occ(
422
+ log: EventLog,
423
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
424
+ ) -> Tuple[Any, List[str]]:
425
+ """
426
+ Calculates for each case, and for each direct path of the case, the difference between the start timestamp
427
+ of the later event and the completion timestamp of the first event. Defaults if a path is not present in a case.
428
+
429
+ Parameters
430
+ -----------------
431
+ log
432
+ Event log
433
+ parameters
434
+ Parameters of the algorithm
435
+
436
+ Returns
437
+ ----------------
438
+ data
439
+ Numeric value of the features
440
+ feature_names
441
+ Names of the features
442
+ """
443
+ if parameters is None:
444
+ parameters = {}
445
+
446
+ activity_key = exec_utils.get_param_value(
447
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
448
+ )
449
+ start_timestamp_key = exec_utils.get_param_value(
450
+ Parameters.START_TIMESTAMP_KEY,
451
+ parameters,
452
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
453
+ )
454
+ timestamp_key = exec_utils.get_param_value(
455
+ Parameters.TIMESTAMP_KEY,
456
+ parameters,
457
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
458
+ )
459
+ default_not_present = exec_utils.get_param_value(
460
+ Parameters.DEFAULT_NOT_PRESENT, parameters, 0
461
+ )
462
+
463
+ all_paths = set()
464
+ for trace in log:
465
+ for i in range(len(trace) - 1):
466
+ all_paths.add((trace[i][activity_key], trace[i + 1][activity_key]))
467
+ all_paths = sorted(list(all_paths))
468
+
469
+ data = []
470
+ feature_names = []
471
+ for p in all_paths:
472
+ feature_names.append(
473
+ "directPathPerformanceLastOcc@@" + p[0] + "##" + p[1]
474
+ )
475
+
476
+ for trace in log:
477
+ data.append([])
478
+ trace_paths_perf = {}
479
+ for i in range(len(trace) - 1):
480
+ p = (trace[i][activity_key], trace[i + 1][activity_key])
481
+ tc = trace[i][timestamp_key].timestamp()
482
+ ts = trace[i + 1][start_timestamp_key].timestamp()
483
+ if ts > tc:
484
+ trace_paths_perf[p] = ts - tc
485
+ for p in all_paths:
486
+ if p in trace_paths_perf:
487
+ data[-1].append(float(trace_paths_perf[p]))
488
+ else:
489
+ data[-1].append(float(default_not_present))
490
+
491
+ return data, feature_names
492
+
493
+
494
+ def times_from_first_occurrence_activity_case(
495
+ log: EventLog,
496
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
497
+ ) -> Tuple[Any, List[str]]:
498
+ """
499
+ Calculates for each case, and for each activity, the times from the start to the case, and to the end of the case,
500
+ from the first occurrence of the activity in the case.
501
+
502
+ Parameters
503
+ -----------------
504
+ log
505
+ Event log
506
+ parameters
507
+ Parameters of the algorithm
508
+
509
+ Returns
510
+ ----------------
511
+ data
512
+ Numeric value of the features
513
+ feature_names
514
+ Names of the features
515
+ """
516
+ if parameters is None:
517
+ parameters = {}
518
+
519
+ activity_key = exec_utils.get_param_value(
520
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
521
+ )
522
+ start_timestamp_key = exec_utils.get_param_value(
523
+ Parameters.START_TIMESTAMP_KEY,
524
+ parameters,
525
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
526
+ )
527
+ timestamp_key = exec_utils.get_param_value(
528
+ Parameters.TIMESTAMP_KEY,
529
+ parameters,
530
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
531
+ )
532
+ default_not_present = exec_utils.get_param_value(
533
+ Parameters.DEFAULT_NOT_PRESENT, parameters, 0
534
+ )
535
+
536
+ activities_log = set()
537
+ for trace in log:
538
+ for event in trace:
539
+ activities_log.add(event[activity_key])
540
+ activities_log = sorted(list(activities_log))
541
+
542
+ data = []
543
+ feature_names = []
544
+ for act in activities_log:
545
+ feature_names.append("startToFirstOcc@@" + act)
546
+ feature_names.append("firstOccToEnd@@" + act)
547
+
548
+ for trace in log:
549
+ data.append([])
550
+ activities_occ = {}
551
+ for i in range(len(trace)):
552
+ if trace[i][activity_key] not in activities_occ:
553
+ activities_occ[trace[i][activity_key]] = i
554
+ for act in activities_log:
555
+ if act in activities_occ:
556
+ ev = trace[activities_occ[act]]
557
+ this_ev_st = ev[start_timestamp_key].timestamp()
558
+ this_ev_ct = ev[timestamp_key].timestamp()
559
+ start_ev_ct = trace[0][timestamp_key].timestamp()
560
+ end_ev_st = trace[-1][start_timestamp_key].timestamp()
561
+ data[-1].append(float(this_ev_st - start_ev_ct))
562
+ data[-1].append(float(end_ev_st - this_ev_ct))
563
+ else:
564
+ data[-1].append(float(default_not_present))
565
+ data[-1].append(float(default_not_present))
566
+
567
+ return data, feature_names
568
+
569
+
570
+ def times_from_last_occurrence_activity_case(
571
+ log: EventLog,
572
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
573
+ ) -> Tuple[Any, List[str]]:
574
+ """
575
+ Calculates for each case, and for each activity, the times from the start to the case, and to the end of the case,
576
+ from the last occurrence of the activity in the case.
577
+
578
+ Parameters
579
+ -----------------
580
+ log
581
+ Event log
582
+ parameters
583
+ Parameters of the algorithm
584
+
585
+ Returns
586
+ ----------------
587
+ data
588
+ Numeric value of the features
589
+ feature_names
590
+ Names of the features
591
+ """
592
+ if parameters is None:
593
+ parameters = {}
594
+
595
+ activity_key = exec_utils.get_param_value(
596
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
597
+ )
598
+ start_timestamp_key = exec_utils.get_param_value(
599
+ Parameters.START_TIMESTAMP_KEY,
600
+ parameters,
601
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
602
+ )
603
+ timestamp_key = exec_utils.get_param_value(
604
+ Parameters.TIMESTAMP_KEY,
605
+ parameters,
606
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
607
+ )
608
+ default_not_present = exec_utils.get_param_value(
609
+ Parameters.DEFAULT_NOT_PRESENT, parameters, 0
610
+ )
611
+
612
+ activities_log = set()
613
+ for trace in log:
614
+ for event in trace:
615
+ activities_log.add(event[activity_key])
616
+ activities_log = sorted(list(activities_log))
617
+
618
+ data = []
619
+ feature_names = []
620
+ for act in activities_log:
621
+ feature_names.append("startToLastOcc@@" + act)
622
+ feature_names.append("lastOccToEnd@@" + act)
623
+
624
+ for trace in log:
625
+ data.append([])
626
+ activities_occ = {}
627
+ for i in range(len(trace)):
628
+ activities_occ[trace[i][activity_key]] = i
629
+ for act in activities_log:
630
+ if act in activities_occ:
631
+ ev = trace[activities_occ[act]]
632
+ this_ev_st = ev[start_timestamp_key].timestamp()
633
+ this_ev_ct = ev[timestamp_key].timestamp()
634
+ start_ev_ct = trace[0][timestamp_key].timestamp()
635
+ end_ev_st = trace[-1][start_timestamp_key].timestamp()
636
+ data[-1].append(float(this_ev_st - start_ev_ct))
637
+ data[-1].append(float(end_ev_st - this_ev_ct))
638
+ else:
639
+ data[-1].append(float(default_not_present))
640
+ data[-1].append(float(default_not_present))
641
+
642
+ return data, feature_names
643
+
644
+
645
+ def first_last_activity_index_trace(
646
+ log: EventLog,
647
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
648
+ ) -> Tuple[Any, List[str]]:
649
+ """
650
+ Consider as features the first and the last index of an activity inside a case
651
+
652
+ Parameters
653
+ ------------------
654
+ log
655
+ Event log
656
+ parameters
657
+ Parameters, including:
658
+ - Parameters.ACTIVITY_KEY => the attribute to use as activity
659
+ - Parameters.DEFAULT_NOT_PRESENT => the replacement value for activities that are not present for the specific case
660
+
661
+ Returns
662
+ -----------------
663
+ data
664
+ Numeric value of the features
665
+ feature_names
666
+ Names of the features
667
+ """
668
+ if parameters is None:
669
+ parameters = {}
670
+
671
+ activity_key = exec_utils.get_param_value(
672
+ Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY
673
+ )
674
+ default_not_present = exec_utils.get_param_value(
675
+ Parameters.DEFAULT_NOT_PRESENT, parameters, -1
676
+ )
677
+
678
+ activities_log = set()
679
+ for trace in log:
680
+ for event in trace:
681
+ activities_log.add(event[activity_key])
682
+ activities_log = sorted(list(activities_log))
683
+
684
+ data = []
685
+ feature_names = []
686
+ for act in activities_log:
687
+ feature_names.append("firstIndexAct@@" + act)
688
+ feature_names.append("lastIndexAct@@" + act)
689
+ for trace in log:
690
+ data.append([])
691
+
692
+ first_occ = {}
693
+ last_occ = {}
694
+ for index, event in enumerate(trace):
695
+ act = event[activity_key]
696
+ last_occ[act] = index
697
+ if act not in first_occ:
698
+ first_occ[act] = index
699
+ for act in activities_log:
700
+ if act not in first_occ:
701
+ data[-1].append(float(default_not_present))
702
+ data[-1].append(float(default_not_present))
703
+ else:
704
+ data[-1].append(float(first_occ[act]))
705
+ data[-1].append(float(last_occ[act]))
706
+
707
+ return data, feature_names
708
+
709
+
710
+ def case_duration(
711
+ log: EventLog,
712
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
713
+ ) -> Tuple[Any, List[str]]:
714
+ """
715
+ Calculates for each case, the case duration (and adds it as a feature)
716
+
717
+ Parameters
718
+ -----------------
719
+ log
720
+ Event log
721
+ parameters
722
+ Parameters of the algorithm
723
+
724
+ Returns
725
+ ----------------
726
+ data
727
+ Numeric value of the features
728
+ feature_names
729
+ Names of the features
730
+ """
731
+ if parameters is None:
732
+ parameters = {}
733
+
734
+ start_timestamp_key = exec_utils.get_param_value(
735
+ Parameters.START_TIMESTAMP_KEY,
736
+ parameters,
737
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
738
+ )
739
+ timestamp_key = exec_utils.get_param_value(
740
+ Parameters.TIMESTAMP_KEY,
741
+ parameters,
742
+ xes_constants.DEFAULT_TIMESTAMP_KEY,
743
+ )
744
+
745
+ feature_names = ["@@caseDuration"]
746
+ data = []
747
+ for trace in log:
748
+ if trace:
749
+ data.append(
750
+ [
751
+ float(
752
+ trace[-1][timestamp_key].timestamp()
753
+ - trace[0][start_timestamp_key].timestamp()
754
+ )
755
+ ]
756
+ )
757
+ else:
758
+ data.append([0.0])
759
+
760
+ return data, feature_names
761
+
762
+
763
+ def get_string_trace_attribute_rep(trace: Trace, trace_attribute: str) -> str:
764
+ """
765
+ Get a representation of the feature name associated to a string trace attribute value
766
+
767
+ Parameters
768
+ ------------
769
+ trace
770
+ Trace of the log
771
+ trace_attribute
772
+ Attribute of the trace to consider
773
+
774
+ Returns
775
+ ------------
776
+ rep
777
+ Representation of the feature name associated to a string trace attribute value
778
+ """
779
+ if trace_attribute in trace.attributes:
780
+ return (
781
+ "trace:"
782
+ + str(trace_attribute)
783
+ + "@"
784
+ + str(trace.attributes[trace_attribute])
785
+ )
786
+ return "trace:" + str(trace_attribute) + "@UNDEFINED"
787
+
788
+
789
+ def get_all_string_trace_attribute_values(
790
+ log: EventLog, trace_attribute: str
791
+ ) -> List[str]:
792
+ """
793
+ Get all string trace attribute values representations for a log
794
+
795
+ Parameters
796
+ ------------
797
+ log
798
+ Trace log
799
+ trace_attribute
800
+ Attribute of the trace to consider
801
+
802
+ Returns
803
+ ------------
804
+ list
805
+ List containing for each trace a representation of the feature name associated to the attribute
806
+ """
807
+ values = set()
808
+ for trace in log:
809
+ values.add(get_string_trace_attribute_rep(trace, trace_attribute))
810
+ return list(sorted(values))
811
+
812
+
813
+ def get_string_event_attribute_rep(event: Event, event_attribute: str) -> str:
814
+ """
815
+ Get a representation of the feature name associated to a string event attribute value
816
+
817
+ Parameters
818
+ ------------
819
+ event
820
+ Single event of a trace
821
+ event_attribute
822
+ Event attribute to consider
823
+
824
+ Returns
825
+ ------------
826
+ rep
827
+ Representation of the feature name associated to a string event attribute value
828
+ """
829
+ return "event:" + str(event_attribute) + "@" + str(event[event_attribute])
830
+
831
+
832
+ def get_values_event_attribute_for_trace(
833
+ trace: Trace, event_attribute: str
834
+ ) -> Set[str]:
835
+ """
836
+ Get all the representations for the events of a trace associated to a string event attribute values
837
+
838
+ Parameters
839
+ -------------
840
+ trace
841
+ Trace of the log
842
+ event_attribute
843
+ Event attribute to consider
844
+
845
+ Returns
846
+ -------------
847
+ values
848
+ All feature names present for the given attribute in the given trace
849
+ """
850
+ values_trace = set()
851
+ for event in trace:
852
+ if event_attribute in event:
853
+ values_trace.add(
854
+ get_string_event_attribute_rep(event, event_attribute)
855
+ )
856
+ if not values_trace:
857
+ values_trace.add("event:" + str(event_attribute) + "@UNDEFINED")
858
+ return values_trace
859
+
860
+
861
+ def get_all_string_event_attribute_values(
862
+ log: EventLog, event_attribute: str
863
+ ) -> List[str]:
864
+ """
865
+ Get all the representations for all the traces of the log associated to a string event attribute values
866
+
867
+ Parameters
868
+ ------------
869
+ log
870
+ Trace of the log
871
+ event_attribute
872
+ Event attribute to consider
873
+
874
+ Returns
875
+ ------------
876
+ values
877
+ All feature names present for the given attribute in the given log
878
+ """
879
+ values = set()
880
+ for trace in log:
881
+ values = values.union(
882
+ get_values_event_attribute_for_trace(trace, event_attribute)
883
+ )
884
+ return list(sorted(values))
885
+
886
+
887
+ def get_string_event_attribute_succession_rep(
888
+ event1: Event, event2: Event, event_attribute: str
889
+ ) -> str:
890
+ """
891
+ Get a representation of the feature name associated to a string event attribute value
892
+
893
+ Parameters
894
+ ------------
895
+ event1
896
+ First event of the succession
897
+ event2
898
+ Second event of the succession
899
+ event_attribute
900
+ Event attribute to consider
901
+
902
+ Returns
903
+ ------------
904
+ rep
905
+ Representation of the feature name associated to a string event attribute value
906
+ """
907
+ return (
908
+ "succession:"
909
+ + str(event_attribute)
910
+ + "@"
911
+ + str(event1[event_attribute])
912
+ + "#"
913
+ + str(event2[event_attribute])
914
+ )
915
+
916
+
917
+ def get_values_event_attribute_succession_for_trace(
918
+ trace: Trace, event_attribute: str
919
+ ) -> Set[str]:
920
+ """
921
+ Get all the representations for the events of a trace associated to a string event attribute succession values
922
+
923
+ Parameters
924
+ -------------
925
+ trace
926
+ Trace of the log
927
+ event_attribute
928
+ Event attribute to consider
929
+
930
+ Returns
931
+ -------------
932
+ values
933
+ All feature names present for the given attribute succession in the given trace
934
+ """
935
+ values_trace = set()
936
+ for i in range(len(trace) - 1):
937
+ event1 = trace[i]
938
+ event2 = trace[i + 1]
939
+ if event_attribute in event1 and event_attribute in event2:
940
+ values_trace.add(
941
+ get_string_event_attribute_succession_rep(
942
+ event1, event2, event_attribute
943
+ )
944
+ )
945
+ if not values_trace:
946
+ values_trace.add("succession:" + str(event_attribute) + "@UNDEFINED")
947
+ return values_trace
948
+
949
+
950
+ def get_all_string_event_succession_attribute_values(
951
+ log: EventLog, event_attribute: str
952
+ ) -> List[str]:
953
+ """
954
+ Get all the representations for all the traces of the log associated to a string event attribute succession values
955
+
956
+ Parameters
957
+ ------------
958
+ log
959
+ Trace of the log
960
+ event_attribute
961
+ Event attribute to consider
962
+
963
+ Returns
964
+ ------------
965
+ values
966
+ All feature names present for the given attribute succession in the given log
967
+ """
968
+ values = set()
969
+ for trace in log:
970
+ values = values.union(
971
+ get_values_event_attribute_succession_for_trace(
972
+ trace, event_attribute
973
+ )
974
+ )
975
+ return list(sorted(values))
976
+
977
+
978
+ def get_numeric_trace_attribute_rep(trace_attribute: str) -> str:
979
+ """
980
+ Get the feature name associated to a numeric trace attribute
981
+
982
+ Parameters
983
+ ------------
984
+ trace_attribute
985
+ Name of the trace attribute
986
+
987
+ Returns
988
+ ------------
989
+ feature_name
990
+ Name of the feature
991
+ """
992
+ return "trace:" + trace_attribute
993
+
994
+
995
+ def get_numeric_trace_attribute_value(
996
+ trace: Trace, trace_attribute: str
997
+ ) -> Union[int, float]:
998
+ """
999
+ Get the value of a numeric trace attribute from a given trace
1000
+
1001
+ Parameters
1002
+ ------------
1003
+ trace
1004
+ Trace of the log
1005
+
1006
+ Returns
1007
+ ------------
1008
+ value
1009
+ Value of the numeric trace attribute for the given trace
1010
+ """
1011
+ if trace_attribute in trace.attributes:
1012
+ return float(trace.attributes[trace_attribute])
1013
+ raise Exception(
1014
+ "at least a trace without trace attribute: " + trace_attribute
1015
+ )
1016
+
1017
+
1018
+ def get_numeric_event_attribute_rep(event_attribute: str) -> str:
1019
+ """
1020
+ Get the feature name associated to a numeric event attribute
1021
+
1022
+ Parameters
1023
+ ------------
1024
+ event_attribute
1025
+ Name of the event attribute
1026
+
1027
+ Returns
1028
+ -------------
1029
+ feature_name
1030
+ Name of the feature
1031
+ """
1032
+ return "event:" + event_attribute
1033
+
1034
+
1035
+ def get_numeric_event_attribute_value(
1036
+ event: Event, event_attribute: str
1037
+ ) -> Union[int, float]:
1038
+ """
1039
+ Get the value of a numeric event attribute from a given event
1040
+
1041
+ Parameters
1042
+ -------------
1043
+ event
1044
+ Event
1045
+
1046
+ Returns
1047
+ -------------
1048
+ value
1049
+ Value of the numeric event attribute for the given event
1050
+ """
1051
+ if event_attribute in event:
1052
+ return float(event[event_attribute])
1053
+ return None
1054
+
1055
+
1056
+ def get_numeric_event_attribute_value_trace(
1057
+ trace: Trace, event_attribute: str
1058
+ ) -> Union[int, float]:
1059
+ """
1060
+ Get the value of the last occurrence of a numeric event attribute given a trace
1061
+
1062
+ Parameters
1063
+ -------------
1064
+ trace
1065
+ Trace of the log
1066
+
1067
+ Returns
1068
+ -------------
1069
+ value
1070
+ Value of the last occurrence of a numeric trace attribute for the given trace
1071
+ """
1072
+ non_zero_values = []
1073
+ for event in trace:
1074
+ value = get_numeric_event_attribute_value(event, event_attribute)
1075
+ if value is not None:
1076
+ non_zero_values.append(value)
1077
+ if len(non_zero_values) > 0:
1078
+ return non_zero_values[-1]
1079
+ raise Exception(
1080
+ "at least a trace without any event with event attribute: "
1081
+ + event_attribute
1082
+ )
1083
+
1084
+
1085
+ def get_default_representation_with_attribute_names(
1086
+ log: EventLog,
1087
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
1088
+ feature_names: Optional[List[str]] = None,
1089
+ ) -> Tuple[Any, List[str], List[str], List[str], List[str], List[str]]:
1090
+ """
1091
+ Gets the default data representation of an event log (for process tree building)
1092
+ returning also the attribute names
1093
+
1094
+ Parameters
1095
+ -------------
1096
+ log
1097
+ Trace log
1098
+ parameters
1099
+ Possible parameters of the algorithm
1100
+ feature_names
1101
+ (If provided) Feature to use in the representation of the log
1102
+
1103
+ Returns
1104
+ -------------
1105
+ data
1106
+ Data to provide for decision tree learning
1107
+ feature_names
1108
+ Names of the features, in order
1109
+ """
1110
+ from pm4py.statistics.attributes.log.select import (
1111
+ select_attributes_from_log_for_tree,
1112
+ )
1113
+
1114
+ if parameters is None:
1115
+ parameters = {}
1116
+
1117
+ enable_activity_def_representation = exec_utils.get_param_value(
1118
+ Parameters.ENABLE_ACTIVITY_DEF_REPRESENTATION, parameters, False
1119
+ )
1120
+ enable_succ_def_representation = exec_utils.get_param_value(
1121
+ Parameters.ENABLE_SUCC_DEF_REPRESENTATION, parameters, False
1122
+ )
1123
+
1124
+ activity_key = (
1125
+ parameters[constants.PARAMETER_CONSTANT_ACTIVITY_KEY]
1126
+ if constants.PARAMETER_CONSTANT_ACTIVITY_KEY in parameters
1127
+ else xes.DEFAULT_NAME_KEY
1128
+ )
1129
+ blacklist = parameters["blacklist"] if "blacklist" in parameters else []
1130
+
1131
+ str_tr_attr, str_ev_attr, num_tr_attr, num_ev_attr = (
1132
+ select_attributes_from_log_for_tree(log)
1133
+ )
1134
+ str_evsucc_attr = None
1135
+
1136
+ if enable_succ_def_representation:
1137
+ str_evsucc_attr = [activity_key]
1138
+ if enable_activity_def_representation and activity_key not in str_ev_attr:
1139
+ str_ev_attr.append(activity_key)
1140
+
1141
+ str_tr_attr = [x for x in str_tr_attr if x not in blacklist]
1142
+ str_ev_attr = [x for x in str_ev_attr if x not in blacklist]
1143
+ num_tr_attr = [x for x in num_tr_attr if x not in blacklist]
1144
+ num_ev_attr = [x for x in num_ev_attr if x not in blacklist]
1145
+ if str_evsucc_attr is not None:
1146
+ str_evsucc_attr = [x for x in str_evsucc_attr if x not in blacklist]
1147
+
1148
+ data, feature_names = get_representation(
1149
+ log,
1150
+ str_tr_attr,
1151
+ str_ev_attr,
1152
+ num_tr_attr,
1153
+ num_ev_attr,
1154
+ str_evsucc_attr=str_evsucc_attr,
1155
+ feature_names=feature_names,
1156
+ )
1157
+
1158
+ return (
1159
+ data,
1160
+ feature_names,
1161
+ str_tr_attr,
1162
+ str_ev_attr,
1163
+ num_tr_attr,
1164
+ num_ev_attr,
1165
+ )
1166
+
1167
+
1168
+ def get_default_representation(
1169
+ log: EventLog,
1170
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
1171
+ feature_names: Optional[List[str]] = None,
1172
+ ) -> Tuple[Any, List[str]]:
1173
+ """
1174
+ Gets the default data representation of an event log (for process tree building)
1175
+
1176
+ Parameters
1177
+ -------------
1178
+ log
1179
+ Trace log
1180
+ parameters
1181
+ Possible parameters of the algorithm
1182
+ feature_names
1183
+ (If provided) Feature to use in the representation of the log
1184
+
1185
+ Returns
1186
+ -------------
1187
+ data
1188
+ Data to provide for decision tree learning
1189
+ feature_names
1190
+ Names of the features, in order
1191
+ """
1192
+ from pm4py.statistics.attributes.log.select import (
1193
+ select_attributes_from_log_for_tree,
1194
+ )
1195
+
1196
+ if parameters is None:
1197
+ parameters = {}
1198
+
1199
+ enable_activity_def_representation = exec_utils.get_param_value(
1200
+ Parameters.ENABLE_ACTIVITY_DEF_REPRESENTATION, parameters, True
1201
+ )
1202
+ enable_succ_def_representation = exec_utils.get_param_value(
1203
+ Parameters.ENABLE_SUCC_DEF_REPRESENTATION, parameters, True
1204
+ )
1205
+
1206
+ activity_key = (
1207
+ parameters[constants.PARAMETER_CONSTANT_ACTIVITY_KEY]
1208
+ if constants.PARAMETER_CONSTANT_ACTIVITY_KEY in parameters
1209
+ else xes.DEFAULT_NAME_KEY
1210
+ )
1211
+ blacklist = parameters["blacklist"] if "blacklist" in parameters else []
1212
+
1213
+ str_tr_attr, str_ev_attr, num_tr_attr, num_ev_attr = (
1214
+ select_attributes_from_log_for_tree(log)
1215
+ )
1216
+ str_evsucc_attr = None
1217
+
1218
+ if enable_succ_def_representation:
1219
+ str_evsucc_attr = [activity_key]
1220
+ if enable_activity_def_representation and activity_key not in str_ev_attr:
1221
+ str_ev_attr.append(activity_key)
1222
+
1223
+ str_tr_attr = [x for x in str_tr_attr if x not in blacklist]
1224
+ str_ev_attr = [x for x in str_ev_attr if x not in blacklist]
1225
+ num_tr_attr = [x for x in num_tr_attr if x not in blacklist]
1226
+ num_ev_attr = [x for x in num_ev_attr if x not in blacklist]
1227
+ if str_evsucc_attr is not None:
1228
+ str_evsucc_attr = [x for x in str_evsucc_attr if x not in blacklist]
1229
+
1230
+ return get_representation(
1231
+ log,
1232
+ str_tr_attr,
1233
+ str_ev_attr,
1234
+ num_tr_attr,
1235
+ num_ev_attr,
1236
+ str_evsucc_attr=str_evsucc_attr,
1237
+ feature_names=feature_names,
1238
+ )
1239
+
1240
+
1241
+ def get_representation(
1242
+ log: EventLog,
1243
+ str_tr_attr: List[str],
1244
+ str_ev_attr: List[str],
1245
+ num_tr_attr: List[str],
1246
+ num_ev_attr: List[str],
1247
+ str_evsucc_attr: Optional[List[str]] = None,
1248
+ feature_names: Optional[List[str]] = None,
1249
+ ) -> Tuple[Any, List[str]]:
1250
+ """
1251
+ Get a representation of the event log that is suited for the data part of the decision tree learning
1252
+
1253
+ NOTE: this function only encodes the last value seen for each attribute
1254
+
1255
+ Parameters
1256
+ -------------
1257
+ log
1258
+ Trace log
1259
+ str_tr_attr
1260
+ List of string trace attributes to consider in data vector creation
1261
+ str_ev_attr
1262
+ List of string event attributes to consider in data vector creation
1263
+ num_tr_attr
1264
+ List of numeric trace attributes to consider in data vector creation
1265
+ num_ev_attr
1266
+ List of numeric event attributes to consider in data vector creation
1267
+ str_evsucc_attr
1268
+ List of attributes succession of values to consider in data vector creation
1269
+ feature_names
1270
+ (If provided) Feature to use in the representation of the log
1271
+
1272
+ Returns
1273
+ -------------
1274
+ data
1275
+ Data to provide for decision tree learning
1276
+ feature_names
1277
+ Names of the features, in order
1278
+ """
1279
+ data = []
1280
+ dictionary = {}
1281
+ count = 0
1282
+ if feature_names is None:
1283
+ feature_names = []
1284
+ for trace_attribute in str_tr_attr:
1285
+ values = get_all_string_trace_attribute_values(
1286
+ log, trace_attribute
1287
+ )
1288
+ for value in values:
1289
+ dictionary[value] = count
1290
+ feature_names.append(value)
1291
+ count = count + 1
1292
+ for event_attribute in str_ev_attr:
1293
+ values = get_all_string_event_attribute_values(
1294
+ log, event_attribute
1295
+ )
1296
+ for value in values:
1297
+ dictionary[value] = count
1298
+ feature_names.append(value)
1299
+ count = count + 1
1300
+ for trace_attribute in num_tr_attr:
1301
+ dictionary[get_numeric_trace_attribute_rep(trace_attribute)] = (
1302
+ count
1303
+ )
1304
+ feature_names.append(
1305
+ get_numeric_trace_attribute_rep(trace_attribute)
1306
+ )
1307
+ count = count + 1
1308
+ for event_attribute in num_ev_attr:
1309
+ dictionary[get_numeric_event_attribute_rep(event_attribute)] = (
1310
+ count
1311
+ )
1312
+ feature_names.append(
1313
+ get_numeric_event_attribute_rep(event_attribute)
1314
+ )
1315
+ count = count + 1
1316
+ if str_evsucc_attr:
1317
+ for event_attribute in str_evsucc_attr:
1318
+ values = get_all_string_event_succession_attribute_values(
1319
+ log, event_attribute
1320
+ )
1321
+ for value in values:
1322
+ dictionary[value] = count
1323
+ feature_names.append(value)
1324
+ count = count + 1
1325
+ else:
1326
+ count = len(feature_names)
1327
+ for index, value in enumerate(feature_names):
1328
+ dictionary[value] = index
1329
+
1330
+ for trace in log:
1331
+ trace_rep = [0.0] * count
1332
+ for trace_attribute in str_tr_attr:
1333
+ trace_attr_rep = get_string_trace_attribute_rep(
1334
+ trace, trace_attribute
1335
+ )
1336
+ if trace_attr_rep in dictionary:
1337
+ trace_rep[dictionary[trace_attr_rep]] = 1.0
1338
+ for event_attribute in str_ev_attr:
1339
+ values = get_values_event_attribute_for_trace(
1340
+ trace, event_attribute
1341
+ )
1342
+ for value in values:
1343
+ if value in dictionary:
1344
+ trace_rep[dictionary[value]] = 1.0
1345
+ for trace_attribute in num_tr_attr:
1346
+ this_value = get_numeric_trace_attribute_rep(trace_attribute)
1347
+ if this_value in dictionary:
1348
+ trace_rep[dictionary[this_value]] = (
1349
+ get_numeric_trace_attribute_value(trace, trace_attribute)
1350
+ )
1351
+ for event_attribute in num_ev_attr:
1352
+ this_value = get_numeric_event_attribute_rep(event_attribute)
1353
+ if this_value in dictionary:
1354
+ trace_rep[dictionary[this_value]] = (
1355
+ get_numeric_event_attribute_value_trace(
1356
+ trace, event_attribute
1357
+ )
1358
+ )
1359
+ if str_evsucc_attr:
1360
+ for event_attribute in str_evsucc_attr:
1361
+ values = get_values_event_attribute_succession_for_trace(
1362
+ trace, event_attribute
1363
+ )
1364
+ for value in values:
1365
+ if value in dictionary:
1366
+ trace_rep[dictionary[value]] = 1.0
1367
+ data.append(trace_rep)
1368
+ # data = np.asarray(data)
1369
+ return data, feature_names
1370
+
1371
+
1372
+ def apply(
1373
+ log: EventLog,
1374
+ parameters: Optional[Dict[Union[str, Parameters], Any]] = None,
1375
+ ) -> Tuple[Any, List[str]]:
1376
+ """
1377
+ Encodes each trace as one feature vector.
1378
+
1379
+ From an event-log point of view, each case is summarized into a single row.
1380
+ String trace attributes and selected string event attributes become one-hot
1381
+ columns; selected numeric trace attributes and the last seen selected
1382
+ numeric event attributes become numeric columns. Optional extra features
1383
+ can add durations, activity positions, path times, concurrency, and
1384
+ workload measures.
1385
+
1386
+ Example with event attribute "concept:name":
1387
+ case 1: A, B, A
1388
+ case 2: A, C
1389
+
1390
+ The activity columns are [event:concept:name@A, event:concept:name@B,
1391
+ event:concept:name@C]. The encoded rows are:
1392
+ case 1 -> [1, 1, 0]
1393
+ case 2 -> [1, 0, 1]
1394
+
1395
+ This differs from count2vec because this legacy trace-based representation
1396
+ stores whether a selected string attribute value appears in the trace,
1397
+ not how many times it appears.
1398
+
1399
+ Parameters
1400
+ -----------------
1401
+ log
1402
+ Log
1403
+ parameters
1404
+ Parameters of the algorithm, including:
1405
+ - STR_TRACE_ATTRIBUTES => string trace attributes to consider in the features extraction
1406
+ - STR_EVENT_ATTRIBUTES => string event attributes to consider in the features extraction
1407
+ - NUM_TRACE_ATTRIBUTES => numeric trace attributes to consider in the features extraction
1408
+ - NUM_EVENT_ATTRIBUTES => numeric event attributes to consider in the features extraction
1409
+ - STR_EVSUCC_ATTRIBUTES => succession of event attributes to consider in the features extraction
1410
+ - FEATURE_NAMES => features to consider (in the given order)
1411
+ - ENABLE_ALL_EXTRA_FEATURES => enables all the extra features
1412
+ - ENABLE_CASE_DURATION => enables the case duration as additional feature
1413
+ - ENABLE_TIMES_FROM_FIRST_OCCURRENCE => enables the addition of the times from start of the case, to the end
1414
+ of the case, from the first occurrence of an activity of a case
1415
+ - ADD_CASE_IDENTIFIER_COLUMN => adds the case identifier (string) as column of the feature table (default: False)
1416
+ - ENABLE_NUMERIC_ATTRIBUTE_STATISTICS => for dataframe inputs, expands numeric attributes to aggregation columns
1417
+ - NUMERIC_ATTRIBUTE_AGGREGATIONS => collection of numeric aggregations to compute for attributes whose names
1418
+ do not start with @@: last, first, min, max, mean, median, stdev, and sum
1419
+ - ENABLE_TIMES_FROM_LAST_OCCURRENCE => enables the addition of the times from start of the case, to the end
1420
+ of the case, from the last occurrence of an activity of a case
1421
+ - ENABLE_DIRECT_PATHS_TIMES_LAST_OCC => add the duration of the last occurrence of a directed (i, i+1) path
1422
+ in the case as feature
1423
+ - ENABLE_INDIRECT_PATHS_TIMES_LAST_OCC => add the duration of the last occurrence of an indirect (i, j) path
1424
+ in the case as feature
1425
+ - ENABLE_WORK_IN_PROGRESS => enables the work in progress (number of concurrent cases) as a feature
1426
+ - ENABLE_RESOURCE_WORKLOAD => enables the resource workload as a feature
1427
+ - ENABLE_FIRST_LAST_ACTIVITY_INDEX => enables the insertion of the indexes of the activities as features
1428
+ - ENABLE_MAX_CONCURRENT_EVENTS => enables the count of the number of concurrent events inside a case
1429
+ - ENABLE_MAX_CONCURRENT_EVENTS_PER_ACTIVITY => enables the count of the number of concurrent events per activity
1430
+
1431
+ Returns
1432
+ -------------
1433
+ data
1434
+ Data to provide for decision tree learning
1435
+ feature_names
1436
+ Names of the features, in order
1437
+ """
1438
+ if parameters is None:
1439
+ parameters = {}
1440
+
1441
+ str_tr_attr = exec_utils.get_param_value(
1442
+ Parameters.STR_TRACE_ATTRIBUTES, parameters, None
1443
+ )
1444
+ num_tr_attr = exec_utils.get_param_value(
1445
+ Parameters.NUM_TRACE_ATTRIBUTES, parameters, None
1446
+ )
1447
+ str_ev_attr = exec_utils.get_param_value(
1448
+ Parameters.STR_EVENT_ATTRIBUTES, parameters, None
1449
+ )
1450
+ num_ev_attr = exec_utils.get_param_value(
1451
+ Parameters.NUM_EVENT_ATTRIBUTES, parameters, None
1452
+ )
1453
+ str_evsucc_attr = exec_utils.get_param_value(
1454
+ Parameters.STR_EVSUCC_ATTRIBUTES, parameters, None
1455
+ )
1456
+ feature_names = exec_utils.get_param_value(
1457
+ Parameters.FEATURE_NAMES, parameters, None
1458
+ )
1459
+
1460
+ at_least_one_provided = (
1461
+ (str_tr_attr is not None)
1462
+ or (num_tr_attr is not None)
1463
+ or (str_ev_attr is not None)
1464
+ or (num_ev_attr is not None)
1465
+ )
1466
+
1467
+ if str_tr_attr is None:
1468
+ str_tr_attr = []
1469
+
1470
+ if num_tr_attr is None:
1471
+ num_tr_attr = []
1472
+
1473
+ if str_ev_attr is None:
1474
+ str_ev_attr = []
1475
+
1476
+ if num_ev_attr is None:
1477
+ num_ev_attr = []
1478
+
1479
+ if pandas_utils.check_is_pandas_dataframe(log):
1480
+ case_attribute_prefix = exec_utils.get_param_value(
1481
+ Parameters.CASE_ATTRIBUTE_PREFIX, parameters, "case:"
1482
+ )
1483
+
1484
+ if str_tr_attr or num_tr_attr or str_ev_attr or num_ev_attr:
1485
+ columns = list(
1486
+ set([case_attribute_prefix + x for x in str_tr_attr])
1487
+ .union(set([case_attribute_prefix + x for x in num_tr_attr]))
1488
+ .union(set(str_ev_attr))
1489
+ .union(set(num_ev_attr))
1490
+ )
1491
+ if is_polars_lazyframe(log):
1492
+ from pm4py.objects.log.util import pl_lazy_fea_utils
1493
+ fea_df = pl_lazy_fea_utils.get_features_df(log, columns, parameters=parameters)
1494
+ else:
1495
+ fea_df = dataframe_utils.get_features_df(
1496
+ log, columns, parameters=parameters
1497
+ )
1498
+ if is_polars_lazyframe(fea_df):
1499
+ feature_names = list(fea_df.collect_schema().names())
1500
+ else:
1501
+ feature_names = list(fea_df.columns)
1502
+ else:
1503
+ if is_polars_lazyframe(log):
1504
+ from pm4py.objects.log.util import pl_lazy_fea_utils
1505
+ fea_df = pl_lazy_fea_utils.automatic_feature_extraction_df(log, parameters=parameters)
1506
+ else:
1507
+ fea_df = dataframe_utils.automatic_feature_extraction_df(
1508
+ log, parameters=parameters
1509
+ )
1510
+ if is_polars_lazyframe(fea_df):
1511
+ feature_names = list(fea_df.collect_schema().names())
1512
+ else:
1513
+ feature_names = list(fea_df.columns)
1514
+ return fea_df, feature_names
1515
+ else:
1516
+ enable_all = exec_utils.get_param_value(
1517
+ Parameters.ENABLE_ALL_EXTRA_FEATURES, parameters, False
1518
+ )
1519
+ case_id_key = exec_utils.get_param_value(
1520
+ Parameters.CASE_ID_KEY,
1521
+ parameters,
1522
+ xes_constants.DEFAULT_TRACEID_KEY,
1523
+ )
1524
+ add_case_identifier_column = exec_utils.get_param_value(
1525
+ Parameters.ADD_CASE_IDENTIFIER_COLUMN, parameters, False
1526
+ )
1527
+ enable_case_duration = exec_utils.get_param_value(
1528
+ Parameters.ENABLE_CASE_DURATION, parameters, enable_all
1529
+ )
1530
+ enable_times_from_first_occ = exec_utils.get_param_value(
1531
+ Parameters.ENABLE_TIMES_FROM_FIRST_OCCURRENCE,
1532
+ parameters,
1533
+ enable_all,
1534
+ )
1535
+ enable_times_from_last_occ = exec_utils.get_param_value(
1536
+ Parameters.ENABLE_TIMES_FROM_LAST_OCCURRENCE,
1537
+ parameters,
1538
+ enable_all,
1539
+ )
1540
+ enable_direct_paths_times_last_occ = exec_utils.get_param_value(
1541
+ Parameters.ENABLE_DIRECT_PATHS_TIMES_LAST_OCC,
1542
+ parameters,
1543
+ enable_all,
1544
+ )
1545
+ enable_indirect_paths_times_last_occ = exec_utils.get_param_value(
1546
+ Parameters.ENABLE_INDIRECT_PATHS_TIMES_LAST_OCC,
1547
+ parameters,
1548
+ enable_all,
1549
+ )
1550
+ enable_work_in_progress = exec_utils.get_param_value(
1551
+ Parameters.ENABLE_WORK_IN_PROGRESS, parameters, enable_all
1552
+ )
1553
+ enable_resource_workload = exec_utils.get_param_value(
1554
+ Parameters.ENABLE_RESOURCE_WORKLOAD, parameters, enable_all
1555
+ )
1556
+ enable_first_last_activity_index = exec_utils.get_param_value(
1557
+ Parameters.ENABLE_FIRST_LAST_ACTIVITY_INDEX, parameters, enable_all
1558
+ )
1559
+ enable_max_concurrent_events = exec_utils.get_param_value(
1560
+ Parameters.ENABLE_MAX_CONCURRENT_EVENTS, parameters, enable_all
1561
+ )
1562
+ enable_max_concurrent_events_per_activity = exec_utils.get_param_value(
1563
+ Parameters.ENABLE_MAX_CONCURRENT_EVENTS_PER_ACTIVITY,
1564
+ parameters,
1565
+ enable_all,
1566
+ )
1567
+
1568
+ log = converter.apply(
1569
+ log, variant=converter.Variants.TO_EVENT_LOG, parameters=parameters
1570
+ )
1571
+ if at_least_one_provided:
1572
+ datas, features_namess = get_representation(
1573
+ log,
1574
+ str_tr_attr,
1575
+ str_ev_attr,
1576
+ num_tr_attr,
1577
+ num_ev_attr,
1578
+ str_evsucc_attr=str_evsucc_attr,
1579
+ feature_names=feature_names,
1580
+ )
1581
+ else:
1582
+ datas, features_namess = get_default_representation(
1583
+ log, parameters=parameters
1584
+ )
1585
+
1586
+ if add_case_identifier_column:
1587
+ for i in range(len(datas)):
1588
+ datas[i] = [log[i].attributes[case_id_key]] + datas[i]
1589
+ features_namess = ["@@case_id_column"] + features_namess
1590
+
1591
+ # add additional features
1592
+
1593
+ if enable_case_duration:
1594
+ data, features_names = case_duration(log, parameters=parameters)
1595
+ for i in range(len(datas)):
1596
+ datas[i] = datas[i] + data[i]
1597
+ features_namess = features_namess + features_names
1598
+
1599
+ if enable_times_from_first_occ:
1600
+ data, features_names = times_from_first_occurrence_activity_case(
1601
+ log, parameters=parameters
1602
+ )
1603
+ for i in range(len(datas)):
1604
+ datas[i] = datas[i] + data[i]
1605
+ features_namess = features_namess + features_names
1606
+
1607
+ if enable_times_from_last_occ:
1608
+ data, features_names = times_from_last_occurrence_activity_case(
1609
+ log, parameters=parameters
1610
+ )
1611
+ for i in range(len(datas)):
1612
+ datas[i] = datas[i] + data[i]
1613
+ features_namess = features_namess + features_names
1614
+
1615
+ if enable_direct_paths_times_last_occ:
1616
+ data, features_names = direct_paths_times_last_occ(
1617
+ log, parameters=parameters
1618
+ )
1619
+ for i in range(len(datas)):
1620
+ datas[i] = datas[i] + data[i]
1621
+ features_namess = features_namess + features_names
1622
+
1623
+ if enable_indirect_paths_times_last_occ:
1624
+ data, features_names = indirect_paths_times_last_occ(
1625
+ log, parameters=parameters
1626
+ )
1627
+ for i in range(len(datas)):
1628
+ datas[i] = datas[i] + data[i]
1629
+ features_namess = features_namess + features_names
1630
+
1631
+ if enable_work_in_progress:
1632
+ data, features_names = work_in_progress(log, parameters=parameters)
1633
+ for i in range(len(datas)):
1634
+ datas[i] = datas[i] + data[i]
1635
+ features_namess = features_namess + features_names
1636
+
1637
+ if enable_resource_workload:
1638
+ data, features_names = resource_workload(
1639
+ log, parameters=parameters
1640
+ )
1641
+ for i in range(len(datas)):
1642
+ datas[i] = datas[i] + data[i]
1643
+ features_namess = features_namess + features_names
1644
+
1645
+ if enable_first_last_activity_index:
1646
+ data, features_names = first_last_activity_index_trace(
1647
+ log, parameters=parameters
1648
+ )
1649
+ for i in range(len(datas)):
1650
+ datas[i] = datas[i] + data[i]
1651
+ features_namess = features_namess + features_names
1652
+
1653
+ if enable_max_concurrent_events:
1654
+ data, features_names = max_concurrent_events(
1655
+ log, parameters=parameters
1656
+ )
1657
+ for i in range(len(datas)):
1658
+ datas[i] = datas[i] + data[i]
1659
+ features_namess = features_namess + features_names
1660
+
1661
+ if enable_max_concurrent_events_per_activity:
1662
+ data, features_names = max_concurrent_events_per_activity(
1663
+ log, parameters=parameters
1664
+ )
1665
+ for i in range(len(datas)):
1666
+ datas[i] = datas[i] + data[i]
1667
+ features_namess = features_namess + features_names
1668
+
1669
+ return datas, features_namess
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/algo/transformation/trace_encodings/variants/word2vec.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ """
23
+ Trace-level Word2Vec encoding.
24
+
25
+ From an event-log point of view, each case is treated as a short sentence and
26
+ each event token is treated as a word. A Word2Vec model learns a vector for
27
+ each token from the neighboring tokens observed in the traces. A trace vector
28
+ is then obtained by aggregating the token vectors in that trace.
29
+
30
+ Example with activity tokens:
31
+ case 1: A, B, C
32
+ case 2: A, B, D
33
+
34
+ Word2Vec learns vectors for A, B, C, and D from their contexts. The trace
35
+ vector for case 1 is, by default, the mean of vectors A, B, and C.
36
+
37
+ Reference:
38
+ Tavares, G. M., Oyamada, R. S., Barbon Junior, S., and Ceravolo, P.
39
+ "Trace encoding in process mining: A survey and benchmarking."
40
+ Engineering Applications of Artificial Intelligence, 126, 107028, 2023.
41
+ https://doi.org/10.1016/j.engappai.2023.107028
42
+
43
+ This variant delegates model training/inference to gensim's maintained
44
+ Word2Vec implementation.
45
+ """
46
+
47
+ from enum import Enum
48
+ from typing import Any, Dict, Optional, Union
49
+
50
+ import numpy as np
51
+ import pandas as pd
52
+
53
+ from pm4py.objects.log.obj import EventLog, EventStream
54
+ from pm4py.algo.transformation.trace_encodings.util import trace_text
55
+ from pm4py.util import exec_utils
56
+
57
+
58
+ class Parameters(Enum):
59
+ EVENT_ATTRIBUTES = "event_attributes"
60
+ TRACE_ATTRIBUTES = "trace_attributes"
61
+ MODEL = "model"
62
+ VECTOR_SIZE = "vector_size"
63
+ WINDOW = "window"
64
+ MIN_COUNT = "min_count"
65
+ WORKERS = "workers"
66
+ EPOCHS = "epochs"
67
+ SG = "sg"
68
+ AGGREGATION = "aggregation"
69
+
70
+
71
+ def _aggregate(vectors, vector_size, aggregation):
72
+ if not vectors:
73
+ return [0.0] * vector_size
74
+
75
+ matrix = np.asarray(vectors, dtype=float)
76
+ if aggregation == "sum":
77
+ return matrix.sum(axis=0).tolist()
78
+ return matrix.mean(axis=0).tolist()
79
+
80
+
81
+ def apply(
82
+ log: Union[EventLog, EventStream, pd.DataFrame],
83
+ parameters: Optional[Dict[Any, Any]] = None,
84
+ ):
85
+ """
86
+ Encodes each trace by aggregating gensim Word2Vec token vectors.
87
+
88
+ Parameters
89
+ ----------
90
+ log
91
+ Event log, event stream, or dataframe containing traces.
92
+ parameters
93
+ Parameters of the encoding. Common options:
94
+ - EVENT_ATTRIBUTES: event attributes used to form tokens. Defaults to
95
+ the activity attribute.
96
+ - TRACE_ATTRIBUTES: case attributes added as context tokens.
97
+ - MODEL: pre-trained gensim Word2Vec model. If omitted, a model is
98
+ trained on the provided log.
99
+ - VECTOR_SIZE, WINDOW, MIN_COUNT, WORKERS, EPOCHS, SG: gensim Word2Vec
100
+ training parameters.
101
+ - AGGREGATION: "mean" or "sum" token-vector aggregation.
102
+
103
+ Returns
104
+ -------
105
+ data
106
+ One row per trace, containing the aggregated Word2Vec dimensions.
107
+ feature_names
108
+ Dimension names corresponding to the columns of data.
109
+ """
110
+ if parameters is None:
111
+ parameters = {}
112
+
113
+ try:
114
+ from gensim.models import Word2Vec
115
+ except ImportError as exc:
116
+ raise ImportError(
117
+ "The WORD2VEC trace encoding uses gensim. Please install gensim "
118
+ "to use this variant."
119
+ ) from exc
120
+
121
+ _, traces = trace_text.log_to_trace_tokens(log, parameters=parameters)
122
+ vector_size = exec_utils.get_param_value(
123
+ Parameters.VECTOR_SIZE, parameters, 100
124
+ )
125
+ model = exec_utils.get_param_value(Parameters.MODEL, parameters, None)
126
+ aggregation = exec_utils.get_param_value(
127
+ Parameters.AGGREGATION, parameters, "mean"
128
+ )
129
+
130
+ if model is None:
131
+ model = Word2Vec(
132
+ sentences=traces,
133
+ vector_size=vector_size,
134
+ window=exec_utils.get_param_value(Parameters.WINDOW, parameters, 5),
135
+ min_count=exec_utils.get_param_value(Parameters.MIN_COUNT, parameters, 1),
136
+ workers=exec_utils.get_param_value(Parameters.WORKERS, parameters, 1),
137
+ sg=exec_utils.get_param_value(Parameters.SG, parameters, 1),
138
+ epochs=exec_utils.get_param_value(Parameters.EPOCHS, parameters, 10),
139
+ )
140
+ else:
141
+ vector_size = int(model.vector_size)
142
+
143
+ data = []
144
+ for trace in traces:
145
+ vectors = [model.wv[token] for token in trace if token in model.wv]
146
+ data.append(_aggregate(vectors, vector_size, aggregation))
147
+
148
+ feature_names = ["@@word2vec_dim_" + str(i) for i in range(vector_size)]
149
+ return data, feature_names
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/analysis.py ADDED
@@ -0,0 +1,980 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ __doc__ = """
23
+ """
24
+
25
+ from typing import List, Optional, Tuple, Dict, Union, Generator, Set, Any
26
+
27
+ from pm4py.objects.log.obj import Trace, EventLog, EventStream
28
+ from pm4py.utils import __event_log_deprecation_warning
29
+ from pm4py.objects.petri_net.obj import PetriNet, Marking
30
+ from pm4py.objects.process_tree.obj import ProcessTree
31
+ from pm4py.utils import get_properties, pandas_utils, constants
32
+ from pm4py.util.pandas_utils import check_is_pandas_dataframe, check_pandas_dataframe_columns
33
+ from pm4py.util import labels_similarity as ls_util
34
+ from pm4py.util import deprecation
35
+
36
+ import pandas as pd
37
+
38
+
39
+ @deprecation.deprecated(
40
+ deprecated_in="2.3.0",
41
+ removed_in="3.0.0",
42
+ details="this method will be removed in a future release.",
43
+ )
44
+ def construct_synchronous_product_net(
45
+ trace: Trace,
46
+ petri_net: PetriNet,
47
+ initial_marking: Marking,
48
+ final_marking: Marking,
49
+ ) -> Tuple[PetriNet, Marking, Marking]:
50
+ """
51
+ Constructs the synchronous product net between a trace and a Petri net process model.
52
+
53
+ :param trace: A trace from an event log.
54
+ :param petri_net: The Petri net process model.
55
+ :param initial_marking: The initial marking of the Petri net.
56
+ :param final_marking: The final marking of the Petri net.
57
+ :return: A tuple containing the synchronous Petri net, the initial marking, and the final marking.
58
+ :rtype: Tuple[PetriNet, ~pm4py.objects.petri_net.obj.Marking, ~pm4py.objects.petri_net.obj.Marking]
59
+
60
+ .. code-block:: python3
61
+
62
+ import pm4py
63
+
64
+ net, im, fm = pm4py.read_pnml('model.pnml')
65
+ log = pm4py.read_xes('log.xes')
66
+ sync_net, sync_im, sync_fm = pm4py.construct_synchronous_product_net(log[0], net, im, fm)
67
+ """
68
+ from pm4py.objects.petri_net.utils.petri_utils import construct_trace_net
69
+ from pm4py.objects.petri_net.utils.synchronous_product import construct
70
+ from pm4py.objects.petri_net.utils.align_utils import SKIP
71
+
72
+ trace_net, trace_im, trace_fm = construct_trace_net(trace)
73
+ sync_net, sync_im, sync_fm = construct(
74
+ trace_net,
75
+ trace_im,
76
+ trace_fm,
77
+ petri_net,
78
+ initial_marking,
79
+ final_marking,
80
+ SKIP,
81
+ )
82
+ return sync_net, sync_im, sync_fm
83
+
84
+
85
+ def compute_emd(
86
+ language1: Dict[List[str], float], language2: Dict[List[str], float]
87
+ ) -> float:
88
+ """
89
+ Computes the Earth Mover Distance (EMD) between two stochastic languages. For example, one language may be extracted from a log, and the other from a process model.
90
+
91
+ :param language1: The first stochastic language.
92
+ :param language2: The second stochastic language.
93
+ :return: The computed Earth Mover Distance.
94
+ :rtype: float
95
+
96
+ .. code-block:: python3
97
+
98
+ import pm4py
99
+
100
+ log = pm4py.read_xes('tests/input_data/running-example.xes')
101
+ language_log = pm4py.get_stochastic_language(log)
102
+ print(language_log)
103
+ net, im, fm = pm4py.read_pnml('tests/input_data/running-example.pnml')
104
+ language_model = pm4py.get_stochastic_language(net, im, fm)
105
+ print(language_model)
106
+ emd_distance = pm4py.compute_emd(language_log, language_model)
107
+ print(emd_distance)
108
+ """
109
+ from pm4py.algo.evaluation.earth_mover_distance import (
110
+ algorithm as earth_mover_distance,
111
+ )
112
+
113
+ return earth_mover_distance.apply(language1, language2)
114
+
115
+
116
+ def solve_marking_equation(
117
+ petri_net: PetriNet,
118
+ initial_marking: Marking,
119
+ final_marking: Marking,
120
+ cost_function: Dict[PetriNet.Transition, float] = None,
121
+ ) -> float:
122
+ """
123
+ Solves the marking equation of a Petri net using an Integer Linear Programming (ILP) approach. An optional transition-based cost function can be provided to minimize the solution.
124
+
125
+ :param petri_net: The Petri net.
126
+ :param initial_marking: The initial marking of the Petri net.
127
+ :param final_marking: The final marking of the Petri net.
128
+ :param cost_function: (Optional) A dictionary mapping transitions to their associated costs. If not provided, a default cost of 1 is assigned to each transition.
129
+ :return: The heuristic value obtained by solving the marking equation.
130
+ :rtype: float
131
+
132
+ .. code-block:: python3
133
+
134
+ import pm4py
135
+
136
+ net, im, fm = pm4py.read_pnml('model.pnml')
137
+ heuristic = pm4py.solve_marking_equation(net, im, fm)
138
+ """
139
+ from pm4py.algo.analysis.marking_equation import (
140
+ algorithm as marking_equation,
141
+ )
142
+
143
+ if cost_function is None:
144
+ cost_function = {t: 1 for t in petri_net.transitions}
145
+
146
+ me = marking_equation.build(
147
+ petri_net,
148
+ initial_marking,
149
+ final_marking,
150
+ parameters={"costs": cost_function},
151
+ )
152
+ return marking_equation.get_h_value(me)
153
+
154
+
155
+ @deprecation.deprecated(
156
+ deprecated_in="2.3.0",
157
+ removed_in="3.0.0",
158
+ details="this method will be removed in a future release.",
159
+ )
160
+ def solve_extended_marking_equation(
161
+ trace: Trace,
162
+ sync_net: PetriNet,
163
+ sync_im: Marking,
164
+ sync_fm: Marking,
165
+ split_points: Optional[List[int]] = None,
166
+ ) -> float:
167
+ """
168
+ Computes a heuristic value (an underestimation of the cost of an alignment) between a trace
169
+ and a synchronous product net using the extended marking equation with the standard cost function.
170
+ For example, synchronization moves have a cost of 0, invisible moves have a cost of 1,
171
+ and other moves on the model or log have a cost of 10,000. This method provides optimal provisioning of the split points.
172
+
173
+ :param trace: The trace to evaluate.
174
+ :param sync_net: The synchronous product net.
175
+ :param sync_im: The initial marking of the synchronous net.
176
+ :param sync_fm: The final marking of the synchronous net.
177
+ :param split_points: (Optional) The indices of the events in the trace to be used as split points. If not specified, the split points are identified automatically.
178
+ :return: The heuristic value representing the cost underestimation.
179
+ :rtype: float
180
+
181
+ .. code-block:: python3
182
+
183
+ import pm4py
184
+
185
+ net, im, fm = pm4py.read_pnml('model.pnml')
186
+ log = pm4py.read_xes('log.xes')
187
+ ext_mark_eq_heu = pm4py.solve_extended_marking_equation(log[0], net, im, fm)
188
+ """
189
+ from pm4py.algo.analysis.extended_marking_equation import (
190
+ algorithm as extended_marking_equation,
191
+ )
192
+
193
+ parameters = {}
194
+ if split_points is not None:
195
+ parameters[
196
+ extended_marking_equation.Variants.CLASSIC.value.Parameters.SPLIT_IDX
197
+ ] = split_points
198
+ me = extended_marking_equation.build(
199
+ trace, sync_net, sync_im, sync_fm, parameters=parameters
200
+ )
201
+ return extended_marking_equation.get_h_value(me)
202
+
203
+
204
+ def check_is_sound(petri_net: PetriNet,
205
+ initial_marking: Marking,
206
+ final_marking: Marking) -> bool:
207
+ """
208
+ Checks if a given Petri net is a sound Workflow net (WF-net).
209
+ Returns a boolean value.
210
+
211
+ A Petri net is a WF-net if and only if:
212
+
213
+ - It has a unique source place.
214
+ - It has a unique end place.
215
+ - Every element in the WF-net is on a path from the source to the sink place.
216
+
217
+ A WF-net is sound if and only if:
218
+
219
+ - It contains no live-locks.
220
+ - It contains no deadlocks.
221
+ - It is always possible to reach the final marking from any reachable marking.
222
+
223
+ :param petri_net: The Petri net to check.
224
+ :param initial_marking: The initial marking of the Petri net.
225
+ :param final_marking: The final marking of the Petri net.
226
+ :returns: boolean (True if the Petri net is sound)
227
+ """
228
+ try:
229
+ from pm4py.convert import convert_to_powl
230
+ powl_model = convert_to_powl(petri_net, initial_marking, final_marking)
231
+ return True
232
+ except:
233
+ pass
234
+
235
+ from pm4py.algo.analysis.woflan import algorithm as woflan
236
+ soundness = woflan.apply(
237
+ petri_net,
238
+ initial_marking,
239
+ final_marking,
240
+ parameters={
241
+ "return_asap_when_not_sound": True,
242
+ "return_diagnostics": True,
243
+ "print_diagnostics": False,
244
+ },
245
+ )
246
+
247
+ return soundness[0]
248
+
249
+
250
+ @deprecation.deprecated(
251
+ deprecated_in="2.3.0",
252
+ removed_in="3.0.0",
253
+ details="this method will be removed in a future release.",
254
+ )
255
+ def check_soundness(
256
+ petri_net: PetriNet,
257
+ initial_marking: Marking,
258
+ final_marking: Marking,
259
+ print_diagnostics: bool = False,
260
+ ) -> Tuple[bool, Dict[str, Any]]:
261
+ """
262
+ Checks if a given Petri net is a sound Workflow net (WF-net).
263
+
264
+ A Petri net is a WF-net if and only if:
265
+
266
+ - It has a unique source place.
267
+ - It has a unique end place.
268
+ - Every element in the WF-net is on a path from the source to the sink place.
269
+
270
+ A WF-net is sound if and only if:
271
+
272
+ - It contains no live-locks.
273
+ - It contains no deadlocks.
274
+ - It is always possible to reach the final marking from any reachable marking.
275
+
276
+ For a formal definition of a sound WF-net, refer to: http://www.padsweb.rwth-aachen.de/wvdaalst/publications/p628.pdf
277
+
278
+ The returned tuple consists of:
279
+
280
+ - A boolean indicating whether the Petri net is a sound WF-net.
281
+ - A dictionary containing diagnostics collected while running WOFLAN, associating diagnostic names with their corresponding details.
282
+
283
+ :param petri_net: The Petri net to check.
284
+ :param initial_marking: The initial marking of the Petri net.
285
+ :param final_marking: The final marking of the Petri net.
286
+ :param print_diagnostics: If True, additional diagnostics will be printed during the execution of WOFLAN.
287
+ :return: A tuple containing a boolean indicating soundness and a dictionary of diagnostics.
288
+ :rtype: Tuple[bool, Dict[str, Any]]
289
+
290
+ .. code-block:: python3
291
+
292
+ import pm4py
293
+
294
+ net, im, fm = pm4py.read_pnml('model.pnml')
295
+ is_sound = pm4py.check_soundness(net, im, fm)
296
+ """
297
+ from pm4py.algo.analysis.woflan import algorithm as woflan
298
+
299
+ return woflan.apply(
300
+ petri_net,
301
+ initial_marking,
302
+ final_marking,
303
+ parameters={
304
+ "return_asap_when_not_sound": True,
305
+ "return_diagnostics": True,
306
+ "print_diagnostics": print_diagnostics,
307
+ },
308
+ )
309
+
310
+
311
+ def cluster_log(
312
+ log: Union[EventLog, EventStream, pd.DataFrame],
313
+ sklearn_clusterer=None,
314
+ activity_key: str = "concept:name",
315
+ timestamp_key: str = "time:timestamp",
316
+ case_id_key: str = "case:concept:name",
317
+ ) -> Generator[EventLog, None, None]:
318
+ """
319
+ Applies clustering to the provided event log by extracting profiles for the log's traces and clustering them using a Scikit-Learn clusterer (default is K-Means with two clusters).
320
+
321
+ :param log: The event log to cluster.
322
+ :param sklearn_clusterer: (Optional) The Scikit-Learn clusterer to use. Default is KMeans with `n_clusters=2`, `random_state=0`, and `n_init="auto"`.
323
+ :param activity_key: The key used to identify activities in the log.
324
+ :param timestamp_key: The key used to identify timestamps in the log.
325
+ :param case_id_key: The key used to identify case IDs in the log.
326
+ :return: A generator that yields clustered event logs as pandas DataFrames.
327
+ :rtype: Generator[pd.DataFrame, None, None]
328
+
329
+ .. code-block:: python3
330
+
331
+ import pm4py
332
+
333
+ for clust_log in pm4py.cluster_log(df):
334
+ print(clust_log)
335
+ """
336
+ __event_log_deprecation_warning(log)
337
+
338
+ properties = get_properties(
339
+ log,
340
+ activity_key=activity_key,
341
+ case_id_key=case_id_key,
342
+ timestamp_key=timestamp_key,
343
+ )
344
+ if sklearn_clusterer is not None:
345
+ properties["sklearn_clusterer"] = sklearn_clusterer
346
+
347
+ from pm4py.algo.clustering.profiles import algorithm as clusterer
348
+
349
+ return clusterer.apply(log, parameters=properties)
350
+
351
+
352
+ def insert_artificial_start_end(
353
+ log: Union[EventLog, pd.DataFrame],
354
+ activity_key: str = "concept:name",
355
+ timestamp_key: str = "time:timestamp",
356
+ case_id_key: str = "case:concept:name",
357
+ artificial_start=constants.DEFAULT_ARTIFICIAL_START_ACTIVITY,
358
+ artificial_end=constants.DEFAULT_ARTIFICIAL_END_ACTIVITY,
359
+ ) -> Union[EventLog, pd.DataFrame]:
360
+ """
361
+ Inserts artificial start and end activities into an event log or a Pandas DataFrame.
362
+
363
+ :param log: The event log or Pandas DataFrame to modify.
364
+ :param activity_key: The attribute key used for activities.
365
+ :param timestamp_key: The attribute key used for timestamps.
366
+ :param case_id_key: The attribute key used to identify cases.
367
+ :param artificial_start: The symbol to use for the artificial start activity.
368
+ :param artificial_end: The symbol to use for the artificial end activity.
369
+ :return: The event log or Pandas DataFrame with artificial start and end activities inserted.
370
+ :rtype: Union[EventLog, pd.DataFrame]
371
+
372
+ .. code-block:: python3
373
+
374
+ import pm4py
375
+
376
+ dataframe = pm4py.insert_artificial_start_end(
377
+ dataframe,
378
+ activity_key='concept:name',
379
+ case_id_key='case:concept:name',
380
+ timestamp_key='time:timestamp'
381
+ )
382
+ """
383
+ __event_log_deprecation_warning(log)
384
+
385
+ properties = get_properties(
386
+ log,
387
+ activity_key=activity_key,
388
+ case_id_key=case_id_key,
389
+ timestamp_key=timestamp_key,
390
+ )
391
+ properties[constants.PARAM_ARTIFICIAL_START_ACTIVITY] = artificial_start
392
+ properties[constants.PARAM_ARTIFICIAL_END_ACTIVITY] = artificial_end
393
+
394
+ if check_is_pandas_dataframe(log):
395
+ check_pandas_dataframe_columns(
396
+ log,
397
+ activity_key=activity_key,
398
+ case_id_key=case_id_key,
399
+ timestamp_key=timestamp_key,
400
+ )
401
+ from pm4py.objects.log.util import dataframe_utils
402
+
403
+ return dataframe_utils.insert_artificial_start_end(
404
+ log, parameters=properties
405
+ )
406
+ else:
407
+ from pm4py.objects.log.util import artificial
408
+
409
+ return artificial.insert_artificial_start_end(
410
+ log, parameters=properties
411
+ )
412
+
413
+
414
+ def insert_case_service_waiting_time(
415
+ log: Union[EventLog, pd.DataFrame],
416
+ service_time_column: str = "@@service_time",
417
+ sojourn_time_column: str = "@@sojourn_time",
418
+ waiting_time_column: str = "@@waiting_time",
419
+ activity_key: str = "concept:name",
420
+ timestamp_key: str = "time:timestamp",
421
+ case_id_key: str = "case:concept:name",
422
+ start_timestamp_key: str = "time:timestamp",
423
+ ) -> pd.DataFrame:
424
+ """
425
+ Inserts service time, waiting time, and sojourn time information for each case into a Pandas DataFrame.
426
+
427
+ :param log: The event log or Pandas DataFrame to modify.
428
+ :param service_time_column: The name of the column to store service times.
429
+ :param sojourn_time_column: The name of the column to store sojourn times.
430
+ :param waiting_time_column: The name of the column to store waiting times.
431
+ :param activity_key: The attribute key used for activities.
432
+ :param timestamp_key: The attribute key used for timestamps.
433
+ :param case_id_key: The attribute key used to identify cases.
434
+ :param start_timestamp_key: The attribute key used for the start timestamp of cases.
435
+ :return: A Pandas DataFrame with the inserted service, waiting, and sojourn time columns.
436
+ :rtype: pd.DataFrame
437
+
438
+ .. code-block:: python3
439
+
440
+ import pm4py
441
+
442
+ dataframe = pm4py.insert_case_service_waiting_time(
443
+ dataframe,
444
+ activity_key='concept:name',
445
+ timestamp_key='time:timestamp',
446
+ case_id_key='case:concept:name',
447
+ start_timestamp_key='time:timestamp'
448
+ )
449
+ """
450
+ __event_log_deprecation_warning(log)
451
+
452
+ properties = get_properties(
453
+ log,
454
+ activity_key=activity_key,
455
+ case_id_key=case_id_key,
456
+ timestamp_key=timestamp_key,
457
+ )
458
+
459
+ from pm4py.objects.conversion.log import converter as log_converter
460
+
461
+ log_df = log_converter.apply(
462
+ log,
463
+ variant=log_converter.Variants.TO_DATA_FRAME,
464
+ parameters=properties,
465
+ )
466
+
467
+ return pandas_utils.insert_case_service_waiting_time(
468
+ log_df,
469
+ case_id_column=case_id_key,
470
+ timestamp_column=timestamp_key,
471
+ start_timestamp_column=start_timestamp_key,
472
+ service_time_column=service_time_column,
473
+ waiting_time_column=waiting_time_column,
474
+ sojourn_time_column=sojourn_time_column,
475
+ )
476
+
477
+
478
+ def insert_case_arrival_finish_rate(
479
+ log: Union[EventLog, pd.DataFrame],
480
+ arrival_rate_column: str = "@@arrival_rate",
481
+ finish_rate_column: str = "@@finish_rate",
482
+ activity_key: str = "concept:name",
483
+ timestamp_key: str = "time:timestamp",
484
+ case_id_key: str = "case:concept:name",
485
+ start_timestamp_key: str = "time:timestamp",
486
+ ) -> pd.DataFrame:
487
+ """
488
+ Inserts arrival and finish rate information for each case into a Pandas DataFrame.
489
+
490
+ The arrival rate is computed as the time difference between the start of the current case and the start of the previous case to start.
491
+ The finish rate is computed as the time difference between the end of the current case and the end of the next case to finish.
492
+
493
+ :param log: The event log or Pandas DataFrame to modify.
494
+ :param arrival_rate_column: The name of the column to store arrival rates.
495
+ :param finish_rate_column: The name of the column to store finish rates.
496
+ :param activity_key: The attribute key used for activities.
497
+ :param timestamp_key: The attribute key used for timestamps.
498
+ :param case_id_key: The attribute key used to identify cases.
499
+ :param start_timestamp_key: The attribute key used for the start timestamp of cases.
500
+ :return: A Pandas DataFrame with the inserted arrival and finish rate columns.
501
+ :rtype: pd.DataFrame
502
+
503
+ .. code-block:: python3
504
+
505
+ import pm4py
506
+
507
+ dataframe = pm4py.insert_case_arrival_finish_rate(
508
+ dataframe,
509
+ activity_key='concept:name',
510
+ timestamp_key='time:timestamp',
511
+ case_id_key='case:concept:name',
512
+ start_timestamp_key='time:timestamp'
513
+ )
514
+ """
515
+ __event_log_deprecation_warning(log)
516
+
517
+ properties = get_properties(
518
+ log,
519
+ activity_key=activity_key,
520
+ case_id_key=case_id_key,
521
+ timestamp_key=timestamp_key,
522
+ )
523
+
524
+ from pm4py.objects.conversion.log import converter as log_converter
525
+
526
+ log_df = log_converter.apply(
527
+ log,
528
+ variant=log_converter.Variants.TO_DATA_FRAME,
529
+ parameters=properties,
530
+ )
531
+
532
+ return pandas_utils.insert_case_arrival_finish_rate(
533
+ log_df,
534
+ case_id_column=case_id_key,
535
+ timestamp_column=timestamp_key,
536
+ start_timestamp_column=start_timestamp_key,
537
+ arrival_rate_column=arrival_rate_column,
538
+ finish_rate_column=finish_rate_column,
539
+ )
540
+
541
+
542
+ def check_is_workflow_net(net: PetriNet) -> bool:
543
+ """
544
+ Checks if the input Petri net satisfies the WF-net (Workflow net) conditions:
545
+ 1. It has a unique source place.
546
+ 2. It has a unique sink place.
547
+ 3. Every node is on a path from the source to the sink.
548
+
549
+ :param net: The Petri net to check.
550
+ :return: True if the Petri net is a WF-net, False otherwise.
551
+ :rtype: bool
552
+
553
+ .. code-block:: python3
554
+
555
+ import pm4py
556
+
557
+ net = pm4py.read_pnml('model.pnml')
558
+ is_wfnet = pm4py.check_is_workflow_net(net)
559
+ """
560
+ from pm4py.algo.analysis.workflow_net import algorithm
561
+
562
+ return algorithm.apply(net)
563
+
564
+
565
+ def maximal_decomposition(
566
+ net: PetriNet, im: Marking, fm: Marking
567
+ ) -> List[Tuple[PetriNet, Marking, Marking]]:
568
+ """
569
+ Calculates the maximal decomposition of an accepting Petri net into its maximal components.
570
+
571
+ :param net: The Petri net to decompose.
572
+ :param im: The initial marking of the Petri net.
573
+ :param fm: The final marking of the Petri net.
574
+ :return: A list of tuples, each containing a subnet Petri net, its initial marking, and its final marking.
575
+ :rtype: List[Tuple[PetriNet, ~pm4py.objects.petri_net.obj.Marking, ~pm4py.objects.petri_net.obj.Marking]]
576
+
577
+ .. code-block:: python3
578
+
579
+ import pm4py
580
+
581
+ net, im, fm = pm4py.read_pnml('model.pnml')
582
+ list_nets = pm4py.maximal_decomposition(net, im, fm)
583
+ for subnet, subim, subfm in list_nets:
584
+ pm4py.view_petri_net(subnet, subim, subfm, format='svg')
585
+ """
586
+ from pm4py.objects.petri_net.utils.decomposition import decompose
587
+
588
+ return decompose(net, im, fm)
589
+
590
+
591
+ def simplicity_petri_net(
592
+ net: PetriNet,
593
+ im: Marking,
594
+ fm: Marking,
595
+ variant: Optional[str] = "arc_degree",
596
+ ) -> float:
597
+ """
598
+ Computes the simplicity metric for a given Petri net model.
599
+
600
+ Three available approaches are supported:
601
+
602
+ - **Arc Degree Simplicity**: Described in the paper "ProDiGen: Mining complete, precise and minimal structure process models with a genetic algorithm." by Vázquez-Barreiros, Borja, Manuel Mucientes, and Manuel Lama. Information Sciences, 294 (2015): 315-333.
603
+ - **Extended Cardoso Metric**: Described in the paper "Complexity Metrics for Workflow Nets" by Lassen, Kristian Bisgaard, and Wil MP van der Aalst.
604
+ - **Extended Cyclomatic Metric**: Also described in the paper "Complexity Metrics for Workflow Nets" by Lassen, Kristian Bisgaard, and Wil MP van der Aalst.
605
+
606
+ :param net: The Petri net for which to compute simplicity.
607
+ :param im: The initial marking of the Petri net.
608
+ :param fm: The final marking of the Petri net.
609
+ :param variant: The simplicity metric variant to use ('arc_degree', 'extended_cardoso', 'extended_cyclomatic').
610
+ :return: The computed simplicity value.
611
+ :rtype: float
612
+
613
+ .. code-block:: python3
614
+
615
+ import pm4py
616
+
617
+ net, im, fm = pm4py.discover_petri_net_inductive(
618
+ dataframe,
619
+ activity_key='concept:name',
620
+ case_id_key='case:concept:name',
621
+ timestamp_key='time:timestamp'
622
+ )
623
+ simplicity = pm4py.simplicity_petri_net(net, im, fm, variant='arc_degree')
624
+ """
625
+ if variant == "arc_degree":
626
+ from pm4py.algo.evaluation.simplicity.variants import arc_degree
627
+
628
+ return arc_degree.apply(net)
629
+ elif variant == "extended_cardoso":
630
+ from pm4py.algo.evaluation.simplicity.variants import extended_cardoso
631
+
632
+ return extended_cardoso.apply(net)
633
+ elif variant == "extended_cyclomatic":
634
+ from pm4py.algo.evaluation.simplicity.variants import (
635
+ extended_cyclomatic,
636
+ )
637
+
638
+ return extended_cyclomatic.apply(net, im)
639
+
640
+
641
+ def generate_marking(
642
+ net: PetriNet,
643
+ place_or_dct_places: Union[
644
+ str, PetriNet.Place, Dict[str, int], Dict[PetriNet.Place, int]
645
+ ],
646
+ ) -> Marking:
647
+ """
648
+ Generates a marking for a given Petri net based on specified places and token counts.
649
+
650
+ :param net: The Petri net for which to generate the marking.
651
+ :param place_or_dct_places: Specifies the places and their token counts for the marking. It can be:
652
+
653
+ - A single `PetriNet.Place` object, which will have one token.
654
+ - A string representing the name of a place, which will have one token.
655
+ - A dictionary mapping `PetriNet.Place` objects to their respective number of tokens.
656
+ - A dictionary mapping place names (strings) to their respective number of tokens. :return: The generated ~pm4py.objects.petri_net.obj.Marking object. :rtype: ~pm4py.objects.petri_net.obj.Marking
657
+
658
+ .. code-block:: python3
659
+
660
+ import pm4py
661
+
662
+ net, im, fm = pm4py.read_pnml('model.pnml')
663
+ marking = pm4py.generate_marking(net, {'source': 2})
664
+ """
665
+ dct_places = {x.name: x for x in net.places}
666
+ if isinstance(place_or_dct_places, PetriNet.Place):
667
+ # A single Place object is specified for the marking
668
+ return Marking({place_or_dct_places: 1})
669
+ elif isinstance(place_or_dct_places, str):
670
+ # The name of a place is specified for the marking
671
+ return Marking({dct_places[place_or_dct_places]: 1})
672
+ elif isinstance(place_or_dct_places, dict):
673
+ dct_keys = list(place_or_dct_places)
674
+ if dct_keys:
675
+ if isinstance(dct_keys[0], PetriNet.Place):
676
+ # A dictionary mapping Place objects to token counts is
677
+ # specified
678
+ return Marking(place_or_dct_places)
679
+ elif isinstance(dct_keys[0], str):
680
+ # A dictionary mapping place names to token counts is specified
681
+ return Marking(
682
+ {dct_places[x]: y for x, y in place_or_dct_places.items()}
683
+ )
684
+
685
+
686
+ def reduce_petri_net_invisibles(net: PetriNet) -> PetriNet:
687
+ """
688
+ Reduces the number of invisible transitions in the provided Petri net.
689
+
690
+ :param net: The Petri net to be reduced.
691
+ :return: The reduced Petri net with fewer invisible transitions.
692
+ :rtype: PetriNet
693
+
694
+ .. code-block:: python3
695
+
696
+ import pm4py
697
+
698
+ net, im, fm = pm4py.read_pnml('model.pnml')
699
+ net = pm4py.reduce_petri_net_invisibles(net)
700
+ """
701
+ from pm4py.objects.petri_net.utils import reduction
702
+
703
+ return reduction.apply_simple_reduction(net)
704
+
705
+
706
+ def reduce_petri_net_implicit_places(
707
+ net: PetriNet, im: Marking, fm: Marking
708
+ ) -> Tuple[PetriNet, Marking, Marking]:
709
+ """
710
+ Reduces the number of implicit places in the provided Petri net.
711
+
712
+ :param net: The Petri net to be reduced.
713
+ :param im: The initial marking of the Petri net.
714
+ :param fm: The final marking of the Petri net.
715
+ :return: A tuple containing the reduced Petri net, its initial marking, and its final marking.
716
+ :rtype: Tuple[PetriNet, ~pm4py.objects.petri_net.obj.Marking, ~pm4py.objects.petri_net.obj.Marking]
717
+
718
+ .. code-block:: python3
719
+
720
+ import pm4py
721
+
722
+ net, im, fm = pm4py.read_pnml('model.pnml')
723
+ net, im, fm = pm4py.reduce_petri_net_implicit_places(net, im, fm)
724
+ """
725
+ from pm4py.objects.petri_net.utils import murata
726
+
727
+ return murata.apply_reduction(net, im, fm)
728
+
729
+
730
+ def get_enabled_transitions(
731
+ net: PetriNet, marking: Marking
732
+ ) -> Set[PetriNet.Transition]:
733
+ """
734
+ Retrieves the set of transitions that are enabled in a given marking of a Petri net.
735
+
736
+ :param net: The Petri net.
737
+ :param marking: The current marking of the Petri net.
738
+ :return: A set of transitions that are enabled in the provided marking.
739
+ :rtype: Set[PetriNet.Transition]
740
+
741
+ .. code-block:: python3
742
+
743
+ import pm4py
744
+
745
+ net, im, fm = pm4py.read_pnml('tests/input_data/running-example.pnml')
746
+ # Gets the transitions enabled in the initial marking
747
+ enabled_transitions = pm4py.get_enabled_transitions(net, im)
748
+ """
749
+ from pm4py.objects.petri_net import semantics
750
+
751
+ return semantics.enabled_transitions(net, marking)
752
+
753
+
754
+ def get_activity_labels(*args) -> List[str]:
755
+ """Gets the activity labels from the specified event log / process model.
756
+
757
+ Returns
758
+ ---------------
759
+ activities : list
760
+ Activity labels
761
+
762
+ """
763
+ import pm4py
764
+
765
+ if isinstance(args[0], EventLog):
766
+ labels = set(y["concept:name"] for x in args[0] for y in x)
767
+ elif isinstance(args[0], pd.DataFrame):
768
+ labels = set(args[0]["concept:name"].unique())
769
+ else:
770
+ net, im, fm = pm4py.convert_to_petri_net(*args)
771
+ labels = {x.label for x in net.transitions if x.label is not None}
772
+ return sorted(list(labels))
773
+
774
+
775
+ def replace_activity_labels(string_dictio, *args):
776
+ """
777
+ Replace the activity labels in the specified process model.
778
+
779
+ The first argument is the dictionary, i.e., {"pay": "pay
780
+ compensation", "reject": "reject request"} The rest is the
781
+ specification of the process model
782
+ """
783
+ from pm4py.objects.powl.obj import POWL
784
+ from pm4py.objects.bpmn.obj import BPMN
785
+
786
+ if isinstance(args[0], POWL):
787
+ from pm4py.objects.powl.utils import label_replacing
788
+ return label_replacing.apply(args[0], string_dictio)
789
+ elif isinstance(args[0], ProcessTree):
790
+ from pm4py.objects.process_tree.utils import label_replacing
791
+ return label_replacing.apply(args[0], string_dictio)
792
+ elif isinstance(args[0], PetriNet):
793
+ from pm4py.objects.petri_net.utils import label_replacing
794
+ return label_replacing.apply(args[0], args[1], args[2], string_dictio)
795
+ elif isinstance(args[0], BPMN):
796
+ from pm4py.objects.bpmn.util import label_replacing
797
+ return label_replacing.apply(args[0], string_dictio)
798
+ else:
799
+ raise Exception("unsupported.")
800
+
801
+
802
+ def __extract_models(*args) -> List[Any]:
803
+ if len(args) < 2:
804
+ raise Exception("Insufficient arguments provided.")
805
+
806
+ counter = 0
807
+ lst_models = []
808
+
809
+ import pm4py
810
+ for i in range(2):
811
+ if type(args[counter]) is PetriNet:
812
+ net, im, fm = args[counter:counter + 3]
813
+ lst_models.append([net, im, fm])
814
+ counter += 3
815
+ elif isinstance(args[counter], dict):
816
+ dfg, sa, ea = args[counter:counter + 3]
817
+ net, im, fm = pm4py.convert_to_petri_net(dfg, sa, ea)
818
+ lst_models.append([net, im, fm])
819
+ counter += 3
820
+ else:
821
+ obj = args[counter]
822
+ lst_models.append([obj])
823
+ counter += 1
824
+
825
+ return lst_models
826
+
827
+
828
+ def behavioral_similarity(*args) -> float:
829
+ """
830
+ Computes the behavioral similarity (footprints-based) between two process models.
831
+
832
+ Examples:
833
+
834
+ * pm4py.behavioral_similarity(petri_net, im, fm, process_tree)
835
+ * pm4py.behavioral_similarity(bpmn1, bpmn2)
836
+ * pm4py.behavioral_similarity(process_tree, powl)
837
+
838
+ Returns
839
+ --------------
840
+ similarity
841
+ Footprints-based behavioral similarity
842
+
843
+ """
844
+ lst_models = __extract_models(*args)
845
+
846
+ import pm4py
847
+ footprints = []
848
+ for i in range(len(lst_models)):
849
+ x = lst_models[i]
850
+ if not (isinstance(x[0], PetriNet) or isinstance(x[0], ProcessTree)):
851
+ x = [pm4py.convert_to_powl(*x)]
852
+
853
+ footprints.append(pm4py.discover_footprints(*x))
854
+
855
+ footprints1, footprints2 = footprints
856
+
857
+ sequence_union = footprints1["sequence"].union(footprints2["sequence"])
858
+ sequence_intersection = footprints1["sequence"].intersection(footprints2["sequence"])
859
+
860
+ parallel_union = footprints1["parallel"].union(footprints2["parallel"])
861
+ parallel_intersection = footprints1["parallel"].intersection(footprints2["parallel"])
862
+
863
+ denominator = len(sequence_union) + len(parallel_union)
864
+
865
+ if denominator == 0:
866
+ return 0
867
+ else:
868
+ return (len(sequence_intersection) + len(parallel_intersection)) / denominator
869
+
870
+
871
+ def structural_similarity(*args) -> float:
872
+ """
873
+ Computes the structural similarity between two semi-block-structured process models,
874
+ following an approach similar to:
875
+
876
+ Yan, Z., Dijkman, R., & Grefen, P. (2012). Fast business process similarity search.
877
+ Distributed and Parallel Databases, 30(2), 105–144.
878
+ (https://doi.org/10.1007/s10619-012-7089-z)
879
+
880
+ Examples:
881
+
882
+ * pm4py.structural_similarity(petri_net, im, fm, process_tree)
883
+ * pm4py.structural_similarity(bpmn1, bpmn2)
884
+ * pm4py.structural_similarity(process_tree, powl)
885
+
886
+ Returns
887
+ --------------
888
+ similarity
889
+ Structural similarity
890
+
891
+ """
892
+ lst_models = __extract_models(*args)
893
+
894
+ import pm4py
895
+ i = 0
896
+ while i < len(lst_models):
897
+ lst_models[i] = pm4py.convert_to_process_tree(pm4py.convert_to_powl(*lst_models[i]))
898
+ i = i + 1
899
+
900
+ from pm4py.objects.process_tree.utils import struct_similarity
901
+ return struct_similarity.structural_similarity(lst_models[0], lst_models[1])
902
+
903
+
904
+ def embeddings_similarity(*args) -> float:
905
+ """
906
+ Computes the embeddings similarity between two process models,
907
+ following the approach described in:
908
+
909
+ Colonna, Juan G., et al. "Process mining embeddings: Learning vector representations for Petri nets."
910
+ Intelligent Systems with Applications 23 (2024): 200423.
911
+
912
+ Examples:
913
+
914
+ * pm4py.embeddings_similarity(petri_net, im, fm, process_tree)
915
+ * pm4py.embeddings_similarity(bpmn1, bpmn2)
916
+ * pm4py.embeddings_similarity(process_tree, powl)
917
+
918
+ Returns
919
+ --------------
920
+ similarity
921
+ Structural similarity
922
+
923
+ """
924
+ lst_models = __extract_models(*args)
925
+
926
+ import pm4py
927
+ i = 0
928
+ while i < len(lst_models):
929
+ lst_models[i] = pm4py.convert_to_petri_net(*lst_models[i])
930
+ i = i + 1
931
+
932
+ from pm4py.objects.petri_net.utils import embeddings_similarity
933
+ return embeddings_similarity.apply(lst_models[0][0], lst_models[1][0])
934
+
935
+
936
+ def label_sets_similarity(*args, threshold=0.75) -> float:
937
+ """
938
+ Computes the label sets similarity between two process models.
939
+
940
+ Examples:
941
+
942
+ * pm4py.labels_similarity(petri_net, im, fm, process_tree)
943
+ * pm4py.labels_similarity(bpmn1, bpmn2)
944
+ * pm4py.labels_similarity(process_tree, powl)
945
+
946
+ Returns
947
+ --------------
948
+ similarity
949
+ Label sets similarity
950
+
951
+ """
952
+ lst_models = __extract_models(*args)
953
+ labels = []
954
+ i = 0
955
+ while i < len(lst_models):
956
+ labels.append(get_activity_labels(*lst_models[i]))
957
+ i = i + 1
958
+
959
+ return ls_util.label_sets_similarity(labels[0], labels[1], threshold=threshold)
960
+
961
+
962
+ def map_labels_from_second_model(*args, threshold=0.75):
963
+ """
964
+ Maps the labels from the second process model into the first.
965
+
966
+ Example usages:
967
+
968
+ * pm4py.map_labels_from_second_model(net, im, fm, process_tree)
969
+ * pm4py.map_labels_from_second_model(process_tree, net, im, fm)
970
+ * pm4py.map_labels_from_second_model(powl1, powl2)
971
+ """
972
+ lst_models = __extract_models(*args)
973
+ labels = []
974
+ i = 0
975
+ while i < len(lst_models):
976
+ labels.append(get_activity_labels(*lst_models[i]))
977
+ i = i + 1
978
+
979
+ label_mapping = ls_util.map_labels(labels[0], labels[1], threshold=threshold)
980
+ return replace_activity_labels(label_mapping, *lst_models[0])
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/cli.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+
23
+ import pm4py
24
+ import sys
25
+ import os
26
+ import itertools
27
+ from pathlib import Path
28
+ import traceback
29
+ import pandas as pd
30
+ from pm4py.util import constants, pandas_utils
31
+
32
+
33
+ methods = {
34
+ "ConvertToXES": {
35
+ "inputs": [".csv"],
36
+ "output_extension": ".xes",
37
+ "method": lambda x: pm4py.write_xes(
38
+ pm4py.convert_to_event_log(
39
+ pm4py.format_dataframe(pandas_utils.read_csv(x[0]))
40
+ ),
41
+ x[1],
42
+ ),
43
+ },
44
+ "ConvertToCSV": {
45
+ "inputs": [".xes"],
46
+ "output_extension": ".csv",
47
+ "method": lambda x: pm4py.convert_to_dataframe(
48
+ pm4py.read_xes(x[0])
49
+ ).to_csv(x[1], index=False),
50
+ },
51
+ "ConvertPNMLtoBPMN": {
52
+ "inputs": [".pnml"],
53
+ "output_extension": ".bpmn",
54
+ "method": lambda x: pm4py.write_bpmn(
55
+ pm4py.convert_to_bpmn(*pm4py.read_pnml(x[0])), x[1]
56
+ ),
57
+ },
58
+ "ConvertPNMLtoPTML": {
59
+ "inputs": [".pnml"],
60
+ "output_extension": ".ptml",
61
+ "method": lambda x: pm4py.write_ptml(
62
+ pm4py.convert_to_process_tree(*pm4py.read_pnml(x[0])), x[1]
63
+ ),
64
+ },
65
+ "ConvertPTMLtoPNML": {
66
+ "inputs": [".ptml"],
67
+ "output_extension": ".pnml",
68
+ "method": lambda x: pm4py.write_pnml(
69
+ *pm4py.convert_to_petri_net(pm4py.read_ptml(x[0])), x[1]
70
+ ),
71
+ },
72
+ "ConvertPTMLtoBPMN": {
73
+ "inputs": [".ptml"],
74
+ "output_extension": ".bpmn",
75
+ "method": lambda x: pm4py.write_bpmn(
76
+ pm4py.convert_to_bpmn(pm4py.read_ptml(x[0])), x[1]
77
+ ),
78
+ },
79
+ "ConvertBPMNtoPNML": {
80
+ "inputs": [".bpmn"],
81
+ "output_extension": ".pnml",
82
+ "method": lambda x: pm4py.write_pnml(
83
+ *pm4py.convert_to_petri_net(pm4py.read_bpmn(x[0])), x[1]
84
+ ),
85
+ },
86
+ "ConvertDFGtoPNML": {
87
+ "inputs": [".dfg"],
88
+ "output_extension": ".pnml",
89
+ "method": lambda x: pm4py.write_pnml(
90
+ *pm4py.convert_to_petri_net(*pm4py.read_dfg(x[0])), x[1]
91
+ ),
92
+ },
93
+ "DiscoverPetriNetAlpha": {
94
+ "inputs": [".xes"],
95
+ "output_extension": ".pnml",
96
+ "method": lambda x: pm4py.write_pnml(
97
+ *pm4py.discover_petri_net_alpha(__read_log(x[0])), x[1]
98
+ ),
99
+ },
100
+ "DiscoverPetriNetInductive": {
101
+ "inputs": [".xes"],
102
+ "output_extension": ".pnml",
103
+ "method": lambda x: pm4py.write_pnml(
104
+ *pm4py.discover_petri_net_inductive(__read_log(x[0])), x[1]
105
+ ),
106
+ },
107
+ "DiscoverPetriNetHeuristics": {
108
+ "inputs": [".xes"],
109
+ "output_extension": ".pnml",
110
+ "method": lambda x: pm4py.write_pnml(
111
+ *pm4py.discover_petri_net_heuristics(__read_log(x[0])), x[1]
112
+ ),
113
+ },
114
+ "DiscoverPetriNetGenetic": {
115
+ "inputs": [".xes"],
116
+ "output_extension": ".pnml",
117
+ "method": lambda x: pm4py.write_pnml(
118
+ *pm4py.discover_petri_net_genetic(__read_log(x[0])), x[1]
119
+ ),
120
+ },
121
+ "DiscoverBPMNInductive": {
122
+ "inputs": [".xes"],
123
+ "output_extension": ".bpmn",
124
+ "method": lambda x: pm4py.write_bpmn(
125
+ pm4py.discover_bpmn_inductive(__read_log(x[0])), x[1]
126
+ ),
127
+ },
128
+ "DiscoverProcessTreeInductive": {
129
+ "inputs": [".xes"],
130
+ "output_extension": ".ptml",
131
+ "method": lambda x: pm4py.write_ptml(
132
+ pm4py.discover_process_tree_inductive(__read_log(x[0])), x[1]
133
+ ),
134
+ },
135
+ "DiscoverDFG": {
136
+ "inputs": [".xes"],
137
+ "output_extension": ".dfg",
138
+ "method": lambda x: pm4py.write_dfg(
139
+ *pm4py.discover_dfg(__read_log(x[0])), x[1]
140
+ ),
141
+ },
142
+ "ConformanceDiagnosticsTBR": {
143
+ "inputs": [".xes", ".pnml"],
144
+ "output_extension": ".txt",
145
+ "method": lambda x: open(x[2], "w").write(
146
+ str(
147
+ pm4py.conformance_diagnostics_token_based_replay(
148
+ __read_log(x[0]),
149
+ *pm4py.read_pnml(x[1]),
150
+ return_diagnostics_dataframe=False
151
+ )
152
+ )
153
+ ),
154
+ },
155
+ "ConformanceDiagnosticsAlignments": {
156
+ "inputs": [".xes", ".pnml"],
157
+ "output_extension": ".txt",
158
+ "method": lambda x: open(x[2], "w").write(
159
+ str(
160
+ pm4py.conformance_diagnostics_alignments(
161
+ __read_log(x[0]),
162
+ *pm4py.read_pnml(x[1]),
163
+ return_diagnostics_dataframe=False
164
+ )
165
+ )
166
+ ),
167
+ },
168
+ "FitnessTBR": {
169
+ "inputs": [".xes", ".pnml"],
170
+ "output_extension": ".txt",
171
+ "method": lambda x: open(x[2], "w").write(
172
+ str(
173
+ pm4py.fitness_token_based_replay(
174
+ __read_log(x[0]), *pm4py.read_pnml(x[1])
175
+ )
176
+ )
177
+ ),
178
+ },
179
+ "FitnessAlignments": {
180
+ "inputs": [".xes", ".pnml"],
181
+ "output_extension": ".txt",
182
+ "method": lambda x: open(x[2], "w").write(
183
+ str(
184
+ pm4py.fitness_alignments(
185
+ __read_log(x[0]), *pm4py.read_pnml(x[1])
186
+ )
187
+ )
188
+ ),
189
+ },
190
+ "PrecisionTBR": {
191
+ "inputs": [".xes", ".pnml"],
192
+ "output_extension": ".txt",
193
+ "method": lambda x: open(x[2], "w").write(
194
+ str(
195
+ pm4py.precision_token_based_replay(
196
+ __read_log(x[0]), *pm4py.read_pnml(x[1])
197
+ )
198
+ )
199
+ ),
200
+ },
201
+ "PrecisionAlignments": {
202
+ "inputs": [".xes", ".pnml"],
203
+ "output_extension": ".txt",
204
+ "method": lambda x: open(x[2], "w").write(
205
+ str(
206
+ pm4py.precision_alignments(
207
+ __read_log(x[0]), *pm4py.read_pnml(x[1])
208
+ )
209
+ )
210
+ ),
211
+ },
212
+ "SaveVisDFG": {
213
+ "inputs": [".dfg"],
214
+ "output_extension": ".png",
215
+ "method": lambda x: pm4py.save_vis_dfg(*pm4py.read_dfg(x[0]), x[1]),
216
+ },
217
+ "SaveVisPNML": {
218
+ "inputs": [".pnml"],
219
+ "output_extension": ".png",
220
+ "method": lambda x: pm4py.save_vis_petri_net(
221
+ *pm4py.read_pnml(x[0]), x[1]
222
+ ),
223
+ },
224
+ "SaveVisBPMN": {
225
+ "inputs": [".bpmn"],
226
+ "output_extension": ".png",
227
+ "method": lambda x: pm4py.save_vis_bpmn(pm4py.read_bpmn(x[0]), x[1]),
228
+ },
229
+ "SaveVisPTML": {
230
+ "inputs": [".ptml"],
231
+ "output_extension": ".png",
232
+ "method": lambda x: pm4py.save_vis_process_tree(
233
+ pm4py.read_ptml(x[0]), x[1]
234
+ ),
235
+ },
236
+ "SaveVisDottedChart": {
237
+ "inputs": [".xes", None, None, None],
238
+ "output_extension": ".png",
239
+ "method": lambda x: pm4py.save_vis_dotted_chart(
240
+ __read_log(x[0]), x[4], attributes=[x[1], x[2], x[3]]
241
+ ),
242
+ },
243
+ "SaveVisTransitionSystem": {
244
+ "inputs": [".xes"],
245
+ "output_extension": ".png",
246
+ "method": lambda x: pm4py.save_vis_transition_system(
247
+ pm4py.discover_transition_system(__read_log(x[0])), x[1]
248
+ ),
249
+ },
250
+ "SaveVisTrie": {
251
+ "inputs": [".xes"],
252
+ "output_extension": ".png",
253
+ "method": lambda x: pm4py.save_vis_prefix_tree(
254
+ pm4py.discover_prefix_tree(__read_log(x[0])), x[1]
255
+ ),
256
+ },
257
+ "SaveVisEventsDistribution": {
258
+ "inputs": [".xes", None],
259
+ "output_extension": ".png",
260
+ "method": lambda x: pm4py.save_vis_events_distribution_graph(
261
+ __read_log(x[0]), x[2], distr_type=x[1]
262
+ ),
263
+ },
264
+ "SaveVisEventsPerTime": {
265
+ "inputs": [".xes"],
266
+ "output_extension": ".png",
267
+ "method": lambda x: pm4py.save_vis_events_per_time_graph(
268
+ __read_log(x[0]), x[1]
269
+ ),
270
+ },
271
+ "GenerateProcessTree": {
272
+ "inputs": [None],
273
+ "output_extension": ".ptml",
274
+ "method": lambda x: pm4py.write_ptml(
275
+ pm4py.generate_process_tree(
276
+ parameters={
277
+ "min": int(x[0]),
278
+ "max": int(x[0]),
279
+ "mode": int(x[0]),
280
+ }
281
+ ),
282
+ x[1],
283
+ ),
284
+ },
285
+ "PNMLplayout": {
286
+ "inputs": [".pnml"],
287
+ "output_extension": ".xes",
288
+ "method": lambda x: pm4py.write_xes(
289
+ pm4py.play_out(*pm4py.read_pnml(x[0])), x[1]
290
+ ),
291
+ },
292
+ "PTMLplayout": {
293
+ "inputs": [".ptml"],
294
+ "output_extension": ".xes",
295
+ "method": lambda x: pm4py.write_xes(
296
+ pm4py.play_out(pm4py.read_ptml(x[0])), x[1]
297
+ ),
298
+ },
299
+ "DFGplayout": {
300
+ "inputs": [".dfg"],
301
+ "output_extension": ".dfg",
302
+ "method": lambda x: pm4py.write_xes(
303
+ pm4py.play_out(*pm4py.read_dfg(x[0])), x[1]
304
+ ),
305
+ },
306
+ "SaveVisSNA": {
307
+ "inputs": [".xes", None],
308
+ "output_extension": ".png",
309
+ "method": lambda x: pm4py.save_vis_sna(
310
+ __apply_sna(__read_log(x[0]), x[1]), x[2]
311
+ ),
312
+ },
313
+ "SaveVisCaseDuration": {
314
+ "inputs": [".xes"],
315
+ "output_extension": ".png",
316
+ "method": lambda x: pm4py.save_vis_case_duration_graph(
317
+ __read_log(x[0]), x[1]
318
+ ),
319
+ },
320
+ "FilterVariantsTopK": {
321
+ "inputs": [".xes", None],
322
+ "output_extension": ".xes",
323
+ "method": lambda x: pm4py.write_xes(
324
+ pm4py.filter_variants_top_k(__read_log(x[0]), int(x[1])), x[2]
325
+ ),
326
+ },
327
+ "FilterVariantsCoverage": {
328
+ "inputs": [".xes", None],
329
+ "output_extension": ".xes",
330
+ "method": lambda x: pm4py.write_xes(
331
+ pm4py.filter_variants_by_coverage_percentage(
332
+ __read_log(x[0]), float(x[1])
333
+ ),
334
+ x[2],
335
+ ),
336
+ },
337
+ "FilterCasePerformance": {
338
+ "inputs": [".xes", None, None],
339
+ "output_extension": ".xes",
340
+ "method": lambda x: pm4py.write_xes(
341
+ pm4py.filter_case_performance(
342
+ __read_log(x[0]),
343
+ min_performance=float(x[1]),
344
+ max_performance=float(x[2]),
345
+ ),
346
+ x[3],
347
+ ),
348
+ },
349
+ "FilterTimeRange": {
350
+ "inputs": [".xes", None, None],
351
+ "output_extension": ".xes",
352
+ "method": lambda x: pm4py.write_xes(
353
+ pm4py.filter_time_range(
354
+ __read_log(x[0]), x[1] + " 00:00:00", x[2] + " 23:59:59"
355
+ ),
356
+ x[3],
357
+ ),
358
+ },
359
+ }
360
+
361
+
362
+ def __read_log(log_path):
363
+ if "xes" in log_path.lower():
364
+ return pm4py.read_xes(log_path)
365
+ elif "csv" in log_path.lower():
366
+ dataframe = pandas_utils.read_csv(log_path)
367
+ dataframe = pm4py.format_dataframe(dataframe)
368
+ return dataframe
369
+
370
+
371
+ def __apply_sna(log, method, **kwargs):
372
+ if method == "handover":
373
+ return pm4py.discover_handover_of_work_network(log, **kwargs)
374
+ elif method == "working_together":
375
+ return pm4py.discover_working_together_network(log, **kwargs)
376
+ elif method == "similar_activities":
377
+ return pm4py.discover_activity_based_resource_similarity(log, **kwargs)
378
+ elif method == "subcontracting":
379
+ return pm4py.discover_subcontracting_network(log, **kwargs)
380
+
381
+
382
+ def __get_output_name(inp_list, idx, method_name, extension):
383
+ ret = []
384
+ for inp in inp_list:
385
+ ret.append(str(Path(inp).stem))
386
+ return "_".join(ret) + "_" + method_name + extension
387
+
388
+
389
+ def cli_interface():
390
+ method_name = sys.argv[1]
391
+ if method_name in methods:
392
+ method = methods[method_name]
393
+ inputs = []
394
+ for i in range(len(method["inputs"])):
395
+ ci = sys.argv[2 + i]
396
+ if os.path.isdir(ci):
397
+ if not os.path.exists(ci):
398
+ raise Exception(
399
+ "the provided path (" + ci + ") does not exist."
400
+ )
401
+ files = os.listdir(ci)
402
+ inputs.append(
403
+ [
404
+ os.path.join(ci, f)
405
+ for f in files
406
+ if os.path.isfile(os.path.join(ci, f))
407
+ and f.endswith(method["inputs"][i])
408
+ ]
409
+ )
410
+ else:
411
+ inputs.append([ci])
412
+ j = 2 + len(method["inputs"])
413
+ inputs = list(itertools.product(*inputs))
414
+ if len(inputs) == 1:
415
+ outputs = [[sys.argv[j]]]
416
+ else:
417
+ if not os.path.exists(sys.argv[j]):
418
+ os.mkdir(sys.argv[j])
419
+ outputs = [
420
+ [
421
+ os.path.join(
422
+ sys.argv[j],
423
+ __get_output_name(
424
+ inputs[z],
425
+ z,
426
+ method_name,
427
+ method["output_extension"],
428
+ ),
429
+ )
430
+ ]
431
+ for z in range(len(inputs))
432
+ ]
433
+ method_tuples = [(*inputs[i], *outputs[i]) for i in range(len(inputs))]
434
+ for i in range(len(method_tuples)):
435
+ try:
436
+ if not os.path.exists(method_tuples[i][-1]):
437
+ print(method_name, method_tuples[i])
438
+ method["method"](method_tuples[i])
439
+ except BaseException:
440
+ traceback.print_exc()
441
+ else:
442
+ raise Exception(
443
+ "the provided method ("
444
+ + method_name
445
+ + ") does not exist in the CLI."
446
+ )
447
+
448
+
449
+ if __name__ == "__main__":
450
+ cli_interface()
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/conformance.py ADDED
@@ -0,0 +1,1578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ __doc__ = """
23
+ The ``pm4py.conformance`` module contains the conformance checking algorithms implemented in ``pm4py``.
24
+
25
+ """
26
+
27
+ from typing import List, Dict, Any, Union, Optional, Tuple, Set
28
+
29
+ from pm4py.objects.log.obj import EventLog, Trace, Event
30
+ from pm4py.objects.petri_net.obj import PetriNet, Marking
31
+ from pm4py.objects.process_tree.obj import ProcessTree
32
+ from pm4py.objects.ocel.obj import OCEL
33
+ from pm4py.util import xes_constants, constants
34
+ from pm4py.utils import get_properties, __event_log_deprecation_warning
35
+ from pm4py.util.pandas_utils import (
36
+ check_is_pandas_dataframe,
37
+ check_pandas_dataframe_columns,
38
+ )
39
+ import pandas as pd
40
+ from pm4py.util import deprecation
41
+
42
+
43
+ def conformance_diagnostics_token_based_replay(
44
+ log: Union[EventLog, pd.DataFrame],
45
+ petri_net: PetriNet,
46
+ initial_marking: Marking,
47
+ final_marking: Marking,
48
+ activity_key: str = "concept:name",
49
+ timestamp_key: str = "time:timestamp",
50
+ case_id_key: str = "case:concept:name",
51
+ return_diagnostics_dataframe: bool = constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME,
52
+ opt_parameters: Optional[Dict[Any, Any]] = None,
53
+ ) -> List[Dict[str, Any]]:
54
+ """
55
+ Apply token-based replay for conformance checking analysis.
56
+ This method returns the full token-based replay diagnostics.
57
+
58
+ Token-based replay matches a trace against a Petri net model, starting from the initial marking, to discover which transitions are executed and in which places there are remaining or missing tokens for the given process instance. Token-based replay is useful for conformance checking: a trace fits the model if, during its execution, all transitions can be fired without the need to insert any missing tokens. If reaching the final marking is imposed, a trace fits if it reaches the final marking without any missing or remaining tokens.
59
+
60
+ In PM4Py, the token replayer implementation can handle hidden transitions by calculating the shortest paths between places. It can be used with any Petri net model that has unique visible transitions and hidden transitions. When a visible transition needs to be fired and not all places in its preset have the correct number of tokens, the current marking is checked to see if any hidden transitions can be fired to enable the visible transition. The hidden transitions are then fired, reaching a marking that permits the firing of the visible transition.
61
+
62
+ The approach is described in:
63
+ Berti, Alessandro, and Wil MP van der Aalst. "Reviving Token-based Replay: Increasing Speed While Improving Diagnostics." ATAED@ Petri Nets/ACSD. 2019.
64
+
65
+ The output of the token-based replay, stored in the variable `replayed_traces`, contains for each trace in the log:
66
+
67
+ - **trace_is_fit**: Boolean value indicating whether the trace conforms to the model.
68
+ - **activated_transitions**: List of transitions activated in the model by the token-based replay.
69
+ - **reached_marking**: Marking reached at the end of the replay.
70
+ - **missing_tokens**: Number of missing tokens.
71
+ - **consumed_tokens**: Number of consumed tokens.
72
+ - **remaining_tokens**: Number of remaining tokens.
73
+ - **produced_tokens**: Number of produced tokens.
74
+
75
+ :param log: Event log.
76
+ :param petri_net: Petri net.
77
+ :param initial_marking: Initial marking.
78
+ :param final_marking: Final marking.
79
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
80
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
81
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
82
+ :param return_diagnostics_dataframe: If possible, returns a dataframe with the diagnostics instead of the usual output (default is `constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME`).
83
+ :param opt_parameters: Optional parameters for the token-based replay, including:
84
+
85
+ * **reach_mark_through_hidden**: Boolean to decide if the final marking should be reached through hidden transitions.
86
+ * **stop_immediately_unfit**: Boolean to decide if the replay should stop immediately when non-conformance is detected.
87
+ * **walk_through_hidden_trans**: Boolean to decide if the replay should walk through hidden transitions to enable visible transitions.
88
+ * **places_shortest_path_by_hidden**: Shortest paths between places using hidden transitions.
89
+ * **is_reduction**: Indicates if the token-based replay is called in a reduction attempt.
90
+ * **thread_maximum_ex_time**: Maximum allowed execution time for alignment threads.
91
+ * **cleaning_token_flood**: Decides if token flood cleaning should be performed.
92
+ * **disable_variants**: Disable variants grouping.
93
+ * **return_object_names**: Decide whether to return names instead of object pointers. :return: A list of dictionaries containing diagnostics for each trace. :rtype: ``List[Dict[str, Any]]``
94
+
95
+ Example:
96
+ .. code-block:: python
97
+
98
+ import pm4py
99
+
100
+ net, im, fm = pm4py.discover_petri_net_inductive(
101
+ dataframe,
102
+ activity_key='concept:name',
103
+ case_id_key='case:concept:name',
104
+ timestamp_key='time:timestamp'
105
+ )
106
+ tbr_diagnostics = pm4py.conformance_diagnostics_token_based_replay(
107
+ dataframe,
108
+ net,
109
+ im,
110
+ fm,
111
+ activity_key='concept:name',
112
+ case_id_key='case:concept:name',
113
+ timestamp_key='time:timestamp'
114
+ )
115
+
116
+ """
117
+ __event_log_deprecation_warning(log)
118
+
119
+ if check_is_pandas_dataframe(log):
120
+ check_pandas_dataframe_columns(
121
+ log,
122
+ activity_key=activity_key,
123
+ timestamp_key=timestamp_key,
124
+ case_id_key=case_id_key,
125
+ )
126
+
127
+ if return_diagnostics_dataframe:
128
+ from pm4py.convert import convert_to_event_log
129
+
130
+ log = convert_to_event_log(log, case_id_key=case_id_key)
131
+ case_id_key = None
132
+
133
+ properties = get_properties(
134
+ log,
135
+ activity_key=activity_key,
136
+ timestamp_key=timestamp_key,
137
+ case_id_key=case_id_key,
138
+ )
139
+
140
+ if opt_parameters is None:
141
+ opt_parameters = {}
142
+
143
+ for k, v in opt_parameters.items():
144
+ properties[k] = v
145
+
146
+ from pm4py.algo.conformance.tokenreplay import algorithm as token_replay
147
+
148
+ result = token_replay.apply(
149
+ log, petri_net, initial_marking, final_marking, parameters=properties
150
+ )
151
+
152
+ if return_diagnostics_dataframe:
153
+ return token_replay.get_diagnostics_dataframe(
154
+ log, result, parameters=properties
155
+ )
156
+
157
+ return result
158
+
159
+
160
+ def conformance_diagnostics_alignments(
161
+ log: Union[EventLog, pd.DataFrame],
162
+ *args,
163
+ multi_processing: bool = constants.ENABLE_MULTIPROCESSING_DEFAULT,
164
+ activity_key: str = "concept:name",
165
+ timestamp_key: str = "time:timestamp",
166
+ case_id_key: str = "case:concept:name",
167
+ variant_str: Optional[str] = None,
168
+ return_diagnostics_dataframe: bool = constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME,
169
+ **kwargs,
170
+ ) -> List[Dict[str, Any]]:
171
+ """
172
+ Apply the alignments algorithm between a log and a process model.
173
+ This method returns the full alignment diagnostics.
174
+
175
+ Alignment-based replay aims to find one of the best alignments between the trace and the model. For each trace, the output of an alignment is a list of pairs where the first element is an event (from the trace) or ``»`` and the second element is a transition (from the model) or ``»``. Each pair can be classified as follows:
176
+
177
+ - **Sync move**: The event and transition labels correspond, advancing both the trace and the model simultaneously.
178
+ - **Move on log**: The transition is ``»``, indicating a replay move in the trace that is not mirrored in the model. This move is unfit and signals a deviation.
179
+ - **Move on model**: The event is ``»``, indicating a replay move in the model not mirrored in the trace. These can be further classified as:
180
+ * **Moves on model involving hidden transitions**: Even if it's not a sync move, the move is fit.
181
+ * **Moves on model not involving hidden transitions**: The move is unfit and signals a deviation.
182
+
183
+ For each trace, a dictionary is associated containing, among other details:
184
+
185
+ - **alignment**: The alignment pairs (sync moves, moves on log, moves on model).
186
+ - **cost**: The cost of the alignment based on the provided cost function.
187
+ - **fitness**: Equals 1 if the trace fits perfectly.
188
+
189
+ :param log: Event log.
190
+ :param args: Specifications of the process model.
191
+ :param multi_processing: Boolean to enable multiprocessing (default is `constants.ENABLE_MULTIPROCESSING_DEFAULT`).
192
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
193
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
194
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
195
+ :param variant_str: Variant specification (for Petri net alignments).
196
+ :param return_diagnostics_dataframe: If possible, returns a dataframe with the diagnostics instead of the usual output (default is `constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME`).
197
+ :return: A list of dictionaries containing diagnostics for each trace.
198
+ :rtype: ``List[Dict[str, Any]]``
199
+
200
+ Example:
201
+ .. code-block:: python
202
+
203
+ import pm4py
204
+
205
+ net, im, fm = pm4py.discover_petri_net_inductive(
206
+ dataframe,
207
+ activity_key='concept:name',
208
+ case_id_key='case:concept:name',
209
+ timestamp_key='time:timestamp'
210
+ )
211
+ alignments_diagnostics = pm4py.conformance_diagnostics_alignments(
212
+ dataframe,
213
+ net,
214
+ im,
215
+ fm,
216
+ activity_key='concept:name',
217
+ case_id_key='case:concept:name',
218
+ timestamp_key='time:timestamp'
219
+ )
220
+
221
+ """
222
+ __event_log_deprecation_warning(log)
223
+
224
+ if check_is_pandas_dataframe(log):
225
+ check_pandas_dataframe_columns(
226
+ log,
227
+ activity_key=activity_key,
228
+ timestamp_key=timestamp_key,
229
+ case_id_key=case_id_key,
230
+ )
231
+
232
+ if return_diagnostics_dataframe:
233
+ from pm4py.convert import convert_to_event_log
234
+
235
+ log = convert_to_event_log(log, case_id_key=case_id_key)
236
+ case_id_key = None
237
+
238
+ properties = get_properties(
239
+ log,
240
+ activity_key=activity_key,
241
+ timestamp_key=timestamp_key,
242
+ case_id_key=case_id_key,
243
+ )
244
+ if kwargs:
245
+ for k, v in kwargs.items():
246
+ properties[k] = v
247
+
248
+ if len(args) == 3:
249
+ if isinstance(args[0], PetriNet):
250
+ # Petri net alignments
251
+ from pm4py.algo.conformance.alignments.petri_net import (
252
+ algorithm as alignments,
253
+ )
254
+
255
+ variant = alignments.DEFAULT_VARIANT
256
+ if variant_str is not None:
257
+ variant = variant_str
258
+ if multi_processing:
259
+ result = alignments.apply_multiprocessing(
260
+ log,
261
+ args[0],
262
+ args[1],
263
+ args[2],
264
+ parameters=properties,
265
+ variant=variant,
266
+ )
267
+ else:
268
+ result = alignments.apply(
269
+ log,
270
+ args[0],
271
+ args[1],
272
+ args[2],
273
+ parameters=properties,
274
+ variant=variant,
275
+ )
276
+
277
+ if return_diagnostics_dataframe:
278
+ return alignments.get_diagnostics_dataframe(
279
+ log, result, parameters=properties
280
+ )
281
+
282
+ return result
283
+ elif isinstance(args[0], dict):
284
+ # DFG alignments
285
+ from pm4py.algo.conformance.alignments.dfg import (
286
+ algorithm as dfg_alignment,
287
+ )
288
+
289
+ result = dfg_alignment.apply(
290
+ log, args[0], args[1], args[2], parameters=properties
291
+ )
292
+
293
+ return result
294
+ elif len(args) == 1:
295
+ if isinstance(args[0], ProcessTree):
296
+ # Process tree alignments
297
+ from pm4py.algo.conformance.alignments.process_tree.variants import (
298
+ search_graph_pt, )
299
+
300
+ if multi_processing:
301
+ result = search_graph_pt.apply_multiprocessing(
302
+ log, args[0], parameters=properties
303
+ )
304
+ else:
305
+ result = search_graph_pt.apply(
306
+ log, args[0], parameters=properties
307
+ )
308
+
309
+ return result
310
+ elif isinstance(args[0], (EventLog, pd.DataFrame)):
311
+ # Edit distance alignments (log to log)
312
+ from pm4py.algo.conformance.alignments.edit_distance import (
313
+ algorithm as edit_distance_alignments,
314
+ )
315
+
316
+ result = edit_distance_alignments.apply(
317
+ log, args[0], parameters=properties
318
+ )
319
+
320
+ return result
321
+ # Try to convert to Petri net
322
+ import pm4py
323
+ from pm4py.algo.conformance.alignments.petri_net import (
324
+ algorithm as alignments,
325
+ )
326
+
327
+ net, im, fm = pm4py.convert_to_petri_net(*args)
328
+ if multi_processing:
329
+ result = alignments.apply_multiprocessing(
330
+ log, net, im, fm, parameters=properties
331
+ )
332
+ else:
333
+ result = alignments.apply(log, net, im, fm, parameters=properties)
334
+
335
+ if return_diagnostics_dataframe:
336
+ return alignments.get_diagnostics_dataframe(
337
+ log, result, parameters=properties
338
+ )
339
+
340
+ return result
341
+
342
+
343
+ def fitness_token_based_replay(
344
+ log: Union[EventLog, pd.DataFrame],
345
+ petri_net: PetriNet,
346
+ initial_marking: Marking,
347
+ final_marking: Marking,
348
+ activity_key: str = "concept:name",
349
+ timestamp_key: str = "time:timestamp",
350
+ case_id_key: str = "case:concept:name",
351
+ ) -> Dict[str, float]:
352
+ """
353
+ Calculate the fitness using token-based replay.
354
+ The fitness is calculated on a log-based level.
355
+ The output dictionary contains the following keys:
356
+
357
+ - **perc_fit_traces**: Percentage of fit traces (from 0.0 to 100.0).
358
+ - **average_trace_fitness**: Average of the trace fitnesses (between 0.0 and 1.0).
359
+ - **log_fitness**: Overall fitness of the log (between 0.0 and 1.0).
360
+ - **percentage_of_fitting_traces**: Percentage of fit traces (from 0.0 to 100.0).
361
+
362
+ Token-based replay matches a trace against a Petri net model, starting from the initial marking, to discover which transitions are executed and in which places there are remaining or missing tokens for the given process instance. Token-based replay is useful for conformance checking: a trace fits the model if, during its execution, all transitions can be fired without the need to insert any missing tokens. If reaching the final marking is imposed, a trace fits if it reaches the final marking without any missing or remaining tokens.
363
+
364
+ In PM4Py, the token replayer implementation can handle hidden transitions by calculating the shortest paths between places. It can be used with any Petri net model that has unique visible transitions and hidden transitions. When a visible transition needs to be fired and not all places in its preset have the correct number of tokens, the current marking is checked to see if any hidden transitions can be fired to enable the visible transition. The hidden transitions are then fired, reaching a marking that permits the firing of the visible transition.
365
+
366
+ The approach is described in:
367
+ Berti, Alessandro, and Wil MP van der Aalst. "Reviving Token-based Replay: Increasing Speed While Improving Diagnostics." ATAED@ Petri Nets/ACSD. 2019.
368
+
369
+ The calculation of replay fitness aims to assess how much of the behavior in the log is admitted by the process model. Two methods are proposed to calculate replay fitness, based on token-based replay and alignments respectively.
370
+
371
+ For token-based replay, the percentage of traces that are completely fit is returned, along with a fitness value calculated as indicated in the referenced contribution.
372
+
373
+ :param log: Event log.
374
+ :param petri_net: Petri net.
375
+ :param initial_marking: Initial marking.
376
+ :param final_marking: Final marking.
377
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
378
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
379
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
380
+ :return: A dictionary containing fitness metrics.
381
+ :rtype: ``Dict[str, float]``
382
+
383
+ Example:
384
+ .. code-block:: python
385
+
386
+ import pm4py
387
+
388
+ net, im, fm = pm4py.discover_petri_net_inductive(
389
+ dataframe,
390
+ activity_key='concept:name',
391
+ case_id_key='case:concept:name',
392
+ timestamp_key='time:timestamp'
393
+ )
394
+ fitness_tbr = pm4py.fitness_token_based_replay(
395
+ dataframe,
396
+ net,
397
+ im,
398
+ fm,
399
+ activity_key='concept:name',
400
+ case_id_key='case:concept:name',
401
+ timestamp_key='time:timestamp'
402
+ )
403
+
404
+ """
405
+ __event_log_deprecation_warning(log)
406
+
407
+ if check_is_pandas_dataframe(log):
408
+ check_pandas_dataframe_columns(
409
+ log,
410
+ activity_key=activity_key,
411
+ timestamp_key=timestamp_key,
412
+ case_id_key=case_id_key,
413
+ )
414
+
415
+ properties = get_properties(
416
+ log,
417
+ activity_key=activity_key,
418
+ timestamp_key=timestamp_key,
419
+ case_id_key=case_id_key,
420
+ )
421
+
422
+ from pm4py.algo.evaluation.replay_fitness import (
423
+ algorithm as replay_fitness,
424
+ )
425
+
426
+ result = replay_fitness.apply(
427
+ log,
428
+ petri_net,
429
+ initial_marking,
430
+ final_marking,
431
+ variant=replay_fitness.Variants.TOKEN_BASED,
432
+ parameters=properties,
433
+ )
434
+
435
+ return result
436
+
437
+
438
+ def fitness_alignments(
439
+ log: Union[EventLog, pd.DataFrame],
440
+ petri_net: PetriNet,
441
+ initial_marking: Marking,
442
+ final_marking: Marking,
443
+ multi_processing: bool = constants.ENABLE_MULTIPROCESSING_DEFAULT,
444
+ activity_key: str = "concept:name",
445
+ timestamp_key: str = "time:timestamp",
446
+ case_id_key: str = "case:concept:name",
447
+ variant_str: Optional[str] = None,
448
+ ) -> Dict[str, float]:
449
+ """
450
+ Calculate the fitness using alignments.
451
+ The output dictionary contains the following keys:
452
+
453
+ - **average_trace_fitness**: Average of the trace fitnesses (between 0.0 and 1.0).
454
+ - **log_fitness**: Overall fitness of the log (between 0.0 and 1.0).
455
+ - **percentage_of_fitting_traces**: Percentage of fit traces (from 0.0 to 100.0).
456
+
457
+ Alignment-based replay aims to find one of the best alignments between the trace and the model. For each trace, the output of an alignment is a list of pairs where the first element is an event (from the trace) or ``»`` and the second element is a transition (from the model) or ``»``. Each pair can be classified as follows:
458
+
459
+ - **Sync move**: The event and transition labels correspond, advancing both the trace and the model simultaneously.
460
+ - **Move on log**: The transition is ``»``, indicating a replay move in the trace that is not mirrored in the model. This move is unfit and signals a deviation.
461
+ - **Move on model**: The event is ``»``, indicating a replay move in the model not mirrored in the trace. These can be further classified as:
462
+ * **Moves on model involving hidden transitions**: Even if it's not a sync move, the move is fit.
463
+ * **Moves on model not involving hidden transitions**: The move is unfit and signals a deviation.
464
+
465
+ The calculation of replay fitness aims to assess how much of the behavior in the log is admitted by the process model. Two methods are proposed to calculate replay fitness, based on token-based replay and alignments respectively.
466
+
467
+ For alignments, the percentage of traces that are completely fit is returned, along with a fitness value calculated as the average of the fitness values of the individual traces.
468
+
469
+ :param log: Event log.
470
+ :param petri_net: Petri net.
471
+ :param initial_marking: Initial marking.
472
+ :param final_marking: Final marking.
473
+ :param multi_processing: Boolean to enable multiprocessing (default is `constants.ENABLE_MULTIPROCESSING_DEFAULT`).
474
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
475
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
476
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
477
+ :param variant_str: Variant specification.
478
+ :return: A dictionary containing fitness metrics.
479
+ :rtype: ``Dict[str, float]``
480
+
481
+ Example:
482
+ .. code-block:: python
483
+
484
+ import pm4py
485
+
486
+ net, im, fm = pm4py.discover_petri_net_inductive(
487
+ dataframe,
488
+ activity_key='concept:name',
489
+ case_id_key='case:concept:name',
490
+ timestamp_key='time:timestamp'
491
+ )
492
+ fitness_alignments = pm4py.fitness_alignments(
493
+ dataframe,
494
+ net,
495
+ im,
496
+ fm,
497
+ activity_key='concept:name',
498
+ case_id_key='case:concept:name',
499
+ timestamp_key='time:timestamp'
500
+ )
501
+
502
+ """
503
+ __event_log_deprecation_warning(log)
504
+
505
+ if check_is_pandas_dataframe(log):
506
+ check_pandas_dataframe_columns(
507
+ log,
508
+ activity_key=activity_key,
509
+ timestamp_key=timestamp_key,
510
+ case_id_key=case_id_key,
511
+ )
512
+
513
+ from pm4py.algo.evaluation.replay_fitness import (
514
+ algorithm as replay_fitness,
515
+ )
516
+
517
+ parameters = get_properties(
518
+ log,
519
+ activity_key=activity_key,
520
+ timestamp_key=timestamp_key,
521
+ case_id_key=case_id_key,
522
+ )
523
+ parameters["multiprocessing"] = multi_processing
524
+ result = replay_fitness.apply(
525
+ log,
526
+ petri_net,
527
+ initial_marking,
528
+ final_marking,
529
+ variant=replay_fitness.Variants.ALIGNMENT_BASED,
530
+ align_variant=variant_str,
531
+ parameters=parameters,
532
+ )
533
+
534
+ return result
535
+
536
+
537
+ def precision_token_based_replay(
538
+ log: Union[EventLog, pd.DataFrame],
539
+ petri_net: PetriNet,
540
+ initial_marking: Marking,
541
+ final_marking: Marking,
542
+ activity_key: str = "concept:name",
543
+ timestamp_key: str = "time:timestamp",
544
+ case_id_key: str = "case:concept:name",
545
+ ) -> float:
546
+ """
547
+ Calculate precision using token-based replay.
548
+
549
+ Token-based replay matches a trace against a Petri net model, starting from the initial marking, to discover which transitions are executed and in which places there are remaining or missing tokens for the given process instance. Token-based replay is useful for conformance checking: a trace fits the model if, during its execution, all transitions can be fired without the need to insert any missing tokens. If reaching the final marking is imposed, a trace fits if it reaches the final marking without any missing or remaining tokens.
550
+
551
+ In PM4Py, the token replayer implementation can handle hidden transitions by calculating the shortest paths between places. It can be used with any Petri net model that has unique visible transitions and hidden transitions. When a visible transition needs to be fired and not all places in its preset have the correct number of tokens, the current marking is checked to see if any hidden transitions can be fired to enable the visible transition. The hidden transitions are then fired, reaching a marking that permits the firing of the visible transition.
552
+
553
+ The approach is described in:
554
+ Berti, Alessandro, and Wil MP van der Aalst. "Reviving Token-based Replay: Increasing Speed While Improving Diagnostics." ATAED@ Petri Nets/ACSD. 2019.
555
+
556
+ The reference paper for the TBR-based precision (ETConformance) is:
557
+ Muñoz-Gama, Jorge, and Josep Carmona. "A fresh look at precision in process conformance." International Conference on Business Process Management. Springer, Berlin, Heidelberg, 2010.
558
+
559
+ In this approach, the different prefixes of the log are replayed (if possible) on the model. At the reached marking, the set of transitions that are enabled in the process model is compared with the set of activities that follow the prefix. The more the sets differ, the lower the precision value. The more the sets are similar, the higher the precision value.
560
+
561
+ :param log: Event log.
562
+ :param petri_net: Petri net.
563
+ :param initial_marking: Initial marking.
564
+ :param final_marking: Final marking.
565
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
566
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
567
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
568
+ :return: The precision value.
569
+ :rtype: ``float``
570
+
571
+ Example:
572
+ .. code-block:: python
573
+
574
+ import pm4py
575
+
576
+ net, im, fm = pm4py.discover_petri_net_inductive(
577
+ dataframe,
578
+ activity_key='concept:name',
579
+ case_id_key='case:concept:name',
580
+ timestamp_key='time:timestamp'
581
+ )
582
+ precision_tbr = pm4py.precision_token_based_replay(
583
+ dataframe,
584
+ net,
585
+ im,
586
+ fm,
587
+ activity_key='concept:name',
588
+ case_id_key='case:concept:name',
589
+ timestamp_key='time:timestamp'
590
+ )
591
+
592
+ """
593
+ __event_log_deprecation_warning(log)
594
+
595
+ if check_is_pandas_dataframe(log):
596
+ check_pandas_dataframe_columns(
597
+ log,
598
+ activity_key=activity_key,
599
+ timestamp_key=timestamp_key,
600
+ case_id_key=case_id_key,
601
+ )
602
+
603
+ properties = get_properties(
604
+ log,
605
+ activity_key=activity_key,
606
+ timestamp_key=timestamp_key,
607
+ case_id_key=case_id_key,
608
+ )
609
+
610
+ from pm4py.algo.evaluation.precision import (
611
+ algorithm as precision_evaluator,
612
+ )
613
+
614
+ result = precision_evaluator.apply(
615
+ log,
616
+ petri_net,
617
+ initial_marking,
618
+ final_marking,
619
+ variant=precision_evaluator.Variants.ETCONFORMANCE_TOKEN,
620
+ parameters=properties,
621
+ )
622
+
623
+ return result
624
+
625
+
626
+ def precision_alignments(
627
+ log: Union[EventLog, pd.DataFrame],
628
+ petri_net: PetriNet,
629
+ initial_marking: Marking,
630
+ final_marking: Marking,
631
+ multi_processing: bool = constants.ENABLE_MULTIPROCESSING_DEFAULT,
632
+ activity_key: str = "concept:name",
633
+ timestamp_key: str = "time:timestamp",
634
+ case_id_key: str = "case:concept:name",
635
+ ) -> float:
636
+ """
637
+ Calculate the precision of the model with respect to the event log using alignments.
638
+
639
+ Alignment-based replay aims to find one of the best alignments between the trace and the model. For each trace, the output of an alignment is a list of pairs where the first element is an event (from the trace) or ``»`` and the second element is a transition (from the model) or ``»``. Each pair can be classified as follows:
640
+
641
+ - **Sync move**: The event and transition labels correspond, advancing both the trace and the model simultaneously.
642
+ - **Move on log**: The transition is ``»``, indicating a replay move in the trace that is not mirrored in the model. This move is unfit and signals a deviation.
643
+ - **Move on model**: The event is ``»``, indicating a replay move in the model not mirrored in the trace. These can be further classified as:
644
+ * **Moves on model involving hidden transitions**: Even if it's not a sync move, the move is fit.
645
+ * **Moves on model not involving hidden transitions**: The move is unfit and signals a deviation.
646
+
647
+ The reference paper for the alignments-based precision (Align-ETConformance) is:
648
+ Adriansyah, Arya, et al. "Measuring precision of modeled behavior." Information systems and e-Business Management 13.1 (2015): 37-67.
649
+
650
+ In this approach, the different prefixes of the log are replayed (if possible) on the model. At the reached marking, the set of transitions that are enabled in the process model is compared with the set of activities that follow the prefix. The more the sets differ, the lower the precision value. The more the sets are similar, the higher the precision value.
651
+
652
+ :param log: Event log.
653
+ :param petri_net: Petri net.
654
+ :param initial_marking: Initial marking.
655
+ :param final_marking: Final marking.
656
+ :param multi_processing: Boolean to enable multiprocessing (default is `constants.ENABLE_MULTIPROCESSING_DEFAULT`).
657
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
658
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
659
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
660
+ :return: The precision value.
661
+ :rtype: ``float``
662
+
663
+ Example:
664
+ .. code-block:: python
665
+
666
+ import pm4py
667
+
668
+ net, im, fm = pm4py.discover_petri_net_inductive(
669
+ dataframe,
670
+ activity_key='concept:name',
671
+ case_id_key='case:concept:name',
672
+ timestamp_key='time:timestamp'
673
+ )
674
+ precision_alignments = pm4py.precision_alignments(
675
+ dataframe,
676
+ net,
677
+ im,
678
+ fm,
679
+ activity_key='concept:name',
680
+ case_id_key='case:concept:name',
681
+ timestamp_key='time:timestamp'
682
+ )
683
+
684
+ """
685
+ __event_log_deprecation_warning(log)
686
+
687
+ if check_is_pandas_dataframe(log):
688
+ check_pandas_dataframe_columns(
689
+ log,
690
+ activity_key=activity_key,
691
+ timestamp_key=timestamp_key,
692
+ case_id_key=case_id_key,
693
+ )
694
+
695
+ from pm4py.algo.evaluation.precision import (
696
+ algorithm as precision_evaluator,
697
+ )
698
+
699
+ parameters = get_properties(
700
+ log,
701
+ activity_key=activity_key,
702
+ timestamp_key=timestamp_key,
703
+ case_id_key=case_id_key,
704
+ )
705
+ parameters["multiprocessing"] = multi_processing
706
+ result = precision_evaluator.apply(
707
+ log,
708
+ petri_net,
709
+ initial_marking,
710
+ final_marking,
711
+ variant=precision_evaluator.Variants.ALIGN_ETCONFORMANCE,
712
+ parameters=parameters,
713
+ )
714
+
715
+ return result
716
+
717
+
718
+ def generalization_tbr(
719
+ log: Union[EventLog, pd.DataFrame],
720
+ petri_net: PetriNet,
721
+ initial_marking: Marking,
722
+ final_marking: Marking,
723
+ activity_key: str = "concept:name",
724
+ timestamp_key: str = "time:timestamp",
725
+ case_id_key: str = "case:concept:name",
726
+ ) -> float:
727
+ """
728
+ Compute the generalization of the model against the event log.
729
+ The approach is described in the paper:
730
+
731
+ Buijs, Joos CAM, Boudewijn F. van Dongen, and Wil MP van der Aalst. "Quality dimensions in process discovery: The importance of fitness, precision, generalization, and simplicity." International Journal of Cooperative Information Systems 23.01 (2014): 1440001.
732
+
733
+ :param log: Event log.
734
+ :param petri_net: Petri net.
735
+ :param initial_marking: Initial marking.
736
+ :param final_marking: Final marking.
737
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
738
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
739
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
740
+ :return: The generalization value.
741
+ :rtype: ``float``
742
+
743
+ Example:
744
+ .. code-block:: python
745
+
746
+ import pm4py
747
+
748
+ net, im, fm = pm4py.discover_petri_net_inductive(
749
+ dataframe,
750
+ activity_key='concept:name',
751
+ case_id_key='case:concept:name',
752
+ timestamp_key='time:timestamp'
753
+ )
754
+ generalization_tbr = pm4py.generalization_tbr(
755
+ dataframe,
756
+ net,
757
+ im,
758
+ fm,
759
+ activity_key='concept:name',
760
+ case_id_key='case:concept:name',
761
+ timestamp_key='time:timestamp'
762
+ )
763
+
764
+ """
765
+ __event_log_deprecation_warning(log)
766
+
767
+ if check_is_pandas_dataframe(log):
768
+ check_pandas_dataframe_columns(
769
+ log,
770
+ activity_key=activity_key,
771
+ timestamp_key=timestamp_key,
772
+ case_id_key=case_id_key,
773
+ )
774
+
775
+ from pm4py.algo.evaluation.generalization import (
776
+ algorithm as generalization_evaluator,
777
+ )
778
+
779
+ parameters = get_properties(
780
+ log,
781
+ activity_key=activity_key,
782
+ timestamp_key=timestamp_key,
783
+ case_id_key=case_id_key,
784
+ )
785
+ result = generalization_evaluator.apply(
786
+ log,
787
+ petri_net,
788
+ initial_marking,
789
+ final_marking,
790
+ variant=generalization_evaluator.Variants.GENERALIZATION_TOKEN,
791
+ parameters=parameters,
792
+ )
793
+
794
+ return result
795
+
796
+
797
+ def replay_prefix_tbr(
798
+ prefix: List[str],
799
+ net: PetriNet,
800
+ im: Marking,
801
+ fm: Marking,
802
+ activity_key: str = "concept:name",
803
+ ) -> Marking:
804
+ """
805
+ Replay a prefix (list of activities) on a given accepting Petri net using Token-Based Replay.
806
+
807
+ :param prefix: List of activities representing the prefix.
808
+ :param net: Petri net.
809
+ :param im: Initial marking.
810
+ :param fm: Final marking.
811
+ :param activity_key: Attribute to be used as the activity key (default is "concept:name").
812
+ :return: The marking reached after replaying the prefix.
813
+ :rtype: ``Marking``
814
+
815
+ Example:
816
+ .. code-block:: python
817
+
818
+ import pm4py
819
+
820
+ net, im, fm = pm4py.read_pnml('tests/input_data/running-example.pnml')
821
+ marking = pm4py.replay_prefix_tbr(
822
+ ['register request', 'check ticket'],
823
+ net,
824
+ im,
825
+ fm,
826
+ activity_key='concept:name'
827
+ )
828
+
829
+ """
830
+ purpose_log = EventLog()
831
+ trace = Trace()
832
+ for act in prefix:
833
+ trace.append(Event({activity_key: act}))
834
+ purpose_log.append(trace)
835
+
836
+ from pm4py.algo.conformance.tokenreplay.variants import token_replay
837
+
838
+ parameters_tr = {
839
+ token_replay.Parameters.CONSIDER_REMAINING_IN_FITNESS: False,
840
+ token_replay.Parameters.TRY_TO_REACH_FINAL_MARKING_THROUGH_HIDDEN: False,
841
+ token_replay.Parameters.STOP_IMMEDIATELY_UNFIT: True,
842
+ token_replay.Parameters.WALK_THROUGH_HIDDEN_TRANS: True,
843
+ token_replay.Parameters.ACTIVITY_KEY: activity_key,
844
+ }
845
+ res = token_replay.apply(
846
+ purpose_log, net, im, fm, parameters=parameters_tr
847
+ )[0]
848
+ return res["reached_marking"]
849
+
850
+
851
+ @deprecation.deprecated(
852
+ deprecated_in="2.3.0",
853
+ removed_in="3.0.0",
854
+ details="Conformance checking using footprints will not be exposed in a future release.",
855
+ )
856
+ def __convert_to_fp(*args) -> Union[List[Dict[str, Any]], Dict[str, Any]]:
857
+ """
858
+ Internal method to convert the provided event log or process model arguments
859
+ to footprints using footprints discovery.
860
+
861
+ :param args: Event log or process model.
862
+ :return: Footprints representation.
863
+ :rtype: ``Union[List[Dict[str, Any]], Dict[str, Any]]``
864
+
865
+ Note:
866
+ This is an internal method and is deprecated.
867
+
868
+ """
869
+ import pm4py
870
+
871
+ while isinstance(args, tuple):
872
+ if len(args) == 1:
873
+ args = args[0]
874
+ else:
875
+ fp = pm4py.discover_footprints(*args)
876
+ return fp
877
+ if isinstance(args, list) or isinstance(args, dict):
878
+ return args
879
+ fp = pm4py.discover_footprints(args)
880
+ return fp
881
+
882
+
883
+ def conformance_diagnostics_footprints(
884
+ *args,
885
+ ) -> Union[List[Dict[str, Any]], Dict[str, Any]]:
886
+ """
887
+ Provide conformance checking diagnostics using footprints.
888
+
889
+ :param args: Arguments where the first is an event log (or its footprints) and the others represent the process model (or its footprints).
890
+ :return: Conformance diagnostics based on footprints.
891
+ :rtype: ``Union[List[Dict[str, Any]], Dict[str, Any]]``
892
+
893
+ Example:
894
+ .. code-block:: python
895
+
896
+ import pm4py
897
+
898
+ net, im, fm = pm4py.discover_petri_net_inductive(
899
+ dataframe,
900
+ activity_key='concept:name',
901
+ case_id_key='case:concept:name',
902
+ timestamp_key='time:timestamp'
903
+ )
904
+ footprints_diagnostics = pm4py.conformance_diagnostics_footprints(
905
+ dataframe,
906
+ net,
907
+ im,
908
+ fm,
909
+ activity_key='concept:name',
910
+ case_id_key='case:concept:name',
911
+ timestamp_key='time:timestamp'
912
+ )
913
+
914
+ """
915
+ fp1 = __convert_to_fp(args[0])
916
+ fp2 = __convert_to_fp(args[1:])
917
+ from pm4py.algo.conformance.footprints import (
918
+ algorithm as footprints_conformance,
919
+ )
920
+
921
+ if isinstance(fp1, list):
922
+ result = footprints_conformance.apply(
923
+ fp1, fp2, variant=footprints_conformance.Variants.TRACE_EXTENSIVE
924
+ )
925
+ else:
926
+ result = footprints_conformance.apply(
927
+ fp1, fp2, variant=footprints_conformance.Variants.LOG_EXTENSIVE
928
+ )
929
+
930
+ return result
931
+
932
+
933
+ def fitness_footprints(*args) -> Dict[str, float]:
934
+ """
935
+ Calculate fitness using footprints.
936
+ The output is a dictionary containing two keys:
937
+
938
+ - **perc_fit_traces**: Percentage of fit traces (over the log).
939
+ - **log_fitness**: The fitness value over the log.
940
+
941
+ :param args: Arguments where the first is an event log (or its footprints) and the others represent the process model (or its footprints).
942
+ :return: A dictionary containing fitness metrics based on footprints.
943
+ :rtype: ``Dict[str, float]``
944
+
945
+ Example:
946
+ .. code-block:: python
947
+
948
+ import pm4py
949
+
950
+ net, im, fm = pm4py.discover_petri_net_inductive(
951
+ dataframe,
952
+ activity_key='concept:name',
953
+ case_id_key='case:concept:name',
954
+ timestamp_key='time:timestamp'
955
+ )
956
+ fitness_fp = pm4py.fitness_footprints(
957
+ dataframe,
958
+ net,
959
+ im,
960
+ fm,
961
+ activity_key='concept:name',
962
+ case_id_key='case:concept:name',
963
+ timestamp_key='time:timestamp'
964
+ )
965
+
966
+ """
967
+ fp_conf = conformance_diagnostics_footprints(*args)
968
+ fp1 = __convert_to_fp(args[0])
969
+ fp2 = __convert_to_fp(args[1:])
970
+ from pm4py.algo.conformance.footprints.util import evaluation
971
+
972
+ result = evaluation.fp_fitness(fp1, fp2, fp_conf)
973
+
974
+ return result
975
+
976
+
977
+ def precision_footprints(*args) -> float:
978
+ """
979
+ Calculate precision using footprints.
980
+
981
+ :param args: Arguments where the first is an event log (or its footprints) and the others represent the process model (or its footprints).
982
+ :return: The precision value based on footprints.
983
+ :rtype: ``float``
984
+
985
+ Example:
986
+ .. code-block:: python
987
+
988
+ import pm4py
989
+
990
+ net, im, fm = pm4py.discover_petri_net_inductive(
991
+ dataframe,
992
+ activity_key='concept:name',
993
+ case_id_key='case:concept:name',
994
+ timestamp_key='time:timestamp'
995
+ )
996
+ precision_fp = pm4py.precision_footprints(
997
+ dataframe,
998
+ net,
999
+ im,
1000
+ fm,
1001
+ activity_key='concept:name',
1002
+ case_id_key='case:concept:name',
1003
+ timestamp_key='time:timestamp'
1004
+ )
1005
+
1006
+ """
1007
+ fp1 = __convert_to_fp(args[0])
1008
+ fp2 = __convert_to_fp(args[1:])
1009
+ from pm4py.algo.conformance.footprints.util import evaluation
1010
+
1011
+ result = evaluation.fp_precision(fp1, fp2)
1012
+
1013
+ return result
1014
+
1015
+
1016
+ @deprecation.deprecated(
1017
+ removed_in="2.3.0",
1018
+ deprecated_in="3.0.0",
1019
+ details="This method will be removed in a future release.",
1020
+ )
1021
+ def __check_is_fit_process_tree(trace, tree) -> bool:
1022
+ """
1023
+ Check if a trace object fits a process tree model.
1024
+
1025
+ :param trace: Trace.
1026
+ :param tree: Process tree.
1027
+ :return: True if the trace fits the process tree, False otherwise.
1028
+ :rtype: ``bool``
1029
+
1030
+ Note:
1031
+ This is an internal method and is deprecated.
1032
+
1033
+ """
1034
+ __event_log_deprecation_warning(trace)
1035
+
1036
+ from pm4py.discovery import discover_footprints
1037
+
1038
+ log = EventLog()
1039
+ log.append(trace)
1040
+ fp_tree = discover_footprints(tree)
1041
+ fp_log = discover_footprints(log)
1042
+ fp_conf_res = conformance_diagnostics_footprints(fp_log, fp_tree)[0]
1043
+ # CHECK 1) If footprints indicate non-conformance, return False
1044
+ if not fp_conf_res["is_footprints_fit"]:
1045
+ return False
1046
+ else:
1047
+ from pm4py.convert import convert_to_petri_net
1048
+
1049
+ net, im, fm = convert_to_petri_net(tree)
1050
+ tbr_conf_res = conformance_diagnostics_token_based_replay(
1051
+ log, net, im, fm, return_diagnostics_dataframe=False
1052
+ )[0]
1053
+ # CHECK 2) If TBR indicates fit, return True
1054
+ if tbr_conf_res["trace_is_fit"]:
1055
+ return True
1056
+ else:
1057
+ # CHECK 3) Use alignments for definitive fit assessment
1058
+ align_conf_res = conformance_diagnostics_alignments(
1059
+ log, tree, return_diagnostics_dataframe=False
1060
+ )[0]
1061
+ return align_conf_res["fitness"] == 1.0
1062
+
1063
+
1064
+ @deprecation.deprecated(
1065
+ removed_in="2.3.0",
1066
+ deprecated_in="3.0.0",
1067
+ details="This method will be removed in a future release.",
1068
+ )
1069
+ def __check_is_fit_petri_net(
1070
+ trace,
1071
+ net: PetriNet,
1072
+ im: Marking,
1073
+ fm: Marking,
1074
+ activity_key=xes_constants.DEFAULT_NAME_KEY,
1075
+ ) -> bool:
1076
+ """
1077
+ Check if a trace object fits a Petri net model.
1078
+
1079
+ :param trace: Trace.
1080
+ :param net: Petri net.
1081
+ :param im: Initial marking.
1082
+ :param fm: Final marking.
1083
+ :param activity_key: Attribute to be used as the activity key (default is defined in `xes_constants.DEFAULT_NAME_KEY`).
1084
+ :return: True if the trace fits the Petri net, False otherwise.
1085
+ :rtype: ``bool``
1086
+
1087
+ Note:
1088
+ This is an internal method and is deprecated.
1089
+
1090
+ """
1091
+ __event_log_deprecation_warning(trace)
1092
+
1093
+ # Avoid checking footprints on Petri net (they are too slow)
1094
+ activities_model = set(
1095
+ trans.label for trans in net.transitions if trans.label is not None
1096
+ )
1097
+ activities_trace = set([x[activity_key] for x in trace])
1098
+ diff = activities_trace.difference(activities_model)
1099
+ if diff:
1100
+ # CHECK 1) If there are activities in the trace not present in the
1101
+ # model, return False
1102
+ return False
1103
+ else:
1104
+ log = EventLog()
1105
+ log.append(trace)
1106
+ tbr_conf_res = conformance_diagnostics_token_based_replay(
1107
+ log, net, im, fm, return_diagnostics_dataframe=False
1108
+ )[0]
1109
+ # CHECK 2) If TBR indicates fit, return True
1110
+ if tbr_conf_res["trace_is_fit"]:
1111
+ return True
1112
+ else:
1113
+ # CHECK 3) Use alignments for definitive fit assessment
1114
+ align_conf_res = conformance_diagnostics_alignments(
1115
+ log, net, im, fm, return_diagnostics_dataframe=False
1116
+ )[0]
1117
+ return align_conf_res["fitness"] == 1.0
1118
+
1119
+
1120
+ @deprecation.deprecated(
1121
+ deprecated_in="2.3.0",
1122
+ removed_in="3.0.0",
1123
+ details="This method will be removed in a future release.",
1124
+ )
1125
+ def check_is_fitting(
1126
+ *args, activity_key=xes_constants.DEFAULT_NAME_KEY
1127
+ ) -> bool:
1128
+ """
1129
+ Check if a trace object fits a process model.
1130
+
1131
+ :param args: Arguments where the first is a trace object and the others represent the process model (process tree, Petri net, BPMN).
1132
+ :param activity_key: Attribute to be used as the activity key (default is defined in `xes_constants.DEFAULT_NAME_KEY`).
1133
+ :return: True if the trace fits the process model, False otherwise.
1134
+ :rtype: ``bool``
1135
+
1136
+ Note:
1137
+ This is an internal method and is deprecated.
1138
+
1139
+ """
1140
+ from pm4py.util import variants_util
1141
+ from pm4py.convert import convert_to_process_tree, convert_to_petri_net
1142
+
1143
+ trace = args[0]
1144
+ model = args[1:]
1145
+
1146
+ try:
1147
+ model = convert_to_process_tree(*model)
1148
+ except BaseException:
1149
+ # If the model cannot be expressed as a process tree, attempt Petri net
1150
+ # conversion
1151
+ model = convert_to_petri_net(*model)
1152
+
1153
+ if not isinstance(trace, Trace):
1154
+ activities = variants_util.get_activities_from_variant(trace)
1155
+ trace = Trace()
1156
+ for act in activities:
1157
+ trace.append(Event({activity_key: act}))
1158
+
1159
+ if isinstance(model, ProcessTree):
1160
+ return __check_is_fit_process_tree(trace, model)
1161
+ elif isinstance(model, tuple) and isinstance(model[0], PetriNet):
1162
+ return __check_is_fit_petri_net(
1163
+ trace, model[0], model[1], model[2], activity_key=activity_key
1164
+ )
1165
+
1166
+
1167
+ def conformance_temporal_profile(
1168
+ log: Union[EventLog, pd.DataFrame],
1169
+ temporal_profile: Dict[Tuple[str, str], Tuple[float, float]],
1170
+ zeta: float = 1.0,
1171
+ activity_key: str = "concept:name",
1172
+ timestamp_key: str = "time:timestamp",
1173
+ case_id_key: str = "case:concept:name",
1174
+ return_diagnostics_dataframe: bool = constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME,
1175
+ ) -> List[List[Tuple[float, float, float, float]]]:
1176
+ """
1177
+ Perform conformance checking on the provided log using the provided temporal profile.
1178
+ The result is a list of time-based deviations for every case.
1179
+
1180
+ For example, consider a log with a single case:
1181
+
1182
+ - A (timestamp: 2000-01)
1183
+ - B (timestamp: 2002-01)
1184
+
1185
+ Given the temporal profile::
1186
+
1187
+ {
1188
+ ('A', 'B'): (1.5, 0.5), # (mean, std)
1189
+ ('A', 'C'): (5.0, 0.0),
1190
+ ('A', 'D'): (2.0, 0.0)
1191
+ }
1192
+
1193
+ and setting `zeta` to 1, the difference between the timestamps of A and B (2 years) exceeds the allowed time (1.5 months + 0.5 months), resulting in a deviation.
1194
+
1195
+ :param log: Log object.
1196
+ :param temporal_profile: Temporal profile. For example, if the log has two cases:
1197
+
1198
+ - Case 1: A (timestamp: 1980-01), B (timestamp: 1980-03), C (timestamp: 1980-06)
1199
+ - Case 2: A (timestamp: 1990-01), B (timestamp: 1990-02), D (timestamp: 1990-03)
1200
+
1201
+ The temporal profile might look like::
1202
+
1203
+ {
1204
+ ('A', 'B'): (1.5, 0.5), # (mean, std)
1205
+ ('A', 'C'): (5.0, 0.0),
1206
+ ('A', 'D'): (2.0, 0.0)
1207
+ }
1208
+
1209
+ :param zeta: Number of standard deviations allowed from the average (default is 1.0). For example, `zeta=1` allows deviations within one standard deviation from the mean.
1210
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
1211
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
1212
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
1213
+ :param return_diagnostics_dataframe: If possible, returns a dataframe with the diagnostics instead of the usual output (default is `constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME`).
1214
+ :return: A list containing lists of tuples representing time-based deviations for each case.
1215
+ :rtype: ``List[List[Tuple[float, float, float, float]]]``
1216
+
1217
+ Example:
1218
+ .. code-block:: python
1219
+
1220
+ import pm4py
1221
+
1222
+ temporal_profile = pm4py.discover_temporal_profile(
1223
+ dataframe,
1224
+ activity_key='concept:name',
1225
+ case_id_key='case:concept:name',
1226
+ timestamp_key='time:timestamp'
1227
+ )
1228
+ conformance_temporal_profile = pm4py.conformance_temporal_profile(
1229
+ dataframe,
1230
+ temporal_profile,
1231
+ zeta=1,
1232
+ activity_key='concept:name',
1233
+ case_id_key='case:concept:name',
1234
+ timestamp_key='time:timestamp'
1235
+ )
1236
+
1237
+ """
1238
+ __event_log_deprecation_warning(log)
1239
+
1240
+ if check_is_pandas_dataframe(log):
1241
+ check_pandas_dataframe_columns(
1242
+ log,
1243
+ activity_key=activity_key,
1244
+ timestamp_key=timestamp_key,
1245
+ case_id_key=case_id_key,
1246
+ )
1247
+
1248
+ properties = get_properties(
1249
+ log,
1250
+ activity_key=activity_key,
1251
+ timestamp_key=timestamp_key,
1252
+ case_id_key=case_id_key,
1253
+ )
1254
+ properties["zeta"] = zeta
1255
+
1256
+ from pm4py.algo.conformance.temporal_profile import (
1257
+ algorithm as temporal_profile_conformance,
1258
+ )
1259
+
1260
+ result = temporal_profile_conformance.apply(
1261
+ log, temporal_profile, parameters=properties
1262
+ )
1263
+
1264
+ if return_diagnostics_dataframe:
1265
+ return temporal_profile_conformance.get_diagnostics_dataframe(
1266
+ log, result, parameters=properties
1267
+ )
1268
+
1269
+ return result
1270
+
1271
+
1272
+ def conformance_declare(
1273
+ log: Union[EventLog, pd.DataFrame],
1274
+ declare_model: Dict[str, Dict[Any, Dict[str, int]]],
1275
+ activity_key: str = "concept:name",
1276
+ timestamp_key: str = "time:timestamp",
1277
+ case_id_key: str = "case:concept:name",
1278
+ return_diagnostics_dataframe: bool = constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME,
1279
+ ) -> List[Dict[str, Any]]:
1280
+ """
1281
+ Apply conformance checking against a DECLARE model.
1282
+
1283
+ Reference paper:
1284
+ F. M. Maggi, A. J. Mooij, and W. M. P. van der Aalst, "User-guided discovery of declarative process models," 2011 IEEE Symposium on Computational Intelligence and Data Mining (CIDM), Paris, France, 2011, pp. 192-199, doi: 10.1109/CIDM.2011.5949297.
1285
+
1286
+ :param log: Event log.
1287
+ :param declare_model: DECLARE model represented as a nested dictionary.
1288
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
1289
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
1290
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
1291
+ :param return_diagnostics_dataframe: If possible, returns a dataframe with the diagnostics instead of the usual output (default is `constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME`).
1292
+ :return: A list of dictionaries containing diagnostics for each trace.
1293
+ :rtype: ``List[Dict[str, Any]]``
1294
+
1295
+ Example:
1296
+ .. code-block:: python
1297
+
1298
+ import pm4py
1299
+
1300
+ log = pm4py.read_xes("C:/receipt.xes")
1301
+ declare_model = pm4py.discover_declare(log)
1302
+ conf_result = pm4py.conformance_declare(
1303
+ log,
1304
+ declare_model,
1305
+ activity_key='concept:name',
1306
+ case_id_key='case:concept:name',
1307
+ timestamp_key='time:timestamp'
1308
+ )
1309
+
1310
+ """
1311
+ __event_log_deprecation_warning(log)
1312
+
1313
+ if check_is_pandas_dataframe(log):
1314
+ check_pandas_dataframe_columns(
1315
+ log,
1316
+ activity_key=activity_key,
1317
+ timestamp_key=timestamp_key,
1318
+ case_id_key=case_id_key,
1319
+ )
1320
+
1321
+ if return_diagnostics_dataframe:
1322
+ from pm4py.convert import convert_to_event_log
1323
+
1324
+ log = convert_to_event_log(log, case_id_key=case_id_key)
1325
+ case_id_key = None
1326
+
1327
+ properties = get_properties(
1328
+ log,
1329
+ activity_key=activity_key,
1330
+ timestamp_key=timestamp_key,
1331
+ case_id_key=case_id_key,
1332
+ )
1333
+
1334
+ from pm4py.algo.conformance.declare import algorithm as declare_conformance
1335
+
1336
+ result = declare_conformance.apply(
1337
+ log, declare_model, parameters=properties
1338
+ )
1339
+
1340
+ if return_diagnostics_dataframe:
1341
+ return declare_conformance.get_diagnostics_dataframe(
1342
+ log, result, parameters=properties
1343
+ )
1344
+
1345
+ return result
1346
+
1347
+
1348
+ def conformance_log_skeleton(
1349
+ log: Union[EventLog, pd.DataFrame],
1350
+ log_skeleton: Dict[str, Any],
1351
+ activity_key: str = "concept:name",
1352
+ timestamp_key: str = "time:timestamp",
1353
+ case_id_key: str = "case:concept:name",
1354
+ return_diagnostics_dataframe: bool = constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME,
1355
+ ) -> List[Set[Any]]:
1356
+ """
1357
+ Perform conformance checking using the log skeleton.
1358
+
1359
+ Reference paper:
1360
+ Verbeek, H. M. W., and R. Medeiros de Carvalho. "Log skeletons: A classification approach to process discovery." arXiv preprint arXiv:1806.08247 (2018).
1361
+
1362
+ A log skeleton is a declarative model consisting of six different constraints:
1363
+
1364
+ - **directly_follows**: Specifies strict bounds on activities directly following each other. For example, 'A should be directly followed by B' and 'B should be directly followed by C'.
1365
+ - **always_before**: Specifies that certain activities may only be executed if some other activities have been executed earlier in the case history. For example, 'C should always be preceded by A'.
1366
+ - **always_after**: Specifies that certain activities should always trigger the execution of other activities in the future history of the case. For example, 'A should always be followed by C'.
1367
+ - **equivalence**: Specifies that pairs of activities should occur the same number of times within a case. For example, 'B and C should always happen the same number of times'.
1368
+ - **never_together**: Specifies that certain pairs of activities should never occur together in the case history. For example, 'No case should contain both C and D'.
1369
+ - **activ_occurrences**: Specifies the allowed number of occurrences per activity. For example, 'A is allowed to be executed 1 or 2 times, and B is allowed to be executed 1 to 4 times'.
1370
+
1371
+ :param log: Log object.
1372
+ :param log_skeleton: Log skeleton object, expressed as dictionaries of the six constraints along with the discovered rules.
1373
+ :param activity_key: Attribute to be used for the activity (default is "concept:name").
1374
+ :param timestamp_key: Attribute to be used for the timestamp (default is "time:timestamp").
1375
+ :param case_id_key: Attribute to be used as the case identifier (default is "case:concept:name").
1376
+ :param return_diagnostics_dataframe: If possible, returns a dataframe with the diagnostics instead of the usual output (default is `constants.DEFAULT_RETURN_DIAGNOSTICS_DATAFRAME`).
1377
+ :return: A list of sets containing deviations for each case.
1378
+ :rtype: ``List[Set[Any]]``
1379
+
1380
+ Example:
1381
+ .. code-block:: python
1382
+
1383
+ import pm4py
1384
+
1385
+ log_skeleton = pm4py.discover_log_skeleton(
1386
+ dataframe,
1387
+ noise_threshold=0.1,
1388
+ activity_key='concept:name',
1389
+ case_id_key='case:concept:name',
1390
+ timestamp_key='time:timestamp'
1391
+ )
1392
+ conformance_lsk = pm4py.conformance_log_skeleton(
1393
+ dataframe,
1394
+ log_skeleton,
1395
+ activity_key='concept:name',
1396
+ case_id_key='case:concept:name',
1397
+ timestamp_key='time:timestamp'
1398
+ )
1399
+
1400
+ """
1401
+ __event_log_deprecation_warning(log)
1402
+
1403
+ if check_is_pandas_dataframe(log):
1404
+ check_pandas_dataframe_columns(
1405
+ log,
1406
+ activity_key=activity_key,
1407
+ timestamp_key=timestamp_key,
1408
+ case_id_key=case_id_key,
1409
+ )
1410
+
1411
+ if return_diagnostics_dataframe:
1412
+ from pm4py.convert import convert_to_event_log
1413
+
1414
+ log = convert_to_event_log(log, case_id_key=case_id_key)
1415
+ case_id_key = None
1416
+
1417
+ properties = get_properties(
1418
+ log,
1419
+ activity_key=activity_key,
1420
+ timestamp_key=timestamp_key,
1421
+ case_id_key=case_id_key,
1422
+ )
1423
+
1424
+ from pm4py.algo.conformance.log_skeleton import (
1425
+ algorithm as log_skeleton_conformance,
1426
+ )
1427
+
1428
+ result = log_skeleton_conformance.apply(
1429
+ log, log_skeleton, parameters=properties
1430
+ )
1431
+
1432
+ if return_diagnostics_dataframe:
1433
+ return log_skeleton_conformance.get_diagnostics_dataframe(
1434
+ log, result, parameters=properties
1435
+ )
1436
+
1437
+ return result
1438
+
1439
+
1440
+ def conformance_ocdfg(
1441
+ ocel: Union[OCEL, Dict[str, Any]],
1442
+ model: Dict[str, Any],
1443
+ variant=None,
1444
+ parameters: Optional[Dict[Any, Any]] = None,
1445
+ ) -> Dict[str, Any]:
1446
+ """
1447
+ Performs OC-DFG-based conformance checking between an object-centric event log (or OC-DFG) and a normative OC-DFG.
1448
+
1449
+ An object-centric directly-follows graph is expressed as a dictionary containing the following properties:
1450
+
1451
+ - activities: complete set of activities derived from the object-centric event log
1452
+ - object_types: complete set of object types derived from the object-centric event log
1453
+ - edges: dictionary connecting each object type to a set of directly-followed arcs between activities
1454
+ - activities_indep: dictionary linking each activity, regardless of the object type
1455
+ - activities_ot: dictionary linking each object type to another dictionary
1456
+ - start_activities: dictionary linking each object type to start activities
1457
+ - end_activities: dictionary linking each object type to end activities
1458
+
1459
+ Published in: https://publications.rwth-aachen.de/record/1014107
1460
+
1461
+ :param ocel: Object-centric event log or OC-DFG representing the real behavior.
1462
+ :param model: Normative OC-DFG obtained from discovery.
1463
+ :param variant: Variant of the OC-DFG conformance algorithm to use (default: graph comparison).
1464
+ :param parameters: Optional variant-specific parameters.
1465
+ :return: Dictionary containing conformance diagnostics.
1466
+ :rtype: ``Dict[str, Any]``
1467
+
1468
+ .. code-block:: python3
1469
+
1470
+ import pm4py
1471
+
1472
+ diagnostics = pm4py.conformance_ocdfg(ocel, ocdfg_model)
1473
+ """
1474
+ from pm4py.algo.conformance.ocel.ocdfg import algorithm as ocdfg_conformance
1475
+
1476
+ if variant is None:
1477
+ variant = ocdfg_conformance.Variants.GRAPH_COMPARISON
1478
+
1479
+ return ocdfg_conformance.apply(ocel, model, variant=variant, parameters=parameters)
1480
+
1481
+
1482
+ def conformance_otg(
1483
+ ocel: Union[OCEL, Tuple[Set[str], Dict[Tuple[str, str, str], int]]],
1484
+ model: Tuple[Set[str], Dict[Tuple[str, str, str], int]],
1485
+ variant=None,
1486
+ parameters: Optional[Dict[Any, Any]] = None,
1487
+ ) -> Dict[str, Any]:
1488
+ """
1489
+ Performs OTG-based conformance checking between an object-centric event log (or OTG) and a normative OTG.
1490
+
1491
+ An OTG summarizes how object types are related across different interaction graphs extracted from the OCEL.
1492
+ Specifically, an OTG is a tuple containing:
1493
+
1494
+ - The set of object types
1495
+ - The edges along with the frequency, where each edge is (object_type1, relationship, object_type2).
1496
+
1497
+ Relationship can be:
1498
+
1499
+ * object_interaction (objects related in some event)
1500
+ * object_descendants (lifecycle of the first event starts before the other object)
1501
+ * object_inheritance (lifecycle of the first object ends exactly when the second one starts)
1502
+ * object_cobirth (objects start their lifecycle in the same event)
1503
+ * object_codeath (objects end their lifecycle in the sae event)
1504
+
1505
+ Published in: https://publications.rwth-aachen.de/record/1014107
1506
+
1507
+ :param ocel: Object-centric event log or OTG capturing the real behavior.
1508
+ :param model: Normative OTG, typically discovered from a reference log.
1509
+ :param variant: Variant of the OTG conformance algorithm to use (default: graph comparison).
1510
+ :param parameters: Optional variant-specific parameters.
1511
+ :return: Dictionary containing OTG conformance diagnostics.
1512
+ :rtype: ``Dict[str, Any]``
1513
+
1514
+ .. code-block:: python3
1515
+
1516
+ import pm4py
1517
+
1518
+ diagnostics = pm4py.conformance_otg(ocel, otg_model)
1519
+ """
1520
+ from pm4py.algo.conformance.ocel.otg import algorithm as otg_conformance
1521
+
1522
+ if variant is None:
1523
+ variant = otg_conformance.Variants.GRAPH_COMPARISON
1524
+
1525
+ return otg_conformance.apply(ocel, model, variant=variant, parameters=parameters)
1526
+
1527
+
1528
+ def conformance_etot(
1529
+ ocel: Union[
1530
+ OCEL,
1531
+ Tuple[
1532
+ Set[str],
1533
+ Set[str],
1534
+ Set[Tuple[str, str]],
1535
+ Dict[Tuple[str, str], int],
1536
+ ],
1537
+ ],
1538
+ model: Tuple[
1539
+ Set[str],
1540
+ Set[str],
1541
+ Set[Tuple[str, str]],
1542
+ Dict[Tuple[str, str], int],
1543
+ ],
1544
+ variant=None,
1545
+ parameters: Optional[Dict[Any, Any]] = None,
1546
+ ) -> Dict[str, Any]:
1547
+ """
1548
+ Performs ET-OT-based conformance checking between an object-centric event log (or ET-OT graph) and a normative ET-OT graph.
1549
+
1550
+ The ET-OT graph captures the relationships between event types and object types along with their frequencies.
1551
+ Specifically, an ET-OT graph is a tuple consisting of:
1552
+
1553
+ - Set of activities
1554
+ - Set of object types
1555
+ - Set of relationships, where an edge (a, ot) indicates that events of type a are associated with objects of type ot
1556
+ - A dictionary associating each relationship to a weight (frequency)
1557
+
1558
+ Published in: https://publications.rwth-aachen.de/record/1014107
1559
+
1560
+ :param ocel: Object-centric event log or ET-OT graph capturing the real behavior.
1561
+ :param model: Normative ET-OT graph, typically discovered from a reference log.
1562
+ :param variant: Variant of the ET-OT conformance algorithm to use (default: graph comparison).
1563
+ :param parameters: Optional variant-specific parameters.
1564
+ :return: Dictionary containing ET-OT conformance diagnostics.
1565
+ :rtype: ``Dict[str, Any]``
1566
+
1567
+ .. code-block:: python3
1568
+
1569
+ import pm4py
1570
+
1571
+ diagnostics = pm4py.conformance_etot(ocel, etot_model)
1572
+ """
1573
+ from pm4py.algo.conformance.ocel.etot import algorithm as etot_conformance
1574
+
1575
+ if variant is None:
1576
+ variant = etot_conformance.Variants.GRAPH_COMPARISON
1577
+
1578
+ return etot_conformance.apply(ocel, model, variant=variant, parameters=parameters)
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/connectors.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+
23
+ from typing import Optional
24
+ import pandas as pd
25
+ from pm4py.objects.ocel.obj import OCEL
26
+
27
+
28
+ def extract_log_outlook_mails() -> pd.DataFrame:
29
+ """
30
+ Extracts the history of conversations from the local instance of Microsoft Outlook
31
+ running on the current computer.
32
+
33
+ Columns:
34
+
35
+ - **CASE ID (case:concept:name)**: Identifier of the conversation.
36
+ - **ACTIVITY (concept:name)**: Activity performed in the current item (e.g., send e-mail, receive e-mail, refuse meeting).
37
+ - **TIMESTAMP (time:timestamp)**: Timestamp of creation of the item in Outlook.
38
+ - **RESOURCE (org:resource)**: Sender of the current item.
39
+
40
+ See Also:
41
+
42
+ * [MailItem Properties](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.outlook.mailitem?redirectedfrom=MSDN&view=outlook-pia#properties_)
43
+ * [OlObjectClass Enumeration](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.outlook.olobjectclass?view=outlook-pia)
44
+
45
+ :rtype: ``pd.DataFrame``
46
+
47
+ Example::
48
+
49
+ import pm4py
50
+
51
+ dataframe = pm4py.connectors.extract_log_outlook_mails()
52
+
53
+ """
54
+ from pm4py.algo.connectors.variants import outlook_mail_extractor
55
+
56
+ return outlook_mail_extractor.apply()
57
+
58
+
59
+ def extract_log_outlook_calendar(
60
+ email_user: Optional[str] = None, calendar_id: int = 9
61
+ ) -> pd.DataFrame:
62
+ """
63
+ Extracts the history of calendar events (creation, update, start, end)
64
+ into a Pandas DataFrame from the local Outlook instance running on the current computer.
65
+
66
+ Columns:
67
+
68
+ - **CASE ID (case:concept:name)**: Identifier of the meeting.
69
+ - **ACTIVITY (concept:name)**: One of the following activities: Meeting Created, Last Change of Meeting, Meeting Started, Meeting Completed.
70
+ - **TIMESTAMP (time:timestamp)**: Timestamp of the event.
71
+ - **case:subject**: Subject of the meeting.
72
+
73
+ :param email_user: (optional) E-mail address from which the (shared) calendar should be extracted.
74
+ :param calendar_id: Identifier of the calendar for the given user (default: 9).
75
+
76
+ :rtype: ``pd.DataFrame``
77
+
78
+ .. code-block:: python3
79
+
80
+ import pm4py
81
+
82
+ # Extract using default parameters
83
+ dataframe = pm4py.connectors.extract_log_outlook_calendar()
84
+
85
+ # Extract using a specific email user
86
+ dataframe = pm4py.connectors.extract_log_outlook_calendar("vacation-calendar@workplace.eu")
87
+ """
88
+ from pm4py.algo.connectors.variants import outlook_calendar
89
+
90
+ parameters = {}
91
+ parameters[outlook_calendar.Parameters.EMAIL_USER] = email_user
92
+ parameters[outlook_calendar.Parameters.CALENDAR_ID] = calendar_id
93
+ return outlook_calendar.apply(parameters=parameters)
94
+
95
+
96
+ def extract_log_windows_events() -> pd.DataFrame:
97
+ """
98
+ Extracts a process mining DataFrame from all events recorded in the Windows registry.
99
+
100
+ Columns:
101
+
102
+ - **CASE ID (case:concept:name)**: Name of the computer emitting the events.
103
+ - **ACTIVITY (concept:name)**: Concatenation of the source name of the event and the event identifier. (See [Win32_NTLogEvent](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/eventlogprov/win32-ntlogevent))
104
+ - **TIMESTAMP (time:timestamp)**: Timestamp of event generation.
105
+ - **RESOURCE (org:resource)**: Username involved in the event.
106
+
107
+ :rtype: ``pd.DataFrame``
108
+
109
+ .. code-block:: python3
110
+
111
+ import pm4py
112
+
113
+ dataframe = pm4py.connectors.extract_log_windows_events()
114
+ """
115
+ from pm4py.algo.connectors.variants import windows_events
116
+
117
+ return windows_events.apply()
118
+
119
+
120
+ def extract_log_chrome_history(
121
+ history_db_path: Optional[str] = None,
122
+ ) -> pd.DataFrame:
123
+ """
124
+ Extracts a DataFrame containing the navigation history of Google Chrome.
125
+ Please ensure that Google Chrome history is closed when extracting.
126
+
127
+ Columns:
128
+
129
+ - **CASE ID (case:concept:name)**: Identifier of the extracted profile.
130
+ - **ACTIVITY (concept:name)**: Complete path of the website, excluding GET arguments.
131
+ - **TIMESTAMP (time:timestamp)**: Timestamp of the visit.
132
+
133
+ :param history_db_path: Path to the Google Chrome history database (default: location of the Windows folder).
134
+ :rtype: ``pd.DataFrame``
135
+
136
+ .. code-block:: python3
137
+
138
+ import pm4py
139
+
140
+ dataframe = pm4py.connectors.extract_log_chrome_history()
141
+ """
142
+ from pm4py.algo.connectors.variants import chrome_history
143
+
144
+ parameters = {}
145
+ if history_db_path is not None:
146
+ parameters[chrome_history.Parameters.HISTORY_DB_PATH] = history_db_path
147
+ return chrome_history.apply(parameters=parameters)
148
+
149
+
150
+ def extract_log_firefox_history(
151
+ history_db_path: Optional[str] = None,
152
+ ) -> pd.DataFrame:
153
+ """
154
+ Extracts a DataFrame containing the navigation history of Mozilla Firefox.
155
+ Please ensure that Mozilla Firefox history is closed when extracting.
156
+
157
+ Columns:
158
+
159
+ - **CASE ID (case:concept:name)**: Identifier of the extracted profile.
160
+ - **ACTIVITY (concept:name)**: Complete path of the website, excluding GET arguments.
161
+ - **TIMESTAMP (time:timestamp)**: Timestamp of the visit.
162
+
163
+ :param history_db_path: Path to the Mozilla Firefox history database (default: location of the Windows folder).
164
+ :rtype: ``pd.DataFrame``
165
+
166
+ .. code-block:: python3
167
+
168
+ import pm4py
169
+
170
+ dataframe = pm4py.connectors.extract_log_firefox_history()
171
+ """
172
+ from pm4py.algo.connectors.variants import firefox_history
173
+
174
+ parameters = {}
175
+ if history_db_path is not None:
176
+ parameters[firefox_history.Parameters.HISTORY_DB_PATH] = (
177
+ history_db_path
178
+ )
179
+ return firefox_history.apply(parameters=parameters)
180
+
181
+
182
+ def extract_log_github(
183
+ owner: str = "pm4py",
184
+ repo: str = "pm4py-core",
185
+ auth_token: Optional[str] = None,
186
+ ) -> pd.DataFrame:
187
+ """
188
+ Extracts a DataFrame containing the history of issues from a GitHub repository.
189
+ Due to API rate limits for public and registered users, only a subset of events may be returned.
190
+
191
+ :param owner: Owner of the repository (e.g., pm4py).
192
+ :param repo: Name of the repository (e.g., pm4py-core).
193
+ :param auth_token: Authorization token.
194
+ :rtype: ``pd.DataFrame``
195
+
196
+ .. code-block:: python3
197
+
198
+ import pm4py
199
+
200
+ dataframe = pm4py.connectors.extract_log_github(owner='pm4py', repo='pm4py-core')
201
+ """
202
+ from pm4py.algo.connectors.variants import github_repo
203
+
204
+ parameters = {}
205
+ parameters[github_repo.Parameters.OWNER] = owner
206
+ parameters[github_repo.Parameters.REPOSITORY] = repo
207
+ parameters[github_repo.Parameters.AUTH_TOKEN] = auth_token
208
+ return github_repo.apply(parameters)
209
+
210
+
211
+ def extract_log_camunda_workflow(connection_string: str) -> pd.DataFrame:
212
+ """
213
+ Extracts a DataFrame from the Camunda workflow system. In addition to traditional columns,
214
+ the process ID of the process in Camunda is included.
215
+
216
+ :param connection_string: ODBC connection string to the Camunda database.
217
+ :rtype: ``pd.DataFrame``
218
+
219
+ .. code-block:: python3
220
+
221
+ import pm4py
222
+
223
+ dataframe = pm4py.connectors.extract_log_camunda_workflow(
224
+ 'Driver={PostgreSQL Unicode(x64)};SERVER=127.0.0.3;DATABASE=process-engine;UID=xx;PWD=yy'
225
+ )
226
+ """
227
+ from pm4py.algo.connectors.variants import camunda_workflow
228
+
229
+ parameters = {}
230
+ parameters[camunda_workflow.Parameters.CONNECTION_STRING] = (
231
+ connection_string
232
+ )
233
+ return camunda_workflow.apply(None, parameters=parameters)
234
+
235
+
236
+ def extract_log_sap_o2c(
237
+ connection_string: str, prefix: str = ""
238
+ ) -> pd.DataFrame:
239
+ """
240
+ Extracts a DataFrame for the SAP Order-to-Cash (O2C) process.
241
+
242
+ :param connection_string: ODBC connection string to the SAP database.
243
+ :param prefix: Prefix for the tables (e.g., SAPSR3.).
244
+ :rtype: ``pd.DataFrame``
245
+
246
+ .. code-block:: python3
247
+
248
+ import pm4py
249
+
250
+ dataframe = pm4py.connectors.extract_log_sap_o2c(
251
+ 'Driver={Oracle in instantclient_21_6};DBQ=127.0.0.3:1521/ZIB;UID=xx;PWD=yy'
252
+ )
253
+ """
254
+ from pm4py.algo.connectors.variants import sap_o2c
255
+
256
+ parameters = {}
257
+ parameters[sap_o2c.Parameters.CONNECTION_STRING] = connection_string
258
+ parameters[sap_o2c.Parameters.PREFIX] = prefix
259
+ return sap_o2c.apply(None, parameters=parameters)
260
+
261
+
262
+ def extract_log_sap_accounting(
263
+ connection_string: str, prefix: str = ""
264
+ ) -> pd.DataFrame:
265
+ """
266
+ Extracts a DataFrame for the SAP Accounting process.
267
+
268
+ :param connection_string: ODBC connection string to the SAP database.
269
+ :param prefix: Prefix for the tables (e.g., SAPSR3.).
270
+ :rtype: ``pd.DataFrame``
271
+
272
+ .. code-block:: python3
273
+
274
+ import pm4py
275
+
276
+ dataframe = pm4py.connectors.extract_log_sap_accounting(
277
+ 'Driver={Oracle in instantclient_21_6};DBQ=127.0.0.3:1521/ZIB;UID=xx;PWD=yy'
278
+ )
279
+ """
280
+ from pm4py.algo.connectors.variants import sap_accounting
281
+
282
+ parameters = {}
283
+ parameters[sap_accounting.Parameters.CONNECTION_STRING] = connection_string
284
+ parameters[sap_accounting.Parameters.PREFIX] = prefix
285
+ return sap_accounting.apply(None, parameters=parameters)
286
+
287
+
288
+ def extract_ocel_outlook_mails() -> OCEL:
289
+ """
290
+ Extracts the history of conversations from the local instance of Microsoft Outlook
291
+ running on the current computer as an object-centric event log.
292
+
293
+ Columns:
294
+
295
+ - **ACTIVITY (ocel:activity)**: Activity performed in the current item (e.g., send e-mail, receive e-mail, refuse meeting).
296
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of creation of the item in Outlook.
297
+
298
+ Object Types:
299
+
300
+ - **org:resource**: Sender of the mail.
301
+ - **recipients**: List of recipients of the mail.
302
+ - **topic**: Topic of the discussion.
303
+
304
+ See Also:
305
+
306
+ * [MailItem Properties](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.outlook.mailitem?redirectedfrom=MSDN&view=outlook-pia#properties_)
307
+ * [OlObjectClass Enumeration](https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.outlook.olobjectclass?view=outlook-pia)
308
+
309
+ :rtype: ``OCEL``
310
+
311
+ .. code-block:: python3
312
+
313
+ import pm4py
314
+
315
+ ocel = pm4py.connectors.extract_ocel_outlook_mails()
316
+
317
+ """
318
+ import pm4py
319
+
320
+ dataframe = pm4py.connectors.extract_log_outlook_mails()
321
+ return pm4py.convert_log_to_ocel(
322
+ dataframe,
323
+ object_types=["case:concept:name"],
324
+ timestamp_column="time:timestamp",
325
+ additional_object_attributes={"case:concept:name": ["org:resource", "recipients", "topic"]},
326
+ )
327
+
328
+
329
+ def extract_ocel_outlook_calendar(
330
+ email_user: Optional[str] = None, calendar_id: int = 9
331
+ ) -> OCEL:
332
+ """
333
+ Extracts the history of calendar events (creation, update, start, end)
334
+ as an object-centric event log from the local Outlook instance running on the current computer.
335
+
336
+ Columns:
337
+
338
+ - **ACTIVITY (ocel:activity)**: One of the following activities: Meeting Created, Last Change of Meeting, Meeting Started, Meeting Completed.
339
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the event.
340
+
341
+ Object Types:
342
+
343
+ - **case:concept:name**: Identifier of the meeting.
344
+ - **case:subject**: Subject of the meeting.
345
+
346
+ :param email_user: (optional) E-mail address from which the (shared) calendar should be extracted.
347
+ :param calendar_id: Identifier of the calendar for the given user (default: 9).
348
+ :rtype: ``OCEL``
349
+
350
+ .. code-block:: python3
351
+
352
+ import pm4py
353
+
354
+ # Extract using default parameters
355
+ ocel = pm4py.connectors.extract_ocel_outlook_calendar()
356
+
357
+ # Extract using a specific email user
358
+ ocel = pm4py.connectors.extract_ocel_outlook_calendar("vacation-calendar@workplace.eu")
359
+ """
360
+ import pm4py
361
+
362
+ dataframe = pm4py.connectors.extract_log_outlook_calendar(
363
+ email_user, calendar_id
364
+ )
365
+ return pm4py.convert_log_to_ocel(
366
+ dataframe,
367
+ object_types=["case:concept:name"],
368
+ timestamp_column="time:timestamp",
369
+ additional_object_attributes={"case:concept:name": ["case:concept:name", "case:subject"]},
370
+ )
371
+
372
+
373
+ def extract_ocel_windows_events() -> OCEL:
374
+ """
375
+ Extracts an object-centric event log from all events recorded in the Windows registry.
376
+
377
+ Columns:
378
+
379
+ - **ACTIVITY (ocel:activity)**: Concatenation of the source name of the event and the event identifier. (See [Win32_NTLogEvent](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/eventlogprov/win32-ntlogevent))
380
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of event generation.
381
+
382
+ Object Types:
383
+
384
+ - **categoryString**: Translation of the subcategory. The translation is source-specific.
385
+ - **computerName**: Name of the computer that generated the event.
386
+ - **eventIdentifier**: Identifier of the event, specific to the source that generated the event log entry.
387
+ - **eventType**: Event type classification (1=Error; 2=Warning; 3=Information; 4=Security Audit Success; 5=Security Audit Failure).
388
+ - **sourceName**: Name of the source (application, service, driver, or subsystem) that generated the entry.
389
+ - **user**: Username of the logged-on user when the event occurred. If the username cannot be determined, this will be NULL.
390
+
391
+ :rtype: ``OCEL``
392
+
393
+ .. code-block:: python3
394
+
395
+ import pm4py
396
+
397
+ ocel = pm4py.connectors.extract_ocel_windows_events()
398
+ """
399
+ import pm4py
400
+
401
+ dataframe = pm4py.connectors.extract_log_windows_events()
402
+ return pm4py.convert_log_to_ocel(
403
+ dataframe,
404
+ object_types="case:concept:name",
405
+ timestamp_column="time:timestamp",
406
+ additional_object_attributes={"case:concept:name": [
407
+ "categoryString",
408
+ "computerName",
409
+ "eventIdentifier",
410
+ "eventType",
411
+ "sourceName",
412
+ "user",
413
+ ]},
414
+ )
415
+
416
+
417
+ def extract_ocel_chrome_history(history_db_path: Optional[str] = None) -> OCEL:
418
+ """
419
+ Extracts an object-centric event log containing the navigation history of Google Chrome.
420
+ Please ensure that Google Chrome history is closed when extracting.
421
+
422
+ Columns:
423
+
424
+ - **ACTIVITY (ocel:activity)**: Complete path of the website, excluding GET arguments.
425
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the visit.
426
+
427
+ Object Types:
428
+
429
+ - **case:concept:name**: Profile of Chrome used to visit the site.
430
+ - **complete_url**: Complete URL of the website.
431
+ - **url_wo_parameters**: Complete URL excluding the part after '?'.
432
+ - **domain**: Domain of the visited website.
433
+
434
+ :param history_db_path: Path to the Google Chrome history database (default: location of the Windows folder).
435
+ :rtype: ``OCEL``
436
+
437
+ .. code-block:: python3
438
+
439
+ import pm4py
440
+
441
+ ocel = pm4py.connectors.extract_ocel_chrome_history()
442
+ """
443
+ import pm4py
444
+
445
+ dataframe = pm4py.connectors.extract_log_chrome_history(history_db_path)
446
+ return pm4py.convert_log_to_ocel(
447
+ dataframe,
448
+ object_types=["case:concept:name"],
449
+ timestamp_column="time:timestamp",
450
+ additional_object_attributes={"case:concept:name": [
451
+ "case:concept:name",
452
+ "complete_url",
453
+ "url_wo_parameters",
454
+ "domain",
455
+ ]},
456
+ )
457
+
458
+
459
+ def extract_ocel_firefox_history(
460
+ history_db_path: Optional[str] = None,
461
+ ) -> OCEL:
462
+ """
463
+ Extracts an object-centric event log containing the navigation history of Mozilla Firefox.
464
+ Please ensure that Mozilla Firefox history is closed when extracting.
465
+
466
+ Columns:
467
+
468
+ - **ACTIVITY (ocel:activity)**: Complete path of the website, excluding GET arguments.
469
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the visit.
470
+
471
+ Object Types:
472
+
473
+ - **case:concept:name**: Profile of Firefox used to visit the site.
474
+ - **complete_url**: Complete URL of the website.
475
+ - **url_wo_parameters**: Complete URL excluding the part after '?'.
476
+ - **domain**: Domain of the visited website.
477
+
478
+ :param history_db_path: Path to the Mozilla Firefox history database (default: location of the Windows folder).
479
+ :rtype: ``OCEL``
480
+
481
+ .. code-block:: python3
482
+
483
+ import pm4py
484
+
485
+ ocel = pm4py.connectors.extract_ocel_firefox_history()
486
+ """
487
+ import pm4py
488
+
489
+ dataframe = pm4py.connectors.extract_log_firefox_history(history_db_path)
490
+ return pm4py.convert_log_to_ocel(
491
+ dataframe,
492
+ object_types=["case:concept:name"],
493
+ timestamp_column="time:timestamp",
494
+ additional_object_attributes={"case:concept:name": [
495
+ "case:concept:name",
496
+ "complete_url",
497
+ "url_wo_parameters",
498
+ "domain",
499
+ ]},
500
+ )
501
+
502
+
503
+ def extract_ocel_github(
504
+ owner: str = "pm4py",
505
+ repo: str = "pm4py-core",
506
+ auth_token: Optional[str] = None,
507
+ ) -> OCEL:
508
+ """
509
+ Extracts an object-centric event log containing the history of issues from a GitHub repository.
510
+ Due to API rate limits for public and registered users, only a subset of events may be returned.
511
+
512
+ Columns:
513
+
514
+ - **ACTIVITY (ocel:activity)**: The event type (e.g., created, commented, closed, subscribed).
515
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the event execution.
516
+
517
+ Object Types:
518
+
519
+ - **case:concept:name**: URL of the events related to the issue.
520
+ - **org:resource**: Involved resource.
521
+ - **case:repo**: Repository in which the issue was created.
522
+
523
+ :param owner: Owner of the repository (e.g., pm4py).
524
+ :param repo: Name of the repository (e.g., pm4py-core).
525
+ :param auth_token: Authorization token.
526
+ :rtype: ``OCEL``
527
+
528
+ .. code-block:: python3
529
+
530
+ import pm4py
531
+
532
+ ocel = pm4py.connectors.extract_ocel_github(owner='pm4py', repo='pm4py-core')
533
+ """
534
+ import pm4py
535
+
536
+ dataframe = pm4py.connectors.extract_log_github(owner, repo, auth_token)
537
+ return pm4py.convert_log_to_ocel(
538
+ dataframe,
539
+ object_types=["case:concept:name"],
540
+ timestamp_column="time:timestamp",
541
+ additional_object_attributes={"case:concept:name": ["case:concept:name", "org:resource", "case:repo"]},
542
+ )
543
+
544
+
545
+ def extract_ocel_camunda_workflow(connection_string: str) -> OCEL:
546
+ """
547
+ Extracts an object-centric event log from the Camunda workflow system.
548
+
549
+ Columns:
550
+
551
+ - **ACTIVITY (ocel:activity)**: Activity performed within Camunda.
552
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the activity execution.
553
+
554
+ Object Types:
555
+
556
+ - **case:concept:name**: Identifier of the case.
557
+ - **processID**: Process ID within Camunda.
558
+ - **org:resource**: Resource involved in the activity.
559
+
560
+ :param connection_string: ODBC connection string to the Camunda database.
561
+ :rtype: ``OCEL``
562
+
563
+ .. code-block:: python3
564
+
565
+ import pm4py
566
+
567
+ ocel = pm4py.connectors.extract_ocel_camunda_workflow(
568
+ 'Driver={PostgreSQL Unicode(x64)};SERVER=127.0.0.3;DATABASE=process-engine;UID=xx;PWD=yy'
569
+ )
570
+ """
571
+ import pm4py
572
+
573
+ dataframe = pm4py.connectors.extract_log_camunda_workflow(
574
+ connection_string
575
+ )
576
+ return pm4py.convert_log_to_ocel(
577
+ dataframe,
578
+ object_types=["case:concept:name"],
579
+ timestamp_column="time:timestamp",
580
+ additional_object_attributes={"case:concept:name": ["case:concept:name", "processID", "org:resource"]},
581
+ )
582
+
583
+
584
+ def extract_ocel_sap_o2c(connection_string: str, prefix: str = "") -> OCEL:
585
+ """
586
+ Extracts an object-centric event log for the SAP Order-to-Cash (O2C) process.
587
+
588
+ Columns:
589
+
590
+ - **ACTIVITY (ocel:activity)**: Activity performed in the O2C process.
591
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the activity execution.
592
+
593
+ Object Types:
594
+
595
+ - **case:concept:name**: Identifier of the case.
596
+ - **org:resource**: Resource involved in the activity.
597
+
598
+ :param connection_string: ODBC connection string to the SAP database.
599
+ :param prefix: Prefix for the tables (e.g., SAPSR3.).
600
+ :rtype: ``OCEL``
601
+
602
+ .. code-block:: python3
603
+
604
+ import pm4py
605
+
606
+ ocel = pm4py.connectors.extract_ocel_sap_o2c(
607
+ 'Driver={Oracle in instantclient_21_6};DBQ=127.0.0.3:1521/ZIB;UID=xx;PWD=yy'
608
+ )
609
+ """
610
+ import pm4py
611
+
612
+ dataframe = pm4py.connectors.extract_log_sap_o2c(
613
+ connection_string, prefix=prefix
614
+ )
615
+ return pm4py.convert_log_to_ocel(
616
+ dataframe,
617
+ object_types=["case:concept:name"],
618
+ timestamp_column="time:timestamp",
619
+ additional_object_attributes={"case:concept:name": ["case:concept:name", "org:resource"]},
620
+ )
621
+
622
+
623
+ def extract_ocel_sap_accounting(
624
+ connection_string: str, prefix: str = ""
625
+ ) -> OCEL:
626
+ """
627
+ Extracts an object-centric event log for the SAP Accounting process.
628
+
629
+ Columns:
630
+
631
+ - **ACTIVITY (ocel:activity)**: Activity performed in the Accounting process.
632
+ - **TIMESTAMP (ocel:timestamp)**: Timestamp of the activity execution.
633
+
634
+ Object Types:
635
+
636
+ - **case:concept:name**: Identifier of the case.
637
+ - **org:resource**: Resource involved in the activity.
638
+
639
+ :param connection_string: ODBC connection string to the SAP database.
640
+ :param prefix: Prefix for the tables (e.g., SAPSR3.).
641
+ :rtype: ``OCEL``
642
+
643
+ .. code-block:: python3
644
+
645
+ import pm4py
646
+
647
+ ocel = pm4py.connectors.extract_ocel_sap_accounting(
648
+ 'Driver={Oracle in instantclient_21_6};DBQ=127.0.0.3:1521/ZIB;UID=xx;PWD=yy'
649
+ )
650
+ """
651
+ import pm4py
652
+
653
+ dataframe = pm4py.connectors.extract_log_sap_accounting(
654
+ connection_string, prefix=prefix
655
+ )
656
+ return pm4py.convert_log_to_ocel(
657
+ dataframe,
658
+ object_types=["case:concept:name"],
659
+ timestamp_column="time:timestamp",
660
+ additional_object_attributes={"case:concept:name": ["case:concept:name", "org:resource"]},
661
+ )
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/convert.py ADDED
@@ -0,0 +1,713 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ __doc__ = """
23
+ The ``pm4py.convert`` module contains the cross-conversions implemented in ``pm4py``
24
+ """
25
+
26
+ from typing import Union, Tuple, Optional, Collection, List, Any, Dict
27
+
28
+ import pandas as pd
29
+ from copy import deepcopy
30
+
31
+ import pm4py
32
+ from pm4py.objects.bpmn.obj import BPMN
33
+ from pm4py.objects.ocel.obj import OCEL
34
+ from pm4py.objects.powl.obj import POWL
35
+ from pm4py.objects.heuristics_net.obj import HeuristicsNet
36
+ from pm4py.objects.genetic_matrix.obj import GeneticMatrix
37
+ from pm4py.objects.log.obj import EventLog, EventStream
38
+ from pm4py.objects.petri_net.obj import Marking
39
+ from pm4py.objects.process_tree.obj import ProcessTree
40
+ from pm4py.objects.petri_net.obj import PetriNet
41
+ from pm4py.util import constants, nx_utils
42
+ from pm4py.utils import get_properties, __event_log_deprecation_warning
43
+ from pm4py.objects.transition_system.obj import TransitionSystem
44
+ from pm4py.util.pandas_utils import (
45
+ check_is_pandas_dataframe,
46
+ check_pandas_dataframe_columns,
47
+ )
48
+ import networkx as nx
49
+
50
+
51
+ def convert_to_event_log(
52
+ obj: Union[pd.DataFrame, EventStream],
53
+ case_id_key: str = "case:concept:name",
54
+ **kwargs,
55
+ ) -> EventLog:
56
+ """
57
+ Converts a DataFrame or EventStream object to an event log object.
58
+
59
+ :param obj: The DataFrame or EventStream object to convert.
60
+ :param case_id_key: The attribute to be used as the case identifier. Defaults to "case:concept:name".
61
+ :param kwargs: Additional keyword arguments to pass to the converter.
62
+ :return: An ``EventLog`` object.
63
+
64
+ .. code-block:: python3
65
+
66
+ import pandas as pd
67
+ import pm4py
68
+
69
+ dataframe = pm4py.read_csv("tests/input_data/running-example.csv")
70
+ dataframe = pm4py.format_dataframe(dataframe, case_id_column='case:concept:name', activity_column='concept:name', timestamp_column='time:timestamp')
71
+ log = pm4py.convert_to_event_log(dataframe)
72
+ """
73
+
74
+ if check_is_pandas_dataframe(obj):
75
+ check_pandas_dataframe_columns(obj, case_id_key=case_id_key)
76
+
77
+ parameters = get_properties(obj, case_id_key=case_id_key)
78
+ for k, v in kwargs.items():
79
+ parameters[k] = v
80
+
81
+ from pm4py.objects.conversion.log import converter
82
+
83
+ log = converter.apply(
84
+ obj, variant=converter.Variants.TO_EVENT_LOG, parameters=parameters
85
+ )
86
+
87
+ __event_log_deprecation_warning(log)
88
+
89
+ return log
90
+
91
+
92
+ def convert_to_event_stream(
93
+ obj: Union[EventLog, pd.DataFrame],
94
+ case_id_key: str = "case:concept:name",
95
+ **kwargs,
96
+ ) -> EventStream:
97
+ """
98
+ Converts a log object or DataFrame to an event stream.
99
+
100
+ :param obj: The log object (``EventLog``) or DataFrame to convert.
101
+ :param case_id_key: The attribute to be used as the case identifier. Defaults to "case:concept:name".
102
+ :param kwargs: Additional keyword arguments to pass to the converter.
103
+ :return: An ``EventStream`` object.
104
+
105
+ .. code-block:: python3
106
+
107
+ import pm4py
108
+
109
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
110
+ event_stream = pm4py.convert_to_event_stream(log)
111
+ """
112
+ if check_is_pandas_dataframe(obj):
113
+ check_pandas_dataframe_columns(obj, case_id_key=case_id_key)
114
+
115
+ parameters = get_properties(obj, case_id_key=case_id_key)
116
+ for k, v in kwargs.items():
117
+ parameters[k] = v
118
+
119
+ from pm4py.objects.conversion.log import converter
120
+
121
+ stream = converter.apply(
122
+ obj, variant=converter.Variants.TO_EVENT_STREAM, parameters=parameters
123
+ )
124
+
125
+ __event_log_deprecation_warning(stream)
126
+
127
+ return stream
128
+
129
+
130
+ def convert_to_dataframe(
131
+ obj: Union[EventStream, EventLog], **kwargs
132
+ ) -> pd.DataFrame:
133
+ """
134
+ Converts a log object (``EventStream`` or ``EventLog``) to a Pandas DataFrame.
135
+
136
+ :param obj: The log object to convert.
137
+ :param kwargs: Additional keyword arguments to pass to the converter.
138
+ :return: A ``pd.DataFrame`` object.
139
+
140
+ .. code-block:: python3
141
+
142
+ import pm4py
143
+
144
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
145
+ dataframe = pm4py.convert_to_dataframe(log)
146
+ """
147
+ if check_is_pandas_dataframe(obj):
148
+ check_pandas_dataframe_columns(obj)
149
+
150
+ parameters = get_properties(obj)
151
+ for k, v in kwargs.items():
152
+ parameters[k] = v
153
+
154
+ from pm4py.objects.conversion.log import converter
155
+
156
+ df = converter.apply(
157
+ obj, variant=converter.Variants.TO_DATA_FRAME, parameters=parameters
158
+ )
159
+ return df
160
+
161
+
162
+ def convert_to_bpmn(
163
+ *args: Union[Tuple[PetriNet, Marking, Marking], ProcessTree]
164
+ ) -> BPMN:
165
+ """
166
+ Converts an object to a BPMN diagram.
167
+
168
+ As input, either a Petri net (with corresponding initial and final markings) or a process tree can be provided.
169
+ A process tree can always be converted into a BPMN model, ensuring the quality of the resulting object.
170
+ For Petri nets, the quality of the conversion largely depends on the net provided (e.g., sound WF-nets are likely to produce reasonable BPMN models).
171
+
172
+ :param args:
173
+ - If converting a Petri net: a tuple of (``PetriNet``, ``Marking``, ``Marking``).
174
+ - If converting a process tree: a single ``ProcessTree`` object.
175
+ :return: A ``BPMN`` object.
176
+
177
+ .. code-block:: python3
178
+
179
+ import pm4py
180
+
181
+ # Import a Petri net from a file
182
+ net, im, fm = pm4py.read_pnml("tests/input_data/running-example.pnml")
183
+ bpmn_graph = pm4py.convert_to_bpmn(net, im, fm)
184
+ """
185
+ from pm4py.objects.process_tree.obj import ProcessTree
186
+ from pm4py.objects.bpmn.obj import BPMN
187
+
188
+ if isinstance(args[0], BPMN):
189
+ # the object is already a BPMN
190
+ return args[0]
191
+ elif isinstance(args[0], ProcessTree):
192
+ from pm4py.objects.conversion.process_tree.variants import to_bpmn
193
+
194
+ return to_bpmn.apply(args[0])
195
+ else:
196
+ # try to convert the object to a Petri net. Then, use the PM4Py PN-to-BPMN converter
197
+ # to get the BPMN object
198
+ try:
199
+ net, im, fm = convert_to_petri_net(*args)
200
+ from pm4py.objects.conversion.wf_net.variants import to_bpmn
201
+
202
+ return to_bpmn.apply(net, im, fm)
203
+ except BaseException:
204
+ # don't do nothing and throw the following exception
205
+ pass
206
+ # if no conversion is done, then the format of the arguments is unsupported
207
+ raise Exception("Unsupported conversion of the provided object to BPMN")
208
+
209
+
210
+ def convert_to_petri_net(
211
+ *args: Union[BPMN, ProcessTree, HeuristicsNet, GeneticMatrix, POWL, dict]
212
+ ) -> Tuple[PetriNet, Marking, Marking]:
213
+ """
214
+ Converts an input model to an (accepting) Petri net.
215
+
216
+ The input objects can be a process tree, BPMN model, Heuristic net, GeneticMatrix, POWL model, or a dictionary representing a Directly-Follows Graph (DFG).
217
+ The output is a tuple containing the Petri net and the initial and final markings.
218
+ The markings are only returned if they can be reasonably derived from the input model.
219
+
220
+ :param args:
221
+ - If converting from a BPMN, ProcessTree, HeuristicsNet, GeneticMatrix, or POWL: a single object of the respective type.
222
+ - If converting from a DFG: a dictionary representing the DFG, followed by lists of start and end activities.
223
+ :return: A tuple of (``PetriNet``, ``Marking``, ``Marking``).
224
+
225
+ .. code-block:: python3
226
+
227
+ import pm4py
228
+
229
+ # Imports a process tree from a PTML file
230
+ process_tree = pm4py.read_ptml("tests/input_data/running-example.ptml")
231
+ net, im, fm = pm4py.convert_to_petri_net(process_tree)
232
+ """
233
+ if isinstance(args[0], PetriNet):
234
+ # the object is already a Petri net
235
+ return args[0], args[1], args[2]
236
+ elif isinstance(args[0], ProcessTree):
237
+ if isinstance(args[0], POWL):
238
+ from pm4py.objects.conversion.powl import converter
239
+
240
+ return converter.apply(args[0])
241
+ from pm4py.objects.conversion.process_tree.variants import to_petri_net
242
+
243
+ return to_petri_net.apply(args[0])
244
+ elif isinstance(args[0], BPMN):
245
+ from pm4py.objects.conversion.bpmn.variants import to_petri_net
246
+
247
+ return to_petri_net.apply(args[0])
248
+ elif isinstance(args[0], HeuristicsNet):
249
+ from pm4py.objects.conversion.heuristics_net.variants import (
250
+ to_petri_net,
251
+ )
252
+
253
+ return to_petri_net.apply(args[0])
254
+ elif isinstance(args[0], GeneticMatrix):
255
+ from pm4py.objects.conversion.genetic_matrix.variants import (
256
+ to_petri_net,
257
+ )
258
+
259
+ return to_petri_net.apply(args[0])
260
+ elif isinstance(args[0], dict):
261
+ # DFG
262
+ from pm4py.objects.conversion.dfg.variants import (
263
+ to_petri_net_activity_defines_place,
264
+ )
265
+
266
+ return to_petri_net_activity_defines_place.apply(
267
+ args[0],
268
+ parameters={
269
+ to_petri_net_activity_defines_place.Parameters.START_ACTIVITIES: args[1],
270
+ to_petri_net_activity_defines_place.Parameters.END_ACTIVITIES: args[2],
271
+ },
272
+ )
273
+ # if no conversion is done, then the format of the arguments is unsupported
274
+ raise Exception(
275
+ "Unsupported conversion of the provided object to Petri net"
276
+ )
277
+
278
+
279
+ def convert_to_process_tree(
280
+ *args: Union[Tuple[PetriNet, Marking, Marking], BPMN, ProcessTree, POWL]
281
+ ) -> ProcessTree:
282
+ """
283
+ Converts an input model to a process tree.
284
+
285
+ The input models can be Petri nets (with markings) or BPMN models.
286
+ For both input types, the conversion is not guaranteed to work and may raise an exception.
287
+
288
+ :param args:
289
+ - If converting from a Petri net: a tuple of (``PetriNet``, ``Marking``, ``Marking``).
290
+ - If converting from a BPMN or ProcessTree: a single object of the respective type.
291
+ :return: A ``ProcessTree`` object.
292
+
293
+ .. code-block:: python3
294
+
295
+ import pm4py
296
+
297
+ # Imports a BPMN file
298
+ bpmn_graph = pm4py.read_bpmn("tests/input_data/running-example.bpmn")
299
+ # Converts the BPMN to a process tree (through intermediate conversion to a Petri net)
300
+ process_tree = pm4py.convert_to_process_tree(bpmn_graph)
301
+ """
302
+ from pm4py.objects.process_tree.obj import ProcessTree
303
+ from pm4py.objects.petri_net.obj import PetriNet
304
+
305
+ if isinstance(args[0], POWL):
306
+ from pm4py.objects.conversion.powl.variants import to_process_tree
307
+ return to_process_tree.apply(args[0])
308
+ elif isinstance(args[0], ProcessTree):
309
+ # the object is already a process tree
310
+ return args[0]
311
+
312
+ if isinstance(args[0], PetriNet):
313
+ net, im, fm = args[0], args[1], args[2]
314
+ else:
315
+ net, im, fm = convert_to_petri_net(*args)
316
+
317
+ from pm4py.objects.conversion.wf_net.variants import to_process_tree
318
+
319
+ tree = to_process_tree.apply(net, im, fm)
320
+ if tree is not None:
321
+ return tree
322
+
323
+ raise Exception(
324
+ "The object represents a model that cannot be represented as a process tree!"
325
+ )
326
+
327
+
328
+ def convert_to_powl(*args: Union[Tuple[PetriNet, Marking, Marking], BPMN, ProcessTree]) -> POWL:
329
+ """
330
+ Converts an input model to a POWL model.
331
+
332
+ The input models can be Petri nets (with markings) or BPMN models or process trees.
333
+ For both input types, the conversion is not guaranteed to work and may raise an exception.
334
+
335
+ :param args:
336
+ - If converting from a Petri net: a tuple of (``PetriNet``, ``Marking``, ``Marking``).
337
+ - If converting from a BPMN or ProcessTree: a single object of the respective type.
338
+ :return: A ``ProcessTree`` object.
339
+
340
+ .. code-block:: python3
341
+
342
+ import pm4py
343
+
344
+ # Imports a BPMN file
345
+ bpmn_graph = pm4py.read_bpmn("tests/input_data/running-example.bpmn")
346
+ # Converts the BPMN to a POWL (through intermediate conversion to a Petri net)
347
+ powl = pm4py.convert_to_powl(bpmn_graph)
348
+ print(powl)
349
+ """
350
+ from pm4py.objects.process_tree.obj import ProcessTree
351
+ from pm4py.objects.petri_net.obj import PetriNet
352
+
353
+ if isinstance(args[0], ProcessTree):
354
+ from pm4py.objects.conversion.process_tree.variants import to_powl
355
+ return to_powl.apply(args[0])
356
+ elif isinstance(args[0], PetriNet):
357
+ from pm4py.objects.conversion.wf_net.variants import to_powl
358
+ return to_powl.apply(args[0])
359
+ elif isinstance(args[0], BPMN):
360
+ from pm4py.objects.conversion.wf_net.variants import to_powl
361
+ net, im, fm = pm4py.convert_to_petri_net(args[0])
362
+ return to_powl.apply(net)
363
+
364
+ raise Exception(
365
+ "The object represents a model that cannot be directly represented as a POWL!"
366
+ )
367
+
368
+
369
+ def convert_to_reachability_graph(
370
+ *args: Union[Tuple[PetriNet, Marking, Marking], BPMN, ProcessTree]
371
+ ) -> TransitionSystem:
372
+ """
373
+ Converts an input model to a reachability graph (transition system).
374
+
375
+ The input models can be Petri nets (with markings), BPMN models, or process trees.
376
+ The output is the state-space of the model, encoded as a ``TransitionSystem`` object.
377
+
378
+ :param args:
379
+ - If converting from a Petri net: a tuple of (``PetriNet``, ``Marking``, ``Marking``).
380
+ - If converting from a BPMN or ProcessTree: a single object of the respective type.
381
+ :return: A ``TransitionSystem`` object.
382
+
383
+ .. code-block:: python3
384
+
385
+ import pm4py
386
+
387
+ # Reads a Petri net from a file
388
+ net, im, fm = pm4py.read_pnml("tests/input_data/running-example.pnml")
389
+ # Converts it to a reachability graph
390
+ reach_graph = pm4py.convert_to_reachability_graph(net, im, fm)
391
+ """
392
+ if isinstance(args[0], PetriNet):
393
+ net, im, fm = args[0], args[1], args[2]
394
+ else:
395
+ net, im, fm = convert_to_petri_net(*args)
396
+
397
+ from pm4py.objects.petri_net.utils import reachability_graph
398
+
399
+ return reachability_graph.construct_reachability_graph(net, im)
400
+
401
+
402
+ def convert_log_to_ocel(
403
+ log: Union[EventLog, EventStream, pd.DataFrame],
404
+ activity_column: str = "concept:name",
405
+ timestamp_column: str = "time:timestamp",
406
+ object_types: Optional[Collection[str]] = None,
407
+ obj_separator: str = " AND ",
408
+ additional_event_attributes: Optional[Collection[str]] = None,
409
+ additional_object_attributes: Optional[Dict[str, Collection[str]]] = None,
410
+ ) -> OCEL:
411
+ """
412
+ Converts an event log to an object-centric event log (OCEL) with one or more object types.
413
+
414
+ :param log: The log object to convert.
415
+ :param activity_column: The name of the column representing activities.
416
+ :param timestamp_column: The name of the column representing timestamps.
417
+ :param object_types: A collection of column names to consider as object types. If None, defaults are used.
418
+ :param obj_separator: The separator used between different objects in the same column. Defaults to " AND ".
419
+ :param additional_event_attributes: Additional attribute names to include as event attributes in the OCEL.
420
+ :param additional_object_attributes: Additional attributes per object type to include as object attributes in the OCEL. Should be a dictionary mapping object types to lists of attribute names.
421
+ :return: An ``OCEL`` object.
422
+
423
+ .. code-block:: python3
424
+
425
+ import pm4py
426
+
427
+ ocel = pm4py.convert_log_to_ocel(
428
+ log,
429
+ activity_column='concept:name',
430
+ timestamp_column='time:timestamp',
431
+ object_types=['case:concept:name']
432
+ )
433
+ """
434
+ __event_log_deprecation_warning(log)
435
+
436
+ if isinstance(log, EventStream):
437
+ log = convert_to_dataframe(log)
438
+
439
+ if object_types is None:
440
+ object_types = list(
441
+ set(
442
+ x
443
+ for x in log.columns
444
+ if x == "case:concept:name" or x.startswith("ocel:type")
445
+ )
446
+ )
447
+
448
+ from pm4py.objects.ocel.util import log_ocel
449
+
450
+ return log_ocel.log_to_ocel_multiple_obj_types(
451
+ log,
452
+ activity_column,
453
+ timestamp_column,
454
+ object_types,
455
+ obj_separator,
456
+ additional_event_attributes=additional_event_attributes,
457
+ additional_object_attributes=additional_object_attributes,
458
+ )
459
+
460
+
461
+ def convert_ocel_to_networkx(
462
+ ocel: OCEL, variant: str = "ocel_to_nx"
463
+ ) -> nx.DiGraph:
464
+ """
465
+ Converts an OCEL to a NetworkX DiGraph object.
466
+
467
+ :param ocel: The object-centric event log to convert.
468
+ :param variant: The variant of the conversion to use.
469
+ Options:
470
+ - "ocel_to_nx": Graph containing event and object IDs and two types of relations (REL=related objects, DF=directly-follows).
471
+ - "ocel_features_to_nx": Graph containing different types of interconnections at the object level.
472
+ :return: A ``nx.DiGraph`` object representing the OCEL.
473
+
474
+ .. code-block:: python3
475
+
476
+ import pm4py
477
+
478
+ nx_digraph = pm4py.convert_ocel_to_networkx(ocel, variant='ocel_to_nx')
479
+ """
480
+ from pm4py.objects.conversion.ocel import converter
481
+
482
+ variant1 = None
483
+ if variant == "ocel_to_nx":
484
+ variant1 = converter.Variants.OCEL_TO_NX
485
+ elif variant == "ocel_features_to_nx":
486
+ variant1 = converter.Variants.OCEL_FEATURES_TO_NX
487
+ else:
488
+ raise ValueError(
489
+ f"Unsupported variant '{variant}'. Supported variants are 'ocel_to_nx' and 'ocel_features_to_nx'.")
490
+
491
+ return converter.apply(ocel, variant=variant1)
492
+
493
+
494
+ def convert_log_to_networkx(
495
+ log: Union[EventLog, EventStream, pd.DataFrame],
496
+ include_df: bool = True,
497
+ case_id_key: str = "concept:name",
498
+ other_case_attributes_as_nodes: Optional[Collection[str]] = None,
499
+ event_attributes_as_nodes: Optional[Collection[str]] = None,
500
+ ) -> nx.DiGraph:
501
+ """
502
+ Converts an event log to a NetworkX DiGraph object.
503
+
504
+ The nodes of the graph include events, cases, and optionally log attributes.
505
+ The edges represent:
506
+ - BELONGS_TO: Connecting each event to its corresponding case.
507
+ - DF: Connecting events that directly follow each other (if enabled).
508
+ - ATTRIBUTE_EDGE: Connecting cases/events to their attribute values.
509
+
510
+ :param log: The log object to convert (``EventLog``, ``EventStream``, or Pandas DataFrame).
511
+ :param include_df: Whether to include the directly-follows relation in the graph. Defaults to True.
512
+ :param case_id_key: The attribute to be used as the case identifier. Defaults to "concept:name".
513
+ :param other_case_attributes_as_nodes: Attributes at the case level to include as nodes, excluding the case ID.
514
+ :param event_attributes_as_nodes: Attributes at the event level to include as nodes.
515
+ :return: A ``nx.DiGraph`` object representing the event log.
516
+
517
+ .. code-block:: python3
518
+
519
+ import pm4py
520
+
521
+ nx_digraph = pm4py.convert_log_to_networkx(
522
+ log,
523
+ other_case_attributes_as_nodes=['responsible', 'department'],
524
+ event_attributes_as_nodes=['concept:name', 'org:resource']
525
+ )
526
+ """
527
+ from pm4py.objects.conversion.log import converter
528
+
529
+ return converter.apply(
530
+ log,
531
+ variant=converter.Variants.TO_NX,
532
+ parameters={
533
+ "include_df": include_df,
534
+ "case_id_attribute": case_id_key,
535
+ "other_case_attributes_as_nodes": other_case_attributes_as_nodes,
536
+ "event_attributes_as_nodes": event_attributes_as_nodes,
537
+ },
538
+ )
539
+
540
+
541
+ def convert_log_to_time_intervals(
542
+ log: Union[EventLog, pd.DataFrame],
543
+ filter_activity_couple: Optional[Tuple[str, str]] = None,
544
+ activity_key: str = "concept:name",
545
+ timestamp_key: str = "time:timestamp",
546
+ case_id_key: str = "case:concept:name",
547
+ start_timestamp_key: str = "time:timestamp",
548
+ ) -> List[List[Any]]:
549
+ """
550
+ Extracts a list of time intervals from an event log.
551
+
552
+ Each interval contains two temporally consecutive events within the same case and measures the time between them
553
+ (complete timestamp of the first event against the start timestamp of the second event).
554
+
555
+ :param log: The log object to convert.
556
+ :param filter_activity_couple: Optional tuple to filter intervals by a specific pair of activities.
557
+ :param activity_key: The attribute to be used as the activity identifier. Defaults to "concept:name".
558
+ :param timestamp_key: The attribute to be used as the timestamp. Defaults to "time:timestamp".
559
+ :param case_id_key: The attribute to be used as the case identifier. Defaults to "case:concept:name".
560
+ :param start_timestamp_key: The attribute to be used as the start timestamp in the interval. Defaults to "time:timestamp".
561
+ :return: A list of intervals, where each interval is a list containing relevant information about the time gap.
562
+
563
+ .. code-block:: python3
564
+
565
+ import pm4py
566
+
567
+ log = pm4py.read_xes('tests/input_data/receipt.xes')
568
+ time_intervals = pm4py.convert_log_to_time_intervals(log)
569
+ print(len(time_intervals))
570
+ time_intervals = pm4py.convert_log_to_time_intervals(
571
+ log,
572
+ filter_activity_couple=('Confirmation of receipt', 'T02 Check confirmation of receipt')
573
+ )
574
+ print(len(time_intervals))
575
+ """
576
+ __event_log_deprecation_warning(log)
577
+
578
+ properties = get_properties(
579
+ log,
580
+ activity_key=activity_key,
581
+ case_id_key=case_id_key,
582
+ timestamp_key=timestamp_key,
583
+ )
584
+ properties["filter_activity_couple"] = filter_activity_couple
585
+ properties[constants.PARAMETER_CONSTANT_START_TIMESTAMP_KEY] = (
586
+ start_timestamp_key
587
+ )
588
+
589
+ from pm4py.algo.transformation.log_to_interval_tree.variants import (
590
+ open_paths,
591
+ )
592
+
593
+ return open_paths.log_to_intervals(log, parameters=properties)
594
+
595
+
596
+ def convert_petri_net_to_networkx(
597
+ net: PetriNet, im: Marking, fm: Marking
598
+ ) -> nx.DiGraph:
599
+ """
600
+ Converts a Petri net to a NetworkX DiGraph.
601
+
602
+ Each place and transition in the Petri net is represented as a node in the graph.
603
+
604
+ :param net: The Petri net to convert.
605
+ :param im: The initial marking of the Petri net.
606
+ :param fm: The final marking of the Petri net.
607
+ :return: A ``nx.DiGraph`` object representing the Petri net.
608
+
609
+ .. code-block:: python3
610
+
611
+ import pm4py
612
+
613
+ net, im, fm = pm4py.read_pnml('tests/input_data/running-example.pnml')
614
+ nx_digraph = pm4py.convert_petri_net_to_networkx(net, im, fm)
615
+ """
616
+ G = nx_utils.DiGraph()
617
+ for place in net.places:
618
+ G.add_node(
619
+ place.name,
620
+ attr={
621
+ "name": place.name,
622
+ "is_in_im": place in im,
623
+ "is_in_fm": place in fm,
624
+ "type": "place",
625
+ },
626
+ )
627
+ for trans in net.transitions:
628
+ G.add_node(
629
+ trans.name,
630
+ attr={
631
+ "name": trans.name,
632
+ "label": trans.label,
633
+ "type": "transition",
634
+ },
635
+ )
636
+ for arc in net.arcs:
637
+ G.add_edge(
638
+ arc.source.name,
639
+ arc.target.name,
640
+ attr={"weight": arc.weight, "properties": arc.properties},
641
+ )
642
+ return G
643
+
644
+
645
+ def convert_petri_net_type(
646
+ net: PetriNet, im: Marking, fm: Marking, type: str = "classic"
647
+ ) -> Tuple[PetriNet, Marking, Marking]:
648
+ """
649
+ Changes the internal type of a Petri net.
650
+
651
+ Supports conversion to different Petri net types such as classic, reset, inhibitor, and reset_inhibitor nets.
652
+
653
+ :param net: The Petri net to convert.
654
+ :param im: The initial marking of the Petri net.
655
+ :param fm: The final marking of the Petri net.
656
+ :param type: The target Petri net type. Options are "classic", "reset", "inhibitor", "reset_inhibitor". Defaults to "classic".
657
+ :return: A tuple of the converted (``PetriNet``, ``Marking``, ``Marking``).
658
+
659
+ .. code-block:: python3
660
+
661
+ import pm4py
662
+
663
+ net, im, fm = pm4py.read_pnml('tests/input_data/running-example.pnml')
664
+ reset_net, new_im, new_fm = pm4py.convert_petri_net_type(net, im, fm, type='reset_inhibitor')
665
+ """
666
+ from pm4py.objects.petri_net.utils import petri_utils
667
+
668
+ [net, im, fm] = deepcopy([net, im, fm])
669
+ new_net = None
670
+ if type == "classic":
671
+ from pm4py.objects.petri_net.obj import PetriNet
672
+
673
+ new_net = PetriNet(net.name)
674
+ elif type == "reset":
675
+ from pm4py.objects.petri_net.obj import ResetNet
676
+
677
+ new_net = ResetNet(net.name)
678
+ elif type == "inhibitor":
679
+ from pm4py.objects.petri_net.obj import InhibitorNet
680
+
681
+ new_net = InhibitorNet(net.name)
682
+ elif type == "reset_inhibitor":
683
+ from pm4py.objects.petri_net.obj import ResetInhibitorNet
684
+
685
+ new_net = ResetInhibitorNet(net.name)
686
+ else:
687
+ raise ValueError(
688
+ f"Unsupported Petri net type '{type}'. Supported types are 'classic', 'reset', 'inhibitor', 'reset_inhibitor'.")
689
+
690
+ for place in net.places:
691
+ new_net.places.add(place)
692
+ in_arcs = set(place.in_arcs)
693
+ out_arcs = set(place.out_arcs)
694
+ for arc in in_arcs:
695
+ place.in_arcs.remove(arc)
696
+ for arc in out_arcs:
697
+ place.out_arcs.remove(arc)
698
+ for trans in net.transitions:
699
+ new_net.transitions.add(trans)
700
+ in_arcs = set(trans.in_arcs)
701
+ out_arcs = set(trans.out_arcs)
702
+ for arc in in_arcs:
703
+ trans.in_arcs.remove(arc)
704
+ for arc in out_arcs:
705
+ trans.out_arcs.remove(arc)
706
+ for arc in net.arcs:
707
+ arc_type = (
708
+ arc.properties["arctype"] if "arctype" in arc.properties else None
709
+ )
710
+ new_arc = petri_utils.add_arc_from_to(
711
+ arc.source, arc.target, new_net, weight=arc.weight, type=arc_type
712
+ )
713
+ return new_net, im, fm
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/discovery.py ADDED
@@ -0,0 +1,1790 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ __doc__ = """
23
+ The ``pm4py.discovery`` module contains the process discovery algorithms implemented in ``pm4py``.
24
+ """
25
+
26
+ from typing import Tuple, Union, List, Dict, Any, Optional, Set, TextIO
27
+ from collections import Counter
28
+
29
+ import pandas as pd
30
+ from pandas import DataFrame
31
+
32
+ from pm4py.objects.ocel.obj import OCEL
33
+ from pm4py.objects.bpmn.obj import BPMN
34
+ from pm4py.objects.dfg.obj import DFG
35
+ from pm4py.objects.powl.obj import POWL
36
+ from pm4py.objects.heuristics_net.obj import HeuristicsNet
37
+ from pm4py.objects.transition_system.obj import TransitionSystem
38
+ from pm4py.objects.trie.obj import Trie
39
+ from pm4py.objects.log.obj import EventLog
40
+ from pm4py.objects.log.obj import EventStream
41
+ from pm4py.objects.petri_net.obj import PetriNet, Marking
42
+ from pm4py.objects.process_tree.obj import ProcessTree
43
+ from pm4py.util.pandas_utils import (
44
+ check_is_pandas_dataframe,
45
+ check_pandas_dataframe_columns,
46
+ )
47
+ from pm4py.utils import get_properties, __event_log_deprecation_warning, is_polars_lazyframe
48
+ from pm4py.util import constants, pandas_utils
49
+ from pm4py.util import deprecation
50
+ import importlib.util
51
+
52
+
53
+ def discover_dfg(
54
+ log: Union[EventLog, pd.DataFrame],
55
+ activity_key: str = "concept:name",
56
+ timestamp_key: str = "time:timestamp",
57
+ case_id_key: str = "case:concept:name",
58
+ ) -> Tuple[dict, dict, dict]:
59
+ """
60
+ Discovers a Directly-Follows Graph (DFG) from a log.
61
+
62
+ This method returns a tuple containing:
63
+
64
+ - A dictionary with pairs of directly-following activities as keys and the frequency of the relationship as values.
65
+ - A dictionary of start activities with their respective frequencies.
66
+ - A dictionary of end activities with their respective frequencies.
67
+
68
+ :param log: Event log or Pandas DataFrame.
69
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
70
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
71
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
72
+ :return: A tuple of three dictionaries: (dfg, start_activities, end_activities).
73
+ :rtype: ``Tuple[dict, dict, dict]``
74
+
75
+ .. code-block:: python3
76
+
77
+ import pm4py
78
+
79
+ dfg, start_activities, end_activities = pm4py.discover_dfg(
80
+ dataframe,
81
+ case_id_key='case:concept:name',
82
+ activity_key='concept:name',
83
+ timestamp_key='time:timestamp'
84
+ )
85
+ """
86
+ __event_log_deprecation_warning(log)
87
+
88
+ properties = get_properties(
89
+ log,
90
+ activity_key=activity_key,
91
+ timestamp_key=timestamp_key,
92
+ case_id_key=case_id_key,
93
+ )
94
+ if check_is_pandas_dataframe(log):
95
+ check_pandas_dataframe_columns(
96
+ log,
97
+ activity_key=activity_key,
98
+ timestamp_key=timestamp_key,
99
+ case_id_key=case_id_key,
100
+ )
101
+ from pm4py.util import constants
102
+
103
+ if is_polars_lazyframe(log):
104
+ from pm4py.algo.discovery.dfg.adapters.polars.df_statistics import get_dfg_graph
105
+ from pm4py.statistics.start_activities.polars import get as start_activities_module
106
+ from pm4py.statistics.end_activities.polars import get as end_activities_module
107
+ else:
108
+ from pm4py.algo.discovery.dfg.adapters.pandas.df_statistics import (
109
+ get_dfg_graph,
110
+ )
111
+ from pm4py.statistics.start_activities.pandas import (
112
+ get as start_activities_module,
113
+ )
114
+ from pm4py.statistics.end_activities.pandas import (
115
+ get as end_activities_module,
116
+ )
117
+
118
+ dfg = get_dfg_graph(
119
+ log,
120
+ activity_key=activity_key,
121
+ timestamp_key=timestamp_key,
122
+ case_id_glue=case_id_key,
123
+ )
124
+
125
+ start_activities = start_activities_module.get_start_activities(
126
+ log, parameters=properties
127
+ )
128
+ end_activities = end_activities_module.get_end_activities(
129
+ log, parameters=properties
130
+ )
131
+ else:
132
+ from pm4py.algo.discovery.dfg import algorithm as dfg_discovery
133
+
134
+ dfg = dfg_discovery.apply(log, parameters=properties)
135
+ from pm4py.statistics.start_activities.log import (
136
+ get as start_activities_module,
137
+ )
138
+ from pm4py.statistics.end_activities.log import (
139
+ get as end_activities_module,
140
+ )
141
+
142
+ start_activities = start_activities_module.get_start_activities(
143
+ log, parameters=properties
144
+ )
145
+ end_activities = end_activities_module.get_end_activities(
146
+ log, parameters=properties
147
+ )
148
+ return dfg, start_activities, end_activities
149
+
150
+
151
+ def discover_directly_follows_graph(
152
+ log: Union[EventLog, pd.DataFrame],
153
+ activity_key: str = "concept:name",
154
+ timestamp_key: str = "time:timestamp",
155
+ case_id_key: str = "case:concept:name",
156
+ ) -> Tuple[dict, dict, dict]:
157
+ return discover_dfg(
158
+ log,
159
+ activity_key=activity_key,
160
+ timestamp_key=timestamp_key,
161
+ case_id_key=case_id_key,
162
+ )
163
+
164
+
165
+ def discover_dfg_typed(
166
+ log: pd.DataFrame,
167
+ case_id_key: str = "case:concept:name",
168
+ activity_key: str = "concept:name",
169
+ timestamp_key: str = "time:timestamp",
170
+ ) -> DFG:
171
+ """
172
+ Discovers a typed Directly-Follows Graph (DFG) from a log.
173
+
174
+ This method returns a typed DFG object, as specified in ``pm4py.objects.dfg.obj.py`` (``DirectlyFollowsGraph`` Class).
175
+ The DFG object includes the graph, start activities, and end activities.
176
+ - The graph is a collection of triples of the form (a, b, f) representing an arc a->b with frequency f.
177
+ - The start activities are a collection of tuples of the form (a, f) representing that activity a starts f cases.
178
+ - The end activities are a collection of tuples of the form (a, f) representing that activity a ends f cases.
179
+
180
+ This method replaces ``pm4py.discover_dfg`` and ``pm4py.discover_directly_follows_graph``. In future releases, these functions will adopt the same behavior as this function.
181
+
182
+ :param log: ``pandas.DataFrame``
183
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
184
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
185
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
186
+ :return: A typed DFG object containing the graph, start activities, and end activities.
187
+ :rtype: ``DFG``
188
+
189
+ .. code-block:: python3
190
+
191
+ import pm4py
192
+
193
+ dfg = pm4py.discover_dfg_typed(
194
+ log,
195
+ case_id_key='case:concept:name',
196
+ activity_key='concept:name',
197
+ timestamp_key='time:timestamp'
198
+ )
199
+ """
200
+ from pm4py.objects.dfg.obj import DFG
201
+
202
+ dfg, sa, ea = discover_dfg(log, activity_key=activity_key, case_id_key=case_id_key, timestamp_key=timestamp_key)
203
+ return DFG(dfg, sa, ea)
204
+
205
+
206
+ def discover_performance_dfg(
207
+ log: Union[EventLog, pd.DataFrame],
208
+ business_hours: bool = False,
209
+ business_hour_slots=constants.DEFAULT_BUSINESS_HOUR_SLOTS,
210
+ workcalendar=constants.DEFAULT_BUSINESS_HOURS_WORKCALENDAR,
211
+ activity_key: str = "concept:name",
212
+ timestamp_key: str = "time:timestamp",
213
+ case_id_key: str = "case:concept:name",
214
+ perf_aggregation_key: str = "all",
215
+ ) -> Tuple[dict, dict, dict]:
216
+ """
217
+ Discovers a Performance Directly-Follows Graph from an event log.
218
+
219
+ This method returns a tuple containing:
220
+
221
+ - A dictionary with pairs of directly-following activities as keys and the performance metrics of the relationship as values.
222
+ - A dictionary of start activities with their respective frequencies.
223
+ - A dictionary of end activities with their respective frequencies.
224
+
225
+ :param log: Event log or Pandas DataFrame.
226
+ :param business_hours: Enables or disables computation based on business hours (default: False).
227
+ :param business_hour_slots: Work schedule of the company, provided as a list of tuples where each tuple represents one time slot of business hours. Each slot consists of a start and end time given in seconds since the week start.
228
+ :param workcalendar: Calendar exposing ``is_working_day(day)``. Dates
229
+ rejected by the calendar are excluded when business hours are enabled.
230
+
231
+ Example::
232
+
233
+ [
234
+ (7 * 60 * 60, 17 * 60 * 60), # Monday 07:00 - 17:00
235
+ ((24 + 7) * 60 * 60, (24 + 12) * 60 * 60), # Tuesday 07:00 - 12:00
236
+ ((24 + 13) * 60 * 60, (24 + 17) * 60 * 60) # Tuesday 13:00 - 17:00
237
+ ]
238
+
239
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
240
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
241
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
242
+ :param perf_aggregation_key: Selector for the type of aggregation (all, mean, median, max, min, sum, stdev)
243
+ When business hours are enabled, the returned performance DFG remains
244
+ dictionary-compatible and also retains the configured schedule so that
245
+ visualizations can express its durations in working days.
246
+
247
+ :return: A tuple of three dictionaries: (performance_dfg, start_activities, end_activities).
248
+ :rtype: ``Tuple[dict, dict, dict]``
249
+
250
+ .. code-block:: python3
251
+
252
+ import pm4py
253
+
254
+ performance_dfg, start_activities, end_activities = pm4py.discover_performance_dfg(
255
+ dataframe,
256
+ case_id_key='case:concept:name',
257
+ activity_key='concept:name',
258
+ timestamp_key='time:timestamp'
259
+ )
260
+ """
261
+ __event_log_deprecation_warning(log)
262
+
263
+ properties = get_properties(
264
+ log,
265
+ activity_key=activity_key,
266
+ timestamp_key=timestamp_key,
267
+ case_id_key=case_id_key,
268
+ )
269
+
270
+ if check_is_pandas_dataframe(log):
271
+ check_pandas_dataframe_columns(
272
+ log,
273
+ activity_key=activity_key,
274
+ timestamp_key=timestamp_key,
275
+ case_id_key=case_id_key,
276
+ )
277
+ from pm4py.util import constants
278
+
279
+ if is_polars_lazyframe(log):
280
+ from pm4py.algo.discovery.dfg.adapters.polars.df_statistics import get_dfg_graph
281
+ from pm4py.statistics.start_activities.polars import get as start_activities_module
282
+ from pm4py.statistics.end_activities.polars import get as end_activities_module
283
+ else:
284
+ from pm4py.algo.discovery.dfg.adapters.pandas.df_statistics import (
285
+ get_dfg_graph,
286
+ )
287
+ from pm4py.statistics.start_activities.pandas import (
288
+ get as start_activities_module,
289
+ )
290
+ from pm4py.statistics.end_activities.pandas import (
291
+ get as end_activities_module,
292
+ )
293
+
294
+ dfg = get_dfg_graph(
295
+ log,
296
+ activity_key=activity_key,
297
+ timestamp_key=timestamp_key,
298
+ case_id_glue=case_id_key,
299
+ measure="performance",
300
+ perf_aggregation_key=perf_aggregation_key,
301
+ business_hours=business_hours,
302
+ business_hours_slot=business_hour_slots,
303
+ workcalendar=workcalendar,
304
+ )
305
+
306
+ start_activities = start_activities_module.get_start_activities(
307
+ log, parameters=properties
308
+ )
309
+ end_activities = end_activities_module.get_end_activities(
310
+ log, parameters=properties
311
+ )
312
+ else:
313
+ from pm4py.algo.discovery.dfg.variants import (
314
+ performance as dfg_discovery,
315
+ )
316
+
317
+ properties[dfg_discovery.Parameters.AGGREGATION_MEASURE] = (
318
+ perf_aggregation_key
319
+ )
320
+ properties[dfg_discovery.Parameters.BUSINESS_HOURS] = business_hours
321
+ properties[dfg_discovery.Parameters.BUSINESS_HOUR_SLOTS] = (
322
+ business_hour_slots
323
+ )
324
+ properties[dfg_discovery.Parameters.WORKCALENDAR] = workcalendar
325
+ dfg = dfg_discovery.apply(log, parameters=properties)
326
+ from pm4py.statistics.start_activities.log import (
327
+ get as start_activities_module,
328
+ )
329
+ from pm4py.statistics.end_activities.log import (
330
+ get as end_activities_module,
331
+ )
332
+
333
+ start_activities = start_activities_module.get_start_activities(
334
+ log, parameters=properties
335
+ )
336
+ end_activities = end_activities_module.get_end_activities(
337
+ log, parameters=properties
338
+ )
339
+ if business_hours:
340
+ from pm4py.objects.dfg.obj import PerformanceDFG
341
+
342
+ dfg = PerformanceDFG(
343
+ dfg, business_hour_slots=business_hour_slots
344
+ )
345
+
346
+ return dfg, start_activities, end_activities
347
+
348
+
349
+ def discover_petri_net_alpha(
350
+ log: Union[EventLog, pd.DataFrame],
351
+ activity_key: str = "concept:name",
352
+ timestamp_key: str = "time:timestamp",
353
+ case_id_key: str = "case:concept:name",
354
+ ) -> Tuple[PetriNet, Marking, Marking]:
355
+ """
356
+ Discovers a Petri net using the Alpha Miner.
357
+
358
+ :param log: Event log or Pandas DataFrame.
359
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
360
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
361
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
362
+ :return: A tuple containing the Petri net, initial marking, and final marking.
363
+ :rtype: ``Tuple[PetriNet, Marking, Marking]``
364
+
365
+ .. code-block:: python3
366
+
367
+ import pm4py
368
+
369
+ net, im, fm = pm4py.discover_petri_net_alpha(
370
+ dataframe,
371
+ activity_key='concept:name',
372
+ case_id_key='case:concept:name',
373
+ timestamp_key='time:timestamp'
374
+ )
375
+ """
376
+ __event_log_deprecation_warning(log)
377
+
378
+ if check_is_pandas_dataframe(log):
379
+ check_pandas_dataframe_columns(
380
+ log,
381
+ activity_key=activity_key,
382
+ timestamp_key=timestamp_key,
383
+ case_id_key=case_id_key,
384
+ )
385
+
386
+ from pm4py.algo.discovery.alpha import algorithm as alpha_miner
387
+
388
+ return alpha_miner.apply(
389
+ log,
390
+ variant=alpha_miner.Variants.ALPHA_VERSION_CLASSIC,
391
+ parameters=get_properties(
392
+ log,
393
+ activity_key=activity_key,
394
+ timestamp_key=timestamp_key,
395
+ case_id_key=case_id_key,
396
+ ),
397
+ )
398
+
399
+
400
+ def discover_petri_net_ilp(
401
+ log: Union[EventLog, pd.DataFrame],
402
+ alpha: float = 1.0,
403
+ activity_key: str = "concept:name",
404
+ timestamp_key: str = "time:timestamp",
405
+ case_id_key: str = "case:concept:name",
406
+ ) -> Tuple[PetriNet, Marking, Marking]:
407
+ """
408
+ Discovers a Petri net using the ILP Miner.
409
+
410
+ :param log: Event log or Pandas DataFrame.
411
+ :param alpha: Noise threshold for the sequence encoding graph (1.0=no filtering, 0.0=maximum filtering) (default: 1.0).
412
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
413
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
414
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
415
+ :return: A tuple containing the Petri net, initial marking, and final marking.
416
+ :rtype: ``Tuple[PetriNet, Marking, Marking]``
417
+
418
+ .. code-block:: python3
419
+
420
+ import pm4py
421
+
422
+ net, im, fm = pm4py.discover_petri_net_ilp(
423
+ dataframe,
424
+ activity_key='concept:name',
425
+ case_id_key='case:concept:name',
426
+ timestamp_key='time:timestamp'
427
+ )
428
+ """
429
+ __event_log_deprecation_warning(log)
430
+
431
+ if check_is_pandas_dataframe(log):
432
+ check_pandas_dataframe_columns(
433
+ log,
434
+ activity_key=activity_key,
435
+ timestamp_key=timestamp_key,
436
+ case_id_key=case_id_key,
437
+ )
438
+
439
+ parameters = get_properties(
440
+ log,
441
+ activity_key=activity_key,
442
+ timestamp_key=timestamp_key,
443
+ case_id_key=case_id_key,
444
+ )
445
+ parameters["alpha"] = alpha
446
+
447
+ from pm4py.algo.discovery.ilp import algorithm as ilp_miner
448
+
449
+ return ilp_miner.apply(
450
+ log, variant=ilp_miner.Variants.CLASSIC, parameters=parameters
451
+ )
452
+
453
+
454
+ def discover_petri_net_genetic(
455
+ log: Union[EventLog, pd.DataFrame],
456
+ population_size: int = 500,
457
+ elitism_rate: float = 0.01,
458
+ crossover_rate: float = 1.0,
459
+ mutation_rate: float = 0.01,
460
+ generations: int = 100,
461
+ elitism_min_sample: int = 5,
462
+ log_csv: TextIO = None,
463
+ activity_key: str = "concept:name",
464
+ timestamp_key: str = "time:timestamp",
465
+ case_id_key: str = "case:concept:name",
466
+ ) -> Tuple[PetriNet, Marking, Marking]:
467
+ """
468
+ Discovers a Petri net using the Genetic Miner.
469
+
470
+ Reference paper:
471
+ Maximilian Josef Frank. "Optimising and Implementing the Genetic Miner in PM4Py" (2026).
472
+
473
+ :param log: Event log or Pandas DataFrame.
474
+ :param population_size: Population size of genetic sampling (default: 500).
475
+ :param elitism_rate: Rate of best models used in next generation (default: 0.01).
476
+ :param crossover_rate: Rate of genetically combined models (offsprings) used in next generation (default: 1.0).
477
+ :param mutation_rate: Random model mutation rate (default: 0.01).
478
+ :param generations: Iterations of model improvement (default: 100).
479
+ :param elitism_min_sample: Minimum sample size for selecting best models (default: 5).
480
+ :param log_csv: Output stream for CSV log (default: None).
481
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
482
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
483
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
484
+ :return: A tuple containing the Petri net, initial marking, and final marking.
485
+ :rtype: ``Tuple[PetriNet, Marking, Marking]``
486
+
487
+ .. code-block:: python3
488
+
489
+ import pm4py
490
+
491
+ net, im, fm = pm4py.discover_petri_net_genetic(
492
+ dataframe,
493
+ activity_key='concept:name',
494
+ timestamp_key='time:timestamp',
495
+ case_id_key='case:concept:name'
496
+ )
497
+ """
498
+ __event_log_deprecation_warning(log)
499
+
500
+ from pm4py.algo.discovery.genetic import algorithm as genetic_miner
501
+
502
+ genetic_parameters = genetic_miner.Parameters
503
+ parameters = get_properties(
504
+ log,
505
+ activity_key=activity_key,
506
+ timestamp_key=timestamp_key,
507
+ case_id_key=case_id_key,
508
+ )
509
+ parameters[genetic_parameters.POPULATION_SIZE] = population_size
510
+ parameters[genetic_parameters.ELITISM_RATE] = elitism_rate
511
+ parameters[genetic_parameters.CROSSOVER_RATE] = crossover_rate
512
+ parameters[genetic_parameters.MUTATION_RATE] = mutation_rate
513
+ parameters[genetic_parameters.GENERATIONS] = generations
514
+ parameters[genetic_parameters.ELITISM_MIN_SAMPLE] = elitism_min_sample
515
+ parameters[genetic_parameters.LOG_CSV] = log_csv
516
+
517
+ if check_is_pandas_dataframe(log):
518
+ check_pandas_dataframe_columns(
519
+ log,
520
+ activity_key=activity_key,
521
+ timestamp_key=timestamp_key,
522
+ case_id_key=case_id_key,
523
+ )
524
+
525
+ return genetic_miner.apply(
526
+ log,
527
+ variant=genetic_miner.Variants.CLASSIC,
528
+ parameters=parameters,
529
+ )
530
+
531
+
532
+ @deprecation.deprecated(
533
+ deprecated_in="2.3.0",
534
+ removed_in="3.0.0",
535
+ details="This method will be removed in a future release.",
536
+ )
537
+ def discover_petri_net_alpha_plus(
538
+ log: Union[EventLog, pd.DataFrame],
539
+ activity_key: str = "concept:name",
540
+ timestamp_key: str = "time:timestamp",
541
+ case_id_key: str = "case:concept:name",
542
+ ) -> Tuple[PetriNet, Marking, Marking]:
543
+ """
544
+ Discovers a Petri net using the Alpha+ algorithm.
545
+
546
+ .. deprecated:: 2.3.0
547
+ This method will be removed in version 3.0.0. Use other discovery methods instead.
548
+
549
+ :param log: Event log or Pandas DataFrame.
550
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
551
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
552
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
553
+ :return: A tuple containing the Petri net, initial marking, and final marking.
554
+ :rtype: ``Tuple[PetriNet, Marking, Marking]``
555
+
556
+ .. code-block:: python3
557
+
558
+ import pm4py
559
+
560
+ net, im, fm = pm4py.discover_petri_net_alpha_plus(
561
+ dataframe,
562
+ activity_key='concept:name',
563
+ case_id_key='case:concept:name',
564
+ timestamp_key='time:timestamp'
565
+ )
566
+ """
567
+ __event_log_deprecation_warning(log)
568
+
569
+ if check_is_pandas_dataframe(log):
570
+ check_pandas_dataframe_columns(
571
+ log,
572
+ activity_key=activity_key,
573
+ timestamp_key=timestamp_key,
574
+ case_id_key=case_id_key,
575
+ )
576
+
577
+ from pm4py.algo.discovery.alpha import algorithm as alpha_miner
578
+
579
+ return alpha_miner.apply(
580
+ log,
581
+ variant=alpha_miner.Variants.ALPHA_VERSION_PLUS,
582
+ parameters=get_properties(
583
+ log,
584
+ activity_key=activity_key,
585
+ timestamp_key=timestamp_key,
586
+ case_id_key=case_id_key,
587
+ ),
588
+ )
589
+
590
+
591
+ def discover_petri_net_inductive(
592
+ log: Union[EventLog, pd.DataFrame, DFG],
593
+ multi_processing: bool = constants.ENABLE_MULTIPROCESSING_DEFAULT,
594
+ noise_threshold: float = 0.0,
595
+ activity_key: str = "concept:name",
596
+ timestamp_key: str = "time:timestamp",
597
+ case_id_key: str = "case:concept:name",
598
+ disable_fallthroughs: bool = False,
599
+ ) -> Tuple[PetriNet, Marking, Marking]:
600
+ """
601
+ Discovers a Petri net using the Inductive Miner algorithm.
602
+
603
+ The Inductive Miner detects a 'cut' in the log (e.g., sequential, parallel, concurrent, loop) and recursively applies the algorithm to sublogs until a base case is found.
604
+ Inductive miner models typically use hidden transitions for skipping or looping portions of the model, and each visible transition has a unique label.
605
+
606
+ :param log: Event log, Pandas DataFrame, or typed DFG.
607
+ :param multi_processing: Enables or disables multiprocessing in the Inductive Miner (default: constants.ENABLE_MULTIPROCESSING_DEFAULT).
608
+ :param noise_threshold: Noise threshold (default: 0.0).
609
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
610
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
611
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
612
+ :param disable_fallthroughs: Disables the Inductive Miner fall-throughs (default: False).
613
+ :return: A tuple containing the Petri net, initial marking, and final marking.
614
+ :rtype: ``Tuple[PetriNet, Marking, Marking]``
615
+
616
+ .. code-block:: python3
617
+
618
+ import pm4py
619
+
620
+ net, im, fm = pm4py.discover_petri_net_inductive(
621
+ dataframe,
622
+ activity_key='concept:name',
623
+ case_id_key='case:concept:name',
624
+ timestamp_key='time:timestamp'
625
+ )
626
+ """
627
+ __event_log_deprecation_warning(log)
628
+
629
+ if check_is_pandas_dataframe(log):
630
+ check_pandas_dataframe_columns(
631
+ log,
632
+ activity_key=activity_key,
633
+ timestamp_key=timestamp_key,
634
+ case_id_key=case_id_key,
635
+ )
636
+
637
+ pt = discover_process_tree_inductive(
638
+ log,
639
+ noise_threshold,
640
+ multi_processing=multi_processing,
641
+ activity_key=activity_key,
642
+ timestamp_key=timestamp_key,
643
+ case_id_key=case_id_key,
644
+ disable_fallthroughs=disable_fallthroughs,
645
+ )
646
+ from pm4py.convert import convert_to_petri_net
647
+
648
+ return convert_to_petri_net(pt)
649
+
650
+
651
+ def discover_petri_net_heuristics(
652
+ log: Union[EventLog, pd.DataFrame],
653
+ dependency_threshold: float = 0.5,
654
+ and_threshold: float = 0.65,
655
+ loop_two_threshold: float = 0.5,
656
+ activity_key: str = "concept:name",
657
+ timestamp_key: str = "time:timestamp",
658
+ case_id_key: str = "case:concept:name",
659
+ ) -> Tuple[PetriNet, Marking, Marking]:
660
+ """
661
+ Discovers a Petri net using the Heuristics Miner.
662
+
663
+ Heuristics Miner operates on the Directly-Follows Graph, handling noise and identifying common constructs such as dependencies between activities and parallelism.
664
+ The output is a Heuristics Net, which can then be converted into a Petri net.
665
+
666
+ :param log: Event log or Pandas DataFrame.
667
+ :param dependency_threshold: Dependency threshold (default: 0.5).
668
+ :param and_threshold: AND threshold for parallelism (default: 0.65).
669
+ :param loop_two_threshold: Loop two threshold (default: 0.5).
670
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
671
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
672
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
673
+ :return: A tuple containing the Petri net, initial marking, and final marking.
674
+ :rtype: ``Tuple[PetriNet, Marking, Marking]``
675
+
676
+ .. code-block:: python3
677
+
678
+ import pm4py
679
+
680
+ net, im, fm = pm4py.discover_petri_net_heuristics(
681
+ dataframe,
682
+ activity_key='concept:name',
683
+ case_id_key='case:concept:name',
684
+ timestamp_key='time:timestamp'
685
+ )
686
+ """
687
+ __event_log_deprecation_warning(log)
688
+
689
+ from pm4py.algo.discovery.heuristics.variants import (
690
+ classic as heuristics_miner,
691
+ )
692
+
693
+ heu_parameters = heuristics_miner.Parameters
694
+ parameters = get_properties(
695
+ log,
696
+ activity_key=activity_key,
697
+ timestamp_key=timestamp_key,
698
+ case_id_key=case_id_key,
699
+ )
700
+ parameters[heu_parameters.DEPENDENCY_THRESH] = dependency_threshold
701
+ parameters[heu_parameters.AND_MEASURE_THRESH] = and_threshold
702
+ parameters[heu_parameters.LOOP_LENGTH_TWO_THRESH] = loop_two_threshold
703
+
704
+ if check_is_pandas_dataframe(log):
705
+ check_pandas_dataframe_columns(
706
+ log,
707
+ activity_key=activity_key,
708
+ timestamp_key=timestamp_key,
709
+ case_id_key=case_id_key,
710
+ )
711
+ return heuristics_miner.apply_pandas(log, parameters=parameters)
712
+ else:
713
+ return heuristics_miner.apply(log, parameters=parameters)
714
+
715
+
716
+ def discover_process_tree_inductive(
717
+ log: Union[EventLog, pd.DataFrame, DFG],
718
+ noise_threshold: float = 0.0,
719
+ multi_processing: bool = constants.ENABLE_MULTIPROCESSING_DEFAULT,
720
+ activity_key: str = "concept:name",
721
+ timestamp_key: str = "time:timestamp",
722
+ case_id_key: str = "case:concept:name",
723
+ disable_fallthroughs: bool = False,
724
+ ) -> ProcessTree:
725
+ """
726
+ Discovers a Process Tree using the Inductive Miner algorithm.
727
+
728
+ The Inductive Miner detects a 'cut' in the log (e.g., sequential, parallel, concurrent, loop) and recursively applies the algorithm to sublogs until a base case is found.
729
+ Inductive miner models typically use hidden transitions for skipping or looping portions of the model, and each visible transition has a unique label.
730
+
731
+ :param log: Event log, Pandas DataFrame, or typed DFG.
732
+ :param noise_threshold: Noise threshold (default: 0.0).
733
+ :param multi_processing: Enables or disables multiprocessing in the Inductive Miner (default: constants.ENABLE_MULTIPROCESSING_DEFAULT).
734
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
735
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
736
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
737
+ :param disable_fallthroughs: Disables the Inductive Miner fall-throughs (default: False).
738
+ :return: A ProcessTree object.
739
+ :rtype: ``ProcessTree``
740
+
741
+ .. code-block:: python3
742
+
743
+ import pm4py
744
+
745
+ process_tree = pm4py.discover_process_tree_inductive(
746
+ dataframe,
747
+ activity_key='concept:name',
748
+ case_id_key='case:concept:name',
749
+ timestamp_key='time:timestamp'
750
+ )
751
+ """
752
+ __event_log_deprecation_warning(log)
753
+
754
+ if check_is_pandas_dataframe(log):
755
+ check_pandas_dataframe_columns(
756
+ log,
757
+ activity_key=activity_key,
758
+ timestamp_key=timestamp_key,
759
+ case_id_key=case_id_key,
760
+ )
761
+
762
+ from pm4py.algo.discovery.inductive import algorithm as inductive_miner
763
+
764
+ parameters = get_properties(
765
+ log,
766
+ activity_key=activity_key,
767
+ timestamp_key=timestamp_key,
768
+ case_id_key=case_id_key,
769
+ )
770
+ parameters["noise_threshold"] = noise_threshold
771
+ parameters["multiprocessing"] = multi_processing
772
+ parameters["disable_fallthroughs"] = disable_fallthroughs
773
+
774
+ variant = (
775
+ inductive_miner.Variants.IMf
776
+ if noise_threshold > 0
777
+ else inductive_miner.Variants.IM
778
+ )
779
+
780
+ if isinstance(log, DFG):
781
+ variant = inductive_miner.Variants.IMd
782
+
783
+ return inductive_miner.apply(log, variant=variant, parameters=parameters)
784
+
785
+
786
+ def discover_heuristics_net(
787
+ log: Union[EventLog, pd.DataFrame],
788
+ dependency_threshold: float = 0.5,
789
+ and_threshold: float = 0.65,
790
+ loop_two_threshold: float = 0.5,
791
+ min_act_count: int = 1,
792
+ min_dfg_occurrences: int = 1,
793
+ activity_key: str = "concept:name",
794
+ timestamp_key: str = "time:timestamp",
795
+ case_id_key: str = "case:concept:name",
796
+ decoration: str = "frequency",
797
+ ) -> HeuristicsNet:
798
+ """
799
+ Discovers a Heuristics Net.
800
+
801
+ Heuristics Miner operates on the Directly-Follows Graph, handling noise and identifying common constructs such as dependencies between activities and parallelism.
802
+ The output is a Heuristics Net, which can then be converted into a Petri net.
803
+
804
+ :param log: Event log or Pandas DataFrame.
805
+ :param dependency_threshold: Dependency threshold (default: 0.5).
806
+ :param and_threshold: AND threshold for parallelism (default: 0.65).
807
+ :param loop_two_threshold: Loop two threshold (default: 0.5).
808
+ :param min_act_count: Minimum number of occurrences per activity to be included in the discovery (default: 1).
809
+ :param min_dfg_occurrences: Minimum number of occurrences per arc in the DFG to be included in the discovery (default: 1).
810
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
811
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
812
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
813
+ :param decoration: The decoration to be used ("frequency" or "performance") (default: "frequency").
814
+ :return: A HeuristicsNet object.
815
+ :rtype: ``HeuristicsNet``
816
+
817
+ .. code-block:: python3
818
+
819
+ import pm4py
820
+
821
+ heu_net = pm4py.discover_heuristics_net(
822
+ dataframe,
823
+ activity_key='concept:name',
824
+ case_id_key='case:concept:name',
825
+ timestamp_key='time:timestamp'
826
+ )
827
+ """
828
+ __event_log_deprecation_warning(log)
829
+
830
+ from pm4py.algo.discovery.heuristics.variants import (
831
+ classic as heuristics_miner,
832
+ )
833
+
834
+ heu_parameters = heuristics_miner.Parameters
835
+ parameters = get_properties(
836
+ log,
837
+ activity_key=activity_key,
838
+ timestamp_key=timestamp_key,
839
+ case_id_key=case_id_key,
840
+ )
841
+ parameters[heu_parameters.DEPENDENCY_THRESH] = dependency_threshold
842
+ parameters[heu_parameters.AND_MEASURE_THRESH] = and_threshold
843
+ parameters[heu_parameters.LOOP_LENGTH_TWO_THRESH] = loop_two_threshold
844
+ parameters[heu_parameters.MIN_ACT_COUNT] = min_act_count
845
+ parameters[heu_parameters.MIN_DFG_OCCURRENCES] = min_dfg_occurrences
846
+ parameters[heu_parameters.HEU_NET_DECORATION] = decoration
847
+
848
+ if check_is_pandas_dataframe(log):
849
+ check_pandas_dataframe_columns(
850
+ log,
851
+ activity_key=activity_key,
852
+ timestamp_key=timestamp_key,
853
+ case_id_key=case_id_key,
854
+ )
855
+ return heuristics_miner.apply_heu_pandas(log, parameters=parameters)
856
+ else:
857
+ return heuristics_miner.apply_heu(log, parameters=parameters)
858
+
859
+
860
+ def derive_minimum_self_distance(
861
+ log: Union[DataFrame, EventLog, EventStream],
862
+ activity_key: str = "concept:name",
863
+ timestamp_key: str = "time:timestamp",
864
+ case_id_key: str = "case:concept:name",
865
+ ) -> Dict[str, int]:
866
+ """
867
+ Computes the minimum self-distance for each activity observed in an event log.
868
+
869
+ The self-distance of activity `a` in `<a>` is infinity,
870
+ in `<a, a>` is 0,
871
+ in `<a, b, a>` is 1,
872
+ etc. The activity key 'concept:name' is used.
873
+
874
+ :param log: Event log or Pandas DataFrame.
875
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
876
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
877
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
878
+ :return: A dictionary mapping each activity to its minimum self-distance.
879
+ :rtype: ``Dict[str, int]``
880
+
881
+ .. code-block:: python3
882
+
883
+ import pm4py
884
+
885
+ msd = pm4py.derive_minimum_self_distance(
886
+ dataframe,
887
+ activity_key='concept:name',
888
+ case_id_key='case:concept:name',
889
+ timestamp_key='time:timestamp'
890
+ )
891
+ """
892
+ __event_log_deprecation_warning(log)
893
+
894
+ if check_is_pandas_dataframe(log):
895
+ check_pandas_dataframe_columns(
896
+ log,
897
+ activity_key=activity_key,
898
+ timestamp_key=timestamp_key,
899
+ case_id_key=case_id_key,
900
+ )
901
+
902
+ from pm4py.algo.discovery.minimum_self_distance import algorithm as msd
903
+
904
+ return msd.apply(
905
+ log,
906
+ parameters=get_properties(
907
+ log,
908
+ activity_key=activity_key,
909
+ timestamp_key=timestamp_key,
910
+ case_id_key=case_id_key,
911
+ ),
912
+ )
913
+
914
+
915
+ def discover_footprints(
916
+ *args: Union[EventLog, Tuple[PetriNet, Marking, Marking], ProcessTree, POWL]
917
+ ) -> Union[List[Dict[str, Any]], Dict[str, Any]]:
918
+ """
919
+ Discovers the footprints from the provided event log or process model.
920
+
921
+ Footprints are a high-level representation of the behavior captured in the event log or process model.
922
+
923
+ :param args: Event log, process model (Petri net and markings), or ProcessTree, or POWL.
924
+ :return: A list of footprint dictionaries or a single footprint dictionary.
925
+ :rtype: ``Union[List[Dict[str, Any]], Dict[str, Any]]``
926
+
927
+ .. code-block:: python3
928
+
929
+ import pm4py
930
+
931
+ footprints = pm4py.discover_footprints(
932
+ dataframe,
933
+ activity_key='concept:name',
934
+ case_id_key='case:concept:name',
935
+ timestamp_key='time:timestamp'
936
+ )
937
+ """
938
+ from pm4py.algo.discovery.footprints import algorithm as fp_discovery
939
+
940
+ return fp_discovery.apply(*args)
941
+
942
+
943
+ def discover_eventually_follows_graph(
944
+ log: Union[EventLog, pd.DataFrame],
945
+ activity_key: str = "concept:name",
946
+ timestamp_key: str = "time:timestamp",
947
+ case_id_key: str = "case:concept:name",
948
+ ) -> Dict[Tuple[str, str], int]:
949
+ """
950
+ Generates the Eventually-Follows Graph from a log.
951
+
952
+ The Eventually-Follows Graph is a dictionary that maps each pair of activities to the number of times one activity eventually follows the other in the log.
953
+
954
+ :param log: Event log or Pandas DataFrame.
955
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
956
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
957
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
958
+ :return: A dictionary mapping each pair of activities to the count of their eventually-follows relationship.
959
+ :rtype: ``Dict[Tuple[str, str], int]``
960
+
961
+ .. code-block:: python3
962
+
963
+ import pm4py
964
+
965
+ efg = pm4py.discover_eventually_follows_graph(
966
+ dataframe,
967
+ activity_key='concept:name',
968
+ case_id_key='case:concept:name',
969
+ timestamp_key='time:timestamp'
970
+ )
971
+ """
972
+ __event_log_deprecation_warning(log)
973
+
974
+ properties = get_properties(
975
+ log,
976
+ activity_key=activity_key,
977
+ timestamp_key=timestamp_key,
978
+ case_id_key=case_id_key,
979
+ )
980
+
981
+ if check_is_pandas_dataframe(log):
982
+ check_pandas_dataframe_columns(
983
+ log,
984
+ activity_key=activity_key,
985
+ timestamp_key=timestamp_key,
986
+ case_id_key=case_id_key,
987
+ )
988
+
989
+ if is_polars_lazyframe(log):
990
+ from pm4py.statistics.eventually_follows.polars import get
991
+ return get.apply(log, parameters=properties)
992
+ else:
993
+ from pm4py.statistics.eventually_follows.pandas import get
994
+ return get.apply(log, parameters=properties)
995
+ else:
996
+ from pm4py.statistics.eventually_follows.log import get
997
+
998
+ return get.apply(log, parameters=properties)
999
+
1000
+
1001
+ def discover_bpmn_inductive(
1002
+ log: Union[EventLog, pd.DataFrame, DFG],
1003
+ noise_threshold: float = 0.0,
1004
+ multi_processing: bool = constants.ENABLE_MULTIPROCESSING_DEFAULT,
1005
+ activity_key: str = "concept:name",
1006
+ timestamp_key: str = "time:timestamp",
1007
+ case_id_key: str = "case:concept:name",
1008
+ disable_fallthroughs: bool = False,
1009
+ ) -> BPMN:
1010
+ """
1011
+ Discovers a BPMN model using the Inductive Miner algorithm.
1012
+
1013
+ The Inductive Miner detects a 'cut' in the log (e.g., sequential, parallel, concurrent, loop) and recursively applies the algorithm to sublogs until a base case is found.
1014
+ Inductive miner models typically use hidden transitions for skipping or looping portions of the model, and each visible transition has a unique label.
1015
+
1016
+ :param log: Event log, Pandas DataFrame, or typed DFG.
1017
+ :param noise_threshold: Noise threshold (default: 0.0).
1018
+ :param multi_processing: Enables or disables multiprocessing in the Inductive Miner (default: constants.ENABLE_MULTIPROCESSING_DEFAULT).
1019
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
1020
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
1021
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
1022
+ :param disable_fallthroughs: Disables the Inductive Miner fall-throughs (default: False).
1023
+ :return: A BPMN object representing the discovered BPMN model.
1024
+ :rtype: ``BPMN``
1025
+
1026
+ .. code-block:: python3
1027
+
1028
+ import pm4py
1029
+
1030
+ bpmn_graph = pm4py.discover_bpmn_inductive(
1031
+ dataframe,
1032
+ activity_key='concept:name',
1033
+ case_id_key='case:concept:name',
1034
+ timestamp_key='time:timestamp'
1035
+ )
1036
+ """
1037
+ __event_log_deprecation_warning(log)
1038
+
1039
+ if check_is_pandas_dataframe(log):
1040
+ check_pandas_dataframe_columns(
1041
+ log,
1042
+ activity_key=activity_key,
1043
+ timestamp_key=timestamp_key,
1044
+ case_id_key=case_id_key,
1045
+ )
1046
+
1047
+ pt = discover_process_tree_inductive(
1048
+ log,
1049
+ noise_threshold,
1050
+ multi_processing=multi_processing,
1051
+ activity_key=activity_key,
1052
+ timestamp_key=timestamp_key,
1053
+ case_id_key=case_id_key,
1054
+ disable_fallthroughs=disable_fallthroughs,
1055
+ )
1056
+ from pm4py.convert import convert_to_bpmn
1057
+
1058
+ return convert_to_bpmn(pt)
1059
+
1060
+
1061
+ def discover_bpmn_split_miner(
1062
+ log: Union[EventLog, pd.DataFrame],
1063
+ epsilon: float = 0.1,
1064
+ eta: float = 0.4,
1065
+ minimize_or_joins: bool = True,
1066
+ variant: str = "classic",
1067
+ activity_key: str = "concept:name",
1068
+ timestamp_key: str = "time:timestamp",
1069
+ case_id_key: str = "case:concept:name",
1070
+ ) -> BPMN:
1071
+ """Discover a BPMN model using Split Miner.
1072
+
1073
+ Two variants are available:
1074
+
1075
+ * ``"classic"`` — the original Split Miner of Augusto, Conforti,
1076
+ Dumas, La Rosa, Polyvyanyy (KAIS, 2019).
1077
+ * ``"sm2"`` — Split Miner 2.0 (Augusto, Dumas, La Rosa, 2021): uses
1078
+ activity lifecycle information to detect true concurrency and
1079
+ inclusive (OR) choices.
1080
+
1081
+ :param log: Event log or Pandas DataFrame.
1082
+ :param epsilon: Concurrency threshold ε ∈ [0, 1] (default 0.1). With a
1083
+ lower ε more pairs of activities are considered concurrent.
1084
+ :param eta: Filtering percentile η ∈ [0, 1] (default 0.4). Lower η
1085
+ keeps more edges (higher fitness, more complex model). Used by the
1086
+ ``classic`` variant only; ``sm2`` pins η to 1.0 and ignores this.
1087
+ :param minimize_or_joins: Replace trivial OR-joins with their XOR/AND
1088
+ equivalent (Algorithm 9 of the SM 1.x paper). Default ``True``.
1089
+ Used by the ``classic`` variant only; for ``sm2`` the OR handling
1090
+ is an intrinsic stage that always runs, so this flag is ignored.
1091
+ :param variant: ``"classic"`` (default) or ``"sm2"``.
1092
+ :param activity_key: XES attribute holding the activity label
1093
+ (default ``"concept:name"``).
1094
+ :param timestamp_key: XES attribute holding the event timestamp
1095
+ (default ``"time:timestamp"``). Used only by the ``sm2`` variant.
1096
+ :param case_id_key: Attribute used as case identifier in pandas inputs
1097
+ (default ``"case:concept:name"``).
1098
+ :return: A :class:`BPMN` model.
1099
+ :rtype: ``BPMN``
1100
+
1101
+ .. code-block:: python3
1102
+
1103
+ import pm4py
1104
+
1105
+ bpmn_graph = pm4py.discover_bpmn_split_miner(
1106
+ log,
1107
+ epsilon=0.1,
1108
+ eta=0.4,
1109
+ variant="sm2",
1110
+ )
1111
+ """
1112
+ __event_log_deprecation_warning(log)
1113
+
1114
+ if check_is_pandas_dataframe(log):
1115
+ check_pandas_dataframe_columns(
1116
+ log,
1117
+ activity_key=activity_key,
1118
+ timestamp_key=timestamp_key,
1119
+ case_id_key=case_id_key,
1120
+ )
1121
+
1122
+ from pm4py.algo.discovery.split_miner import algorithm as sm_alg
1123
+
1124
+ if variant == "sm2":
1125
+ sm_variant = sm_alg.SM2
1126
+ from pm4py.algo.discovery.split_miner.variants.sm2 import (
1127
+ Parameters as SmParameters,
1128
+ )
1129
+ elif variant == "classic":
1130
+ sm_variant = sm_alg.CLASSIC
1131
+ from pm4py.algo.discovery.split_miner.variants.classic import (
1132
+ Parameters as SmParameters,
1133
+ )
1134
+ else:
1135
+ raise ValueError(
1136
+ f"Unknown Split Miner variant: {variant!r} "
1137
+ f"(expected 'classic' or 'sm2')"
1138
+ )
1139
+
1140
+ parameters = {
1141
+ SmParameters.EPSILON: epsilon,
1142
+ SmParameters.ETA: eta,
1143
+ SmParameters.OR_MINIMISE: minimize_or_joins,
1144
+ SmParameters.ACTIVITY_KEY: activity_key,
1145
+ }
1146
+ if variant == "sm2":
1147
+ parameters[SmParameters.TIMESTAMP_KEY] = timestamp_key
1148
+
1149
+ return sm_alg.apply(log, parameters=parameters, variant=sm_variant)
1150
+
1151
+
1152
+ def discover_transition_system(
1153
+ log: Union[EventLog, pd.DataFrame],
1154
+ direction: str = "forward",
1155
+ window: int = 2,
1156
+ view: str = "sequence",
1157
+ activity_key: str = "concept:name",
1158
+ timestamp_key: str = "time:timestamp",
1159
+ case_id_key: str = "case:concept:name",
1160
+ ) -> TransitionSystem:
1161
+ """
1162
+ Discovers a Transition System from a log.
1163
+
1164
+ The Transition System is built based on the specified direction, window size, and view. It captures the transitions between states of activity sequences.
1165
+
1166
+ :param log: Event log or Pandas DataFrame.
1167
+ :param direction: Direction in which the transition system is built ("forward" or "backward") (default: "forward").
1168
+ :param window: Window size for state construction (e.g., 2, 3) (default: 2).
1169
+ :param view: View to use in the construction of the states ("sequence", "set", "multiset") (default: "sequence").
1170
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
1171
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
1172
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
1173
+ :return: A TransitionSystem object representing the discovered transition system.
1174
+ :rtype: ``TransitionSystem``
1175
+
1176
+ .. code-block:: python3
1177
+
1178
+ import pm4py
1179
+
1180
+ transition_system = pm4py.discover_transition_system(
1181
+ dataframe,
1182
+ activity_key='concept:name',
1183
+ case_id_key='case:concept:name',
1184
+ timestamp_key='time:timestamp'
1185
+ )
1186
+ """
1187
+ __event_log_deprecation_warning(log)
1188
+
1189
+ if check_is_pandas_dataframe(log):
1190
+ check_pandas_dataframe_columns(
1191
+ log,
1192
+ activity_key=activity_key,
1193
+ timestamp_key=timestamp_key,
1194
+ case_id_key=case_id_key,
1195
+ )
1196
+
1197
+ properties = get_properties(
1198
+ log,
1199
+ activity_key=activity_key,
1200
+ timestamp_key=timestamp_key,
1201
+ case_id_key=case_id_key,
1202
+ )
1203
+ properties["direction"] = direction
1204
+ properties["window"] = window
1205
+ properties["view"] = view
1206
+
1207
+ from pm4py.algo.discovery.transition_system import (
1208
+ algorithm as ts_discovery,
1209
+ )
1210
+
1211
+ return ts_discovery.apply(log, parameters=properties)
1212
+
1213
+
1214
+ def discover_prefix_tree(
1215
+ log: Union[EventLog, pd.DataFrame],
1216
+ max_path_length: Optional[int] = None,
1217
+ activity_key: str = "concept:name",
1218
+ timestamp_key: str = "time:timestamp",
1219
+ case_id_key: str = "case:concept:name",
1220
+ ) -> Trie:
1221
+ """
1222
+ Discovers a Prefix Tree from the provided log.
1223
+
1224
+ A Prefix Tree represents all the unique prefixes of activity sequences in the log.
1225
+
1226
+ :param log: Event log or Pandas DataFrame.
1227
+ :param max_path_length: maximum path length (each trace is trimmed afterwards).
1228
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
1229
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
1230
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
1231
+ :return: A Trie object representing the discovered prefix tree.
1232
+ :rtype: ``Trie``
1233
+
1234
+ .. code-block:: python3
1235
+
1236
+ import pm4py
1237
+
1238
+ prefix_tree = pm4py.discover_prefix_tree(
1239
+ dataframe,
1240
+ activity_key='concept:name',
1241
+ case_id_key='case:concept:name',
1242
+ timestamp_key='time:timestamp'
1243
+ )
1244
+ """
1245
+ __event_log_deprecation_warning(log)
1246
+
1247
+ if check_is_pandas_dataframe(log):
1248
+ check_pandas_dataframe_columns(
1249
+ log,
1250
+ activity_key=activity_key,
1251
+ timestamp_key=timestamp_key,
1252
+ case_id_key=case_id_key,
1253
+ )
1254
+
1255
+ properties = get_properties(
1256
+ log,
1257
+ activity_key=activity_key,
1258
+ timestamp_key=timestamp_key,
1259
+ case_id_key=case_id_key,
1260
+ )
1261
+
1262
+ properties["max_path_length"] = max_path_length
1263
+
1264
+ from pm4py.algo.transformation.log_to_trie import (
1265
+ algorithm as trie_discovery,
1266
+ )
1267
+
1268
+ return trie_discovery.apply(log, parameters=properties)
1269
+
1270
+
1271
+ def discover_temporal_profile(
1272
+ log: Union[EventLog, pd.DataFrame],
1273
+ activity_key: str = "concept:name",
1274
+ timestamp_key: str = "time:timestamp",
1275
+ case_id_key: str = "case:concept:name",
1276
+ ) -> Dict[Tuple[str, str], Tuple[float, float]]:
1277
+ """
1278
+ Discovers a Temporal Profile from a log.
1279
+
1280
+ Implements the approach described in:
1281
+ Stertz, Florian, Jürgen Mangler, and Stefanie Rinderle-Ma. "Temporal Conformance Checking at Runtime based on Time-infused Process Models." arXiv preprint arXiv:2008.07262 (2020).
1282
+
1283
+ The output is a dictionary containing, for every pair of activities that eventually follow each other in at least one case of the log,
1284
+ the average and the standard deviation of the time difference between their timestamps.
1285
+
1286
+ Example:
1287
+ If the log has two cases:
1288
+
1289
+ - Case 1: A (timestamp: 1980-01) → B (timestamp: 1980-03) → C (timestamp: 1980-06)
1290
+ - Case 2: A (timestamp: 1990-01) → B (timestamp: 1990-02) → D (timestamp: 1990-03)
1291
+
1292
+ The returned dictionary will contain::
1293
+
1294
+ {
1295
+ ('A', 'B'): (1.5 months, 0.5 months),
1296
+ ('A', 'C'): (5 months, 0),
1297
+ ('A', 'D'): (2 months, 0)
1298
+ }
1299
+
1300
+ :param log: Event log or Pandas DataFrame.
1301
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
1302
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
1303
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
1304
+ :return: A dictionary mapping each pair of activities to a tuple of (average time difference, standard deviation).
1305
+ :rtype: ``Dict[Tuple[str, str], Tuple[float, float]]``
1306
+
1307
+ .. code-block:: python3
1308
+
1309
+ import pm4py
1310
+
1311
+ temporal_profile = pm4py.discover_temporal_profile(
1312
+ dataframe,
1313
+ activity_key='concept:name',
1314
+ case_id_key='case:concept:name',
1315
+ timestamp_key='time:timestamp'
1316
+ )
1317
+
1318
+ """
1319
+ __event_log_deprecation_warning(log)
1320
+
1321
+ if check_is_pandas_dataframe(log):
1322
+ check_pandas_dataframe_columns(
1323
+ log,
1324
+ activity_key=activity_key,
1325
+ timestamp_key=timestamp_key,
1326
+ case_id_key=case_id_key,
1327
+ )
1328
+
1329
+ properties = get_properties(
1330
+ log,
1331
+ activity_key=activity_key,
1332
+ timestamp_key=timestamp_key,
1333
+ case_id_key=case_id_key,
1334
+ )
1335
+
1336
+ from pm4py.algo.discovery.temporal_profile import (
1337
+ algorithm as temporal_profile_discovery,
1338
+ )
1339
+
1340
+ return temporal_profile_discovery.apply(log, parameters=properties)
1341
+
1342
+
1343
+ def discover_log_skeleton(
1344
+ log: Union[EventLog, pd.DataFrame],
1345
+ noise_threshold: float = 0.0,
1346
+ activity_key: str = "concept:name",
1347
+ timestamp_key: str = "time:timestamp",
1348
+ case_id_key: str = "case:concept:name",
1349
+ ) -> Dict[str, Any]:
1350
+ """
1351
+ Discovers a Log Skeleton from an event log.
1352
+
1353
+ A Log Skeleton is a declarative model consisting of six different constraints:
1354
+ - **directly_follows**: Specifies strict bounds on activities that directly follow each other. Example: 'A should be directly followed by B' and 'B should be directly followed by C'.
1355
+ - **always_before**: Specifies that some activities may only be executed if certain other activities have been executed earlier in the case. Example: 'C should always be preceded by A'.
1356
+ - **always_after**: Specifies that certain activities should always trigger the execution of some other activities later in the case. Example: 'A should always be followed by C'.
1357
+ - **equivalence**: Specifies that a given pair of activities should occur the same number of times within a case. Example: 'B and C should always occur the same number of times'.
1358
+ - **never_together**: Specifies that a given pair of activities should never occur together in a case. Example: 'There should be no case containing both C and D'.
1359
+ - **activ_occurrences**: Specifies allowed numbers of occurrences per activity. Example: 'Activity A can occur 1 or 2 times, and Activity B can occur 1 to 4 times'.
1360
+
1361
+ Reference paper:
1362
+ Verbeek, H. M. W., and R. Medeiros de Carvalho. "Log skeletons: A classification approach to process discovery." arXiv preprint arXiv:1806.08247 (2018).
1363
+
1364
+ :param log: Event log or Pandas DataFrame.
1365
+ :param noise_threshold: Noise threshold influencing the strictness of constraints (default: 0.0).
1366
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
1367
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
1368
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
1369
+ :return: A dictionary representing the Log Skeleton with various constraints.
1370
+ :rtype: ``Dict[str, Any]``
1371
+
1372
+ .. code-block:: python3
1373
+
1374
+ import pm4py
1375
+
1376
+ log_skeleton = pm4py.discover_log_skeleton(
1377
+ dataframe,
1378
+ noise_threshold=0.1,
1379
+ activity_key='concept:name',
1380
+ case_id_key='case:concept:name',
1381
+ timestamp_key='time:timestamp'
1382
+ )
1383
+ """
1384
+ __event_log_deprecation_warning(log)
1385
+
1386
+ if check_is_pandas_dataframe(log):
1387
+ check_pandas_dataframe_columns(
1388
+ log,
1389
+ activity_key=activity_key,
1390
+ timestamp_key=timestamp_key,
1391
+ case_id_key=case_id_key,
1392
+ )
1393
+
1394
+ properties = get_properties(
1395
+ log,
1396
+ activity_key=activity_key,
1397
+ timestamp_key=timestamp_key,
1398
+ case_id_key=case_id_key,
1399
+ )
1400
+ properties["noise_threshold"] = noise_threshold
1401
+
1402
+ from pm4py.algo.discovery.log_skeleton import (
1403
+ algorithm as log_skeleton_discovery,
1404
+ )
1405
+
1406
+ return log_skeleton_discovery.apply(log, parameters=properties)
1407
+
1408
+
1409
+ def discover_declare(
1410
+ log: Union[EventLog, pd.DataFrame],
1411
+ allowed_templates: Optional[Set[str]] = None,
1412
+ considered_activities: Optional[Set[str]] = None,
1413
+ min_support_ratio: Optional[float] = None,
1414
+ min_confidence_ratio: Optional[float] = None,
1415
+ activity_key: str = "concept:name",
1416
+ timestamp_key: str = "time:timestamp",
1417
+ case_id_key: str = "case:concept:name",
1418
+ ) -> Dict[str, Dict[Any, Dict[str, int]]]:
1419
+ """
1420
+ Discovers a DECLARE model from an event log.
1421
+
1422
+ Reference paper:
1423
+ F. M. Maggi, A. J. Mooij and W. M. P. van der Aalst, "User-guided discovery of declarative process models," 2011 IEEE Symposium on Computational Intelligence and Data Mining (CIDM), Paris, France, 2011, pp. 192-199, doi: 10.1109/CIDM.2011.5949297.
1424
+
1425
+ :param log: Event log or Pandas DataFrame.
1426
+ :param allowed_templates: (Optional) Set of DECLARE templates to consider for discovery.
1427
+ :param considered_activities: (Optional) Set of activities to consider for discovery.
1428
+ :param min_support_ratio: (Optional) Minimum percentage of cases for which the discovered rules apply.
1429
+ :param min_confidence_ratio: (Optional) Minimum percentage of cases for which the discovered rules are valid, based on the rule's support.
1430
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
1431
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
1432
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
1433
+ :return: A dictionary representing the discovered DECLARE model with constraints and their parameters.
1434
+ :rtype: ``Dict[str, Dict[Any, Dict[str, int]]]``
1435
+
1436
+ .. code-block:: python3
1437
+
1438
+ import pm4py
1439
+
1440
+ declare_model = pm4py.discover_declare(log)
1441
+ """
1442
+ __event_log_deprecation_warning(log)
1443
+
1444
+ if check_is_pandas_dataframe(log):
1445
+ check_pandas_dataframe_columns(
1446
+ log,
1447
+ activity_key=activity_key,
1448
+ timestamp_key=timestamp_key,
1449
+ case_id_key=case_id_key,
1450
+ )
1451
+
1452
+ properties = get_properties(
1453
+ log,
1454
+ activity_key=activity_key,
1455
+ timestamp_key=timestamp_key,
1456
+ case_id_key=case_id_key,
1457
+ )
1458
+ properties["allowed_templates"] = allowed_templates
1459
+ properties["considered_activities"] = considered_activities
1460
+ properties["min_support_ratio"] = min_support_ratio
1461
+ properties["min_confidence_ratio"] = min_confidence_ratio
1462
+
1463
+ from pm4py.algo.discovery.declare import algorithm as declare_discovery
1464
+
1465
+ return declare_discovery.apply(log, parameters=properties)
1466
+
1467
+
1468
+ def discover_powl(
1469
+ log: Union[EventLog, pd.DataFrame],
1470
+ variant=None,
1471
+ filtering_weight_factor: float = 0.0,
1472
+ order_graph_filtering_threshold: float = None,
1473
+ activity_key: str = "concept:name",
1474
+ timestamp_key: str = "time:timestamp",
1475
+ case_id_key: str = "case:concept:name",
1476
+ ) -> POWL:
1477
+ """
1478
+ Discovers a POWL (Partially Ordered Workflow Language) model from an event log.
1479
+
1480
+ Reference paper:
1481
+ Kourani, Humam, and Sebastiaan J. van Zelst. "POWL: partially ordered workflow language." International Conference on Business Process Management. Cham: Springer Nature Switzerland, 2023.
1482
+
1483
+ :param log: Event log or Pandas DataFrame.
1484
+ :param variant: Variant of the POWL discovery algorithm to use.
1485
+ :param filtering_weight_factor: Factoring threshold for filtering weights, accepts values 0 <= x < 1 (default: 0.0).
1486
+ :param order_graph_filtering_threshold: Filtering threshold for the order graph, valid for the DYNAMIC_CLUSTERING variant, accepts values 0.5 < x <= 1 (default: None).
1487
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
1488
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
1489
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
1490
+ :return: A POWL object representing the discovered POWL model.
1491
+ :rtype: ``POWL``
1492
+
1493
+ .. code-block:: python3
1494
+
1495
+ import pm4py
1496
+
1497
+ log = pm4py.read_xes('tests/input_data/receipt.xes')
1498
+ powl_model = pm4py.discover_powl(
1499
+ log,
1500
+ activity_key='concept:name'
1501
+ )
1502
+ print(powl_model)
1503
+ """
1504
+ from pm4py.algo.discovery.powl.inductive.variants.dynamic_clustering_frequency.dynamic_clustering_frequency_partial_order_cut import (
1505
+ ORDER_FREQUENCY_RATIO, )
1506
+ from pm4py.algo.discovery.powl.inductive.variants.powl_discovery_varaints import (
1507
+ POWLDiscoveryVariant, )
1508
+
1509
+ if variant is None:
1510
+ variant = POWLDiscoveryVariant.MAXIMAL
1511
+
1512
+ __event_log_deprecation_warning(log)
1513
+
1514
+ if check_is_pandas_dataframe(log):
1515
+ check_pandas_dataframe_columns(
1516
+ log,
1517
+ activity_key=activity_key,
1518
+ timestamp_key=timestamp_key,
1519
+ case_id_key=case_id_key,
1520
+ )
1521
+
1522
+ #import pm4py
1523
+ #log = pm4py.convert_to_event_log(log, case_id_key=case_id_key)
1524
+ properties = get_properties(log, activity_key=activity_key, timestamp_key=timestamp_key)
1525
+
1526
+ if order_graph_filtering_threshold is not None:
1527
+ if variant is POWLDiscoveryVariant.DYNAMIC_CLUSTERING:
1528
+ properties[ORDER_FREQUENCY_RATIO] = order_graph_filtering_threshold
1529
+ else:
1530
+ raise Exception(
1531
+ "The order graph filtering threshold can only be used for the DYNAMIC_CLUSTERING variant."
1532
+ )
1533
+
1534
+ properties["filtering_threshold"] = filtering_weight_factor
1535
+
1536
+ from pm4py.algo.discovery.powl import algorithm as powl_discovery
1537
+
1538
+ return powl_discovery.apply(log, variant=variant, parameters=properties)
1539
+
1540
+
1541
+ def discover_batches(
1542
+ log: Union[EventLog, pd.DataFrame],
1543
+ merge_distance: int = 15 * 60,
1544
+ min_batch_size: int = 2,
1545
+ activity_key: str = "concept:name",
1546
+ timestamp_key: str = "time:timestamp",
1547
+ case_id_key: str = "case:concept:name",
1548
+ resource_key: str = "org:resource",
1549
+ ) -> List[Tuple[Tuple[str, str], int, Dict[str, Any]]]:
1550
+ """
1551
+ Discovers batches from the provided log.
1552
+
1553
+ An activity is executed in batches by a given resource when the resource performs the same activity multiple times in a short period.
1554
+ Identifying such activities may highlight repetitive tasks that could be automated.
1555
+
1556
+ The following batch categories are detected:
1557
+ - **Simultaneous**: All events in the batch have identical start and end timestamps.
1558
+ - **Batching at Start**: All events in the batch have identical start timestamps.
1559
+ - **Batching at End**: All events in the batch have identical end timestamps.
1560
+ - **Sequential Batching**: Consecutive events have the end of the first equal to the start of the second.
1561
+ - **Concurrent Batching**: Consecutive events that do not match sequentially.
1562
+
1563
+ Reference paper:
1564
+ Martin, N., Swennen, M., Depaire, B., Jans, M., Caris, A., & Vanhoof, K. (2015, December). Batch Processing: Definition and Event Log Identification. In SIMPDA (pp. 137-140).
1565
+
1566
+ :param log: Event log or Pandas DataFrame.
1567
+ :param merge_distance: Maximum time distance (in seconds) between non-overlapping intervals to consider them part of the same batch (default: 900 seconds, i.e., 15 minutes).
1568
+ :param min_batch_size: Minimum number of events required to form a batch (default: 2).
1569
+ :param activity_key: Attribute to be used for the activity (default: "concept:name").
1570
+ :param timestamp_key: Attribute to be used for the timestamp (default: "time:timestamp").
1571
+ :param case_id_key: Attribute to be used as case identifier (default: "case:concept:name").
1572
+ :param resource_key: Attribute to be used as resource (default: "org:resource").
1573
+ :return: A sorted list of tuples, each containing:
1574
+ - The (activity, resource) pair.
1575
+ - The number of batches for the given activity-resource.
1576
+ - A dictionary with batch details.
1577
+ :rtype: ``List[Tuple[Tuple[str, str], int, Dict[str, Any]]]``
1578
+
1579
+ .. code-block:: python3
1580
+
1581
+ import pm4py
1582
+
1583
+ batches = pm4py.discover_batches(
1584
+ dataframe,
1585
+ activity_key='concept:name',
1586
+ case_id_key='case:concept:name',
1587
+ timestamp_key='time:timestamp',
1588
+ resource_key='org:resource'
1589
+ )
1590
+ """
1591
+ __event_log_deprecation_warning(log)
1592
+
1593
+ if check_is_pandas_dataframe(log):
1594
+ check_pandas_dataframe_columns(
1595
+ log,
1596
+ activity_key=activity_key,
1597
+ timestamp_key=timestamp_key,
1598
+ case_id_key=case_id_key,
1599
+ )
1600
+
1601
+ properties = get_properties(
1602
+ log,
1603
+ activity_key=activity_key,
1604
+ timestamp_key=timestamp_key,
1605
+ case_id_key=case_id_key,
1606
+ resource_key=resource_key,
1607
+ )
1608
+ properties["merge_distance"] = merge_distance
1609
+ properties["min_batch_size"] = min_batch_size
1610
+
1611
+ from pm4py.algo.discovery.batches import algorithm as batches_discovery
1612
+
1613
+ return batches_discovery.apply(log, parameters=properties)
1614
+
1615
+
1616
+ def correlation_miner(
1617
+ df: pd.DataFrame,
1618
+ annotation: str = "frequency",
1619
+ activity_key: str = "concept:name",
1620
+ timestamp_key: str = "time:timestamp",
1621
+ ) -> Tuple[dict, dict, dict]:
1622
+ """
1623
+ Applies the Correlation Miner to 'discover' the frequency/performance DFG from an event log without case ID.
1624
+
1625
+ The approach is described in:
1626
+ Pourmirza, Shaya, Remco Dijkman, and Paul Grefen. "Correlation miner: mining business process models and event
1627
+ correlations without case identifiers." International Journal of Cooperative Information Systems 26.02 (2017):
1628
+ 1742002.
1629
+
1630
+ :param log: Pandas dataframe
1631
+ :param annotation: annotation ('frequency' for the frequency DFG, or 'performance' for the performance DFG)
1632
+ :param activity_key: attribute to be used for the activity
1633
+ :param timestamp_key: attribute to be used for the timestamp
1634
+ :rtype: ``Tuple[dict, dict, dict]``
1635
+
1636
+ .. code-block:: python3
1637
+
1638
+ import pm4py
1639
+
1640
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
1641
+ log = log[["concept:name", "time:timestamp"]]
1642
+
1643
+ dfg, sa, ea = pm4py.correlation_miner(log)
1644
+ pm4py.view_dfg(dfg, sa, ea, format="svg")
1645
+
1646
+ perf_dfg, sa, ea = pm4py.correlation_miner(log, annotation="performance")
1647
+ pm4py.view_performance_dfg(perf_dfg, sa, ea, format="svg")
1648
+ """
1649
+ properties = get_properties(
1650
+ df, activity_key=activity_key, timestamp_key=timestamp_key
1651
+ )
1652
+
1653
+ if is_polars_lazyframe(df):
1654
+ if importlib.util.find_spec("polars") is None:
1655
+ raise RuntimeError(
1656
+ "Polars LazyFrame provided but 'polars' package is not installed."
1657
+ )
1658
+
1659
+ import polars as pl # type: ignore[import-untyped]
1660
+
1661
+ if activity_key not in df.columns:
1662
+ raise Exception(
1663
+ f"Column '{activity_key}' is not present in the provided Polars LazyFrame."
1664
+ )
1665
+
1666
+ first_row = (
1667
+ df.select(pl.col(activity_key))
1668
+ .head(1)
1669
+ .collect()
1670
+ )
1671
+ if first_row.height == 0:
1672
+ raise ValueError("The provided Polars LazyFrame must contain at least one event.")
1673
+ first_activity = first_row[activity_key].to_list()[0]
1674
+
1675
+ last_row = (
1676
+ df.select(pl.col(activity_key))
1677
+ .tail(1)
1678
+ .collect()
1679
+ )
1680
+ last_activity = last_row[activity_key].to_list()[0]
1681
+ else:
1682
+ # code for Pandas dataframes
1683
+ first_activity = df[activity_key].iloc[0]
1684
+ last_activity = df[activity_key].iloc[-1]
1685
+
1686
+ from pm4py.algo.discovery.correlation_mining import (
1687
+ algorithm as correlation_miner,
1688
+ )
1689
+
1690
+ dfg, perf_dfg = correlation_miner.apply(df, parameters=properties)
1691
+ perf_dfg = {a: float(y) for a, y in perf_dfg.items()}
1692
+
1693
+ activities_entering = Counter()
1694
+ activities_exiting = Counter()
1695
+
1696
+ for edge, freq in dfg.items():
1697
+ activities_exiting[edge[0]] += freq
1698
+ activities_entering[edge[1]] += freq
1699
+
1700
+ start_activities = {first_activity: activities_exiting[first_activity]}
1701
+ end_activities = {last_activity: activities_entering[last_activity]}
1702
+
1703
+ if annotation == "frequency":
1704
+ return dfg, start_activities, end_activities
1705
+ else:
1706
+ return perf_dfg, start_activities, end_activities
1707
+
1708
+
1709
+ def discover_otg(
1710
+ ocel: OCEL,
1711
+ variant=None,
1712
+ parameters: Optional[Dict[Any, Any]] = None,
1713
+ ) -> Tuple[Set[str], Dict[Tuple[str, str, str], int]]:
1714
+ """
1715
+ Discovers an Object-Type Graph (OTG) from an object-centric event log.
1716
+
1717
+ Published in: https://publications.rwth-aachen.de/record/1014107
1718
+
1719
+ An OTG summarizes how object types are related across different interaction graphs extracted from the OCEL.
1720
+ Specifically, an OTG is a tuple containing:
1721
+ - The set of object types
1722
+ - The edges along with the frequency, where each edge is (object_type1, relationship, object_type2).
1723
+
1724
+ Relationship can be:
1725
+ * object_interaction (objects related in some event)
1726
+ * object_descendants (lifecycle of the first event starts before the other object)
1727
+ * object_inheritance (lifecycle of the first object ends exactly when the second one starts)
1728
+ * object_cobirth (objects start their lifecycle in the same event)
1729
+ * object_codeath (objects end their lifecycle in the sae event)
1730
+
1731
+ :param ocel: Object-centric event log.
1732
+ :param variant: Variant of the OTG discovery algorithm to use (default: classic variant).
1733
+ :param parameters: Optional variant-specific parameters.
1734
+ :return: Tuple containing the set of object types and the OTG edges with their frequencies.
1735
+ :rtype: ``Tuple[Set[str], Dict[Tuple[str, str, str], int]]``
1736
+
1737
+ .. code-block:: python3
1738
+
1739
+ import pm4py
1740
+
1741
+ otg = pm4py.discover_otg(ocel)
1742
+ """
1743
+ from pm4py.algo.discovery.ocel.otg import algorithm as otg_discovery
1744
+
1745
+ if variant is None:
1746
+ variant = otg_discovery.Variants.CLASSIC
1747
+
1748
+ return otg_discovery.apply(ocel, variant=variant, parameters=parameters)
1749
+
1750
+
1751
+ def discover_etot(
1752
+ ocel: OCEL,
1753
+ variant=None,
1754
+ parameters: Optional[Dict[Any, Any]] = None,
1755
+ ) -> Tuple[
1756
+ Set[str],
1757
+ Set[str],
1758
+ Set[Tuple[str, str]],
1759
+ Dict[Tuple[str, str], int],
1760
+ ]:
1761
+ """
1762
+ Discovers the ET-OT (Event Type - Object Type) graph from an object-centric event log.
1763
+
1764
+ Published in: https://publications.rwth-aachen.de/record/1014107
1765
+
1766
+ The ET-OT graph captures the relationships between event types and object types along with their frequencies.
1767
+ Specifically, an ET-OT graph is a tuple consisting of:
1768
+ - Set of activities
1769
+ - Set of object types
1770
+ - Set of relationships, where an edge (a, ot) indicates that events of type a are associated with objects of type ot
1771
+ - A dictionary associating each relationship to a weight (frequency)
1772
+
1773
+ :param ocel: Object-centric event log.
1774
+ :param variant: Variant of the ET-OT discovery algorithm to use (default: classic variant).
1775
+ :param parameters: Optional variant-specific parameters.
1776
+ :return: Tuple containing the set of activities, the set of object types, the ET-OT edges, and their frequencies.
1777
+ :rtype: ``Tuple[Set[str], Set[str], Set[Tuple[str, str]], Dict[Tuple[str, str], int]]``
1778
+
1779
+ .. code-block:: python3
1780
+
1781
+ import pm4py
1782
+
1783
+ etot = pm4py.discover_etot(ocel)
1784
+ """
1785
+ from pm4py.algo.discovery.ocel.etot import algorithm as etot_discovery
1786
+
1787
+ if variant is None:
1788
+ variant = etot_discovery.Variants.CLASSIC
1789
+
1790
+ return etot_discovery.apply(ocel, variant=variant, parameters=parameters)
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/filtering.py ADDED
@@ -0,0 +1,2230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ __doc__ = """
23
+ The ``pm4py.filtering`` module contains the filtering features offered in ``pm4py``.
24
+ """
25
+
26
+ from typing import Union, Set, List, Tuple, Collection, Any, Dict, Optional
27
+ from collections import Counter
28
+
29
+ import pandas as pd
30
+
31
+ from pm4py.objects.log.obj import EventLog
32
+ from pm4py.util import constants, xes_constants, pandas_utils, nx_utils
33
+ import warnings
34
+ from pm4py.util.pandas_utils import (
35
+ check_is_pandas_dataframe,
36
+ check_pandas_dataframe_columns,
37
+ )
38
+ from pm4py.utils import (
39
+ get_properties,
40
+ __event_log_deprecation_warning,
41
+ is_polars_lazyframe,
42
+ )
43
+ from pm4py.objects.ocel.obj import OCEL
44
+ from pm4py.utils import __event_log_filtering_level_warning
45
+ import datetime
46
+
47
+
48
+ def _get_dataframe_filtering_package(df):
49
+ if is_polars_lazyframe(df):
50
+ import pm4py.algo.filtering.polars as filtering_pkg
51
+ else:
52
+ import pm4py.algo.filtering.pandas as filtering_pkg
53
+
54
+ return filtering_pkg
55
+
56
+
57
+ def _is_dataframe_like(obj):
58
+ return check_is_pandas_dataframe(obj) or is_polars_lazyframe(obj)
59
+
60
+
61
+ def _normalize_sequence_argument(value):
62
+ """Normalize a prefix/suffix input into the list-of-list structure expected by Polars filters."""
63
+ if isinstance(value, str):
64
+ return [[value]]
65
+ if isinstance(value, (list, tuple)):
66
+ if value and all(isinstance(elem, (list, tuple)) for elem in value):
67
+ return [list(elem) if isinstance(elem, tuple) else list(elem) for elem in value]
68
+ if all(isinstance(elem, str) for elem in value):
69
+ return [list(value)]
70
+ return [[str(value)]]
71
+
72
+
73
+ def filter_log_relative_occurrence_event_attribute(
74
+ log: Union[EventLog, pd.DataFrame],
75
+ min_relative_stake: float,
76
+ attribute_key: str = xes_constants.DEFAULT_NAME_KEY,
77
+ level: str = "cases",
78
+ timestamp_key: str = "time:timestamp",
79
+ case_id_key: str = "case:concept:name",
80
+ ) -> Union[EventLog, pd.DataFrame]:
81
+ """
82
+ Filters the event log, keeping only the events that have an attribute value which occurs:
83
+ - in at least the specified (min_relative_stake) percentage of events when level="events",
84
+ - in at least the specified (min_relative_stake) percentage of cases when level="cases".
85
+
86
+ :param log: Event log or Pandas DataFrame.
87
+ :param min_relative_stake: Minimum percentage of cases (expressed as a number between 0 and 1) in which the attribute should occur.
88
+ :param attribute_key: The attribute to filter.
89
+ :param level: The level of the filter (if level="events", then events; if level="cases", then cases).
90
+ :param timestamp_key: Attribute to be used for the timestamp.
91
+ :param case_id_key: Attribute to be used as case identifier.
92
+ :return: Filtered event log or Pandas DataFrame.
93
+
94
+ .. code-block:: python3
95
+
96
+ import pm4py
97
+
98
+ filtered_dataframe = pm4py.filter_log_relative_occurrence_event_attribute(
99
+ dataframe,
100
+ 0.5,
101
+ attribute_key='concept:name',
102
+ level='cases',
103
+ case_id_key='case:concept:name',
104
+ timestamp_key='time:timestamp'
105
+ )
106
+ """
107
+ __event_log_deprecation_warning(log)
108
+
109
+ parameters = get_properties(
110
+ log,
111
+ timestamp_key=timestamp_key,
112
+ case_id_key=case_id_key,
113
+ activity_key=attribute_key,
114
+ )
115
+ if _is_dataframe_like(log):
116
+ check_pandas_dataframe_columns(
117
+ log, timestamp_key=timestamp_key, case_id_key=case_id_key
118
+ )
119
+ filtering_pkg = _get_dataframe_filtering_package(log)
120
+ attributes_filter = filtering_pkg.attributes.attributes_filter
121
+
122
+ parameters[attributes_filter.Parameters.ATTRIBUTE_KEY] = attribute_key
123
+ parameters[attributes_filter.Parameters.KEEP_ONCE_PER_CASE] = (
124
+ True if level == "cases" else False
125
+ )
126
+ return attributes_filter.filter_df_relative_occurrence_event_attribute(
127
+ log, min_relative_stake, parameters=parameters
128
+ )
129
+ else:
130
+ from pm4py.algo.filtering.log.attributes import attributes_filter
131
+
132
+ parameters[attributes_filter.Parameters.ATTRIBUTE_KEY] = attribute_key
133
+ parameters[attributes_filter.Parameters.KEEP_ONCE_PER_CASE] = (
134
+ True if level == "cases" else False
135
+ )
136
+ return (
137
+ attributes_filter.filter_log_relative_occurrence_event_attribute(
138
+ log, min_relative_stake, parameters=parameters
139
+ )
140
+ )
141
+
142
+
143
+ def filter_start_activities(
144
+ log: Union[EventLog, pd.DataFrame],
145
+ activities: Union[Set[str], List[str]],
146
+ retain: bool = True,
147
+ activity_key: str = "concept:name",
148
+ timestamp_key: str = "time:timestamp",
149
+ case_id_key: str = "case:concept:name",
150
+ ) -> Union[EventLog, pd.DataFrame]:
151
+ """
152
+ Filters cases that have a start activity in the provided list.
153
+
154
+ :param log: Event log or Pandas DataFrame.
155
+ :param activities: Collection of start activities.
156
+ :param retain: If True, retains the traces containing the given start activities; if False, drops the traces.
157
+ :param activity_key: Attribute to be used for the activity.
158
+ :param timestamp_key: Attribute to be used for the timestamp.
159
+ :param case_id_key: Attribute to be used as case identifier.
160
+ :return: Filtered event log or Pandas DataFrame.
161
+
162
+ .. code-block:: python3
163
+
164
+ import pm4py
165
+
166
+ filtered_dataframe = pm4py.filter_start_activities(
167
+ dataframe,
168
+ ['Act. A'],
169
+ activity_key='concept:name',
170
+ case_id_key='case:concept:name',
171
+ timestamp_key='time:timestamp'
172
+ )
173
+ """
174
+ __event_log_deprecation_warning(log)
175
+
176
+ parameters = get_properties(
177
+ log,
178
+ activity_key=activity_key,
179
+ timestamp_key=timestamp_key,
180
+ case_id_key=case_id_key,
181
+ )
182
+ if _is_dataframe_like(log):
183
+ check_pandas_dataframe_columns(
184
+ log,
185
+ activity_key=activity_key,
186
+ timestamp_key=timestamp_key,
187
+ case_id_key=case_id_key,
188
+ )
189
+ filtering_pkg = _get_dataframe_filtering_package(log)
190
+ start_activities_filter = (
191
+ filtering_pkg.start_activities.start_activities_filter
192
+ )
193
+
194
+ parameters[start_activities_filter.Parameters.POSITIVE] = retain
195
+ return start_activities_filter.apply(
196
+ log, activities, parameters=parameters
197
+ )
198
+ else:
199
+ from pm4py.algo.filtering.log.start_activities import (
200
+ start_activities_filter,
201
+ )
202
+
203
+ parameters[start_activities_filter.Parameters.POSITIVE] = retain
204
+ return start_activities_filter.apply(
205
+ log, activities, parameters=parameters
206
+ )
207
+
208
+
209
+ def filter_end_activities(
210
+ log: Union[EventLog, pd.DataFrame],
211
+ activities: Union[Set[str], List[str]],
212
+ retain: bool = True,
213
+ activity_key: str = "concept:name",
214
+ timestamp_key: str = "time:timestamp",
215
+ case_id_key: str = "case:concept:name",
216
+ ) -> Union[EventLog, pd.DataFrame]:
217
+ """
218
+ Filters cases that have an end activity in the provided list.
219
+
220
+ :param log: Event log or Pandas DataFrame.
221
+ :param activities: Collection of end activities.
222
+ :param retain: If True, retains the traces containing the given end activities; if False, drops the traces.
223
+ :param activity_key: Attribute to be used for the activity.
224
+ :param timestamp_key: Attribute to be used for the timestamp.
225
+ :param case_id_key: Attribute to be used as case identifier.
226
+ :return: Filtered event log or Pandas DataFrame.
227
+
228
+ .. code-block:: python3
229
+
230
+ import pm4py
231
+
232
+ filtered_dataframe = pm4py.filter_end_activities(
233
+ dataframe,
234
+ ['Act. Z'],
235
+ activity_key='concept:name',
236
+ case_id_key='case:concept:name',
237
+ timestamp_key='time:timestamp'
238
+ )
239
+ """
240
+ __event_log_deprecation_warning(log)
241
+
242
+ parameters = get_properties(
243
+ log,
244
+ activity_key=activity_key,
245
+ timestamp_key=timestamp_key,
246
+ case_id_key=case_id_key,
247
+ )
248
+ if _is_dataframe_like(log):
249
+ check_pandas_dataframe_columns(
250
+ log,
251
+ activity_key=activity_key,
252
+ timestamp_key=timestamp_key,
253
+ case_id_key=case_id_key,
254
+ )
255
+ filtering_pkg = _get_dataframe_filtering_package(log)
256
+ end_activities_filter = (
257
+ filtering_pkg.end_activities.end_activities_filter
258
+ )
259
+
260
+ parameters[end_activities_filter.Parameters.POSITIVE] = retain
261
+ return end_activities_filter.apply(
262
+ log, activities, parameters=parameters
263
+ )
264
+ else:
265
+ from pm4py.algo.filtering.log.end_activities import (
266
+ end_activities_filter,
267
+ )
268
+
269
+ parameters[end_activities_filter.Parameters.POSITIVE] = retain
270
+ return end_activities_filter.apply(
271
+ log, activities, parameters=parameters
272
+ )
273
+
274
+
275
+ def filter_event_attribute_values(
276
+ log: Union[EventLog, pd.DataFrame],
277
+ attribute_key: str,
278
+ values: Union[Set[str], List[str]],
279
+ level: Optional[str] = None,
280
+ retain: bool = True,
281
+ case_id_key: str = "case:concept:name",
282
+ ) -> Union[EventLog, pd.DataFrame]:
283
+ """
284
+ Filters a log object based on the values of a specified event attribute.
285
+
286
+ :param log: Event log or Pandas DataFrame.
287
+ :param attribute_key: Attribute to filter.
288
+ :param values: Admitted or forbidden values.
289
+ :param level: Specifies how the filter should be applied ('case' filters the cases where at least one occurrence happens; 'event' filters the events, potentially trimming the cases).
290
+ :param retain: Specifies if the values should be kept or removed.
291
+ :param case_id_key: Attribute to be used as case identifier.
292
+ :return: Filtered event log or Pandas DataFrame.
293
+
294
+ .. code-block:: python3
295
+
296
+ import pm4py
297
+
298
+ filtered_dataframe = pm4py.filter_event_attribute_values(
299
+ dataframe,
300
+ 'concept:name',
301
+ ['Act. A', 'Act. Z'],
302
+ case_id_key='case:concept:name'
303
+ )
304
+ """
305
+ __event_log_deprecation_warning(log)
306
+
307
+ if level is None:
308
+ __event_log_filtering_level_warning()
309
+
310
+ parameters = get_properties(log, case_id_key=case_id_key)
311
+ parameters[constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY] = attribute_key
312
+ if _is_dataframe_like(log):
313
+ check_pandas_dataframe_columns(log, case_id_key=case_id_key)
314
+ filtering_pkg = _get_dataframe_filtering_package(log)
315
+ attributes_filter = filtering_pkg.attributes.attributes_filter
316
+
317
+ if level == "event":
318
+ parameters[attributes_filter.Parameters.POSITIVE] = retain
319
+ return attributes_filter.apply_events(
320
+ log, values, parameters=parameters
321
+ )
322
+ elif level == "case":
323
+ parameters[attributes_filter.Parameters.POSITIVE] = retain
324
+ return attributes_filter.apply(log, values, parameters=parameters)
325
+ else:
326
+ from pm4py.algo.filtering.log.attributes import attributes_filter
327
+
328
+ if level == "event":
329
+ parameters[attributes_filter.Parameters.POSITIVE] = retain
330
+ return attributes_filter.apply_events(
331
+ log, values, parameters=parameters
332
+ )
333
+ elif level == "case":
334
+ parameters[attributes_filter.Parameters.POSITIVE] = retain
335
+ return attributes_filter.apply(log, values, parameters=parameters)
336
+
337
+
338
+ def filter_trace_attribute_values(
339
+ log: Union[EventLog, pd.DataFrame],
340
+ attribute_key: str,
341
+ values: Union[Set[str], List[str]],
342
+ retain: bool = True,
343
+ case_id_key: str = "case:concept:name",
344
+ ) -> Union[EventLog, pd.DataFrame]:
345
+ """
346
+ Filters a log based on the values of a specified trace attribute.
347
+
348
+ :param log: Event log or Pandas DataFrame.
349
+ :param attribute_key: Attribute to filter.
350
+ :param values: Collection of values to filter.
351
+ :param retain: Boolean value indicating whether to keep or discard matching traces.
352
+ :param case_id_key: Attribute to be used as case identifier.
353
+ :return: Filtered event log or Pandas DataFrame.
354
+
355
+ .. code-block:: python3
356
+
357
+ import pm4py
358
+
359
+ filtered_dataframe = pm4py.filter_trace_attribute_values(
360
+ dataframe,
361
+ 'case:creator',
362
+ ['Mike'],
363
+ case_id_key='case:concept:name'
364
+ )
365
+ """
366
+ __event_log_deprecation_warning(log)
367
+
368
+ parameters = get_properties(log, case_id_key=case_id_key)
369
+ parameters[constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY] = attribute_key
370
+ if _is_dataframe_like(log):
371
+ check_pandas_dataframe_columns(log, case_id_key=case_id_key)
372
+ filtering_pkg = _get_dataframe_filtering_package(log)
373
+ attributes_filter = filtering_pkg.attributes.attributes_filter
374
+
375
+ parameters[attributes_filter.Parameters.POSITIVE] = retain
376
+ return attributes_filter.apply(log, values, parameters=parameters)
377
+ else:
378
+ from pm4py.algo.filtering.log.attributes import attributes_filter
379
+
380
+ parameters[attributes_filter.Parameters.POSITIVE] = retain
381
+ return attributes_filter.apply_trace_attribute(
382
+ log, values, parameters=parameters
383
+ )
384
+
385
+
386
+ def filter_variants(
387
+ log: Union[EventLog, pd.DataFrame],
388
+ variants: Union[Set[str], List[str], List[Tuple[str]]],
389
+ retain: bool = True,
390
+ activity_key: str = "concept:name",
391
+ timestamp_key: str = "time:timestamp",
392
+ case_id_key: str = "case:concept:name",
393
+ ) -> Union[EventLog, pd.DataFrame]:
394
+ """
395
+ Filters a log based on a specified set of variants.
396
+
397
+ :param log: Event log or Pandas DataFrame.
398
+ :param variants: Collection of variants to filter. A variant should be specified as a list of tuples of activity names, e.g., [('a', 'b', 'c')].
399
+ :param retain: Boolean indicating whether to retain (if True) or remove (if False) traces conforming to the specified variants.
400
+ :param activity_key: Attribute to be used for the activity.
401
+ :param timestamp_key: Attribute to be used for the timestamp.
402
+ :param case_id_key: Attribute to be used as case identifier.
403
+ :return: Filtered event log or Pandas DataFrame.
404
+
405
+ .. code-block:: python3
406
+
407
+ import pm4py
408
+
409
+ filtered_dataframe = pm4py.filter_variants(
410
+ dataframe,
411
+ [('Act. A', 'Act. B', 'Act. Z'), ('Act. A', 'Act. C', 'Act. Z')],
412
+ activity_key='concept:name',
413
+ case_id_key='case:concept:name',
414
+ timestamp_key='time:timestamp'
415
+ )
416
+ """
417
+ __event_log_deprecation_warning(log)
418
+
419
+ from pm4py.util import variants_util
420
+
421
+ parameters = get_properties(
422
+ log,
423
+ activity_key=activity_key,
424
+ timestamp_key=timestamp_key,
425
+ case_id_key=case_id_key,
426
+ )
427
+ if _is_dataframe_like(log):
428
+ check_pandas_dataframe_columns(
429
+ log,
430
+ activity_key=activity_key,
431
+ timestamp_key=timestamp_key,
432
+ case_id_key=case_id_key,
433
+ )
434
+ filtering_pkg = _get_dataframe_filtering_package(log)
435
+ variants_filter = filtering_pkg.variants.variants_filter
436
+
437
+ parameters[variants_filter.Parameters.POSITIVE] = retain
438
+ return variants_filter.apply(log, variants, parameters=parameters)
439
+ else:
440
+ from pm4py.algo.filtering.log.variants import variants_filter
441
+
442
+ parameters[variants_filter.Parameters.POSITIVE] = retain
443
+ return variants_filter.apply(log, variants, parameters=parameters)
444
+
445
+
446
+ def filter_directly_follows_relation(
447
+ log: Union[EventLog, pd.DataFrame],
448
+ relations: List[str],
449
+ retain: bool = True,
450
+ activity_key: str = "concept:name",
451
+ timestamp_key: str = "time:timestamp",
452
+ case_id_key: str = "case:concept:name",
453
+ ) -> Union[EventLog, pd.DataFrame]:
454
+ """
455
+ Retains traces that contain any of the specified 'directly follows' relations.
456
+ For example, if relations == [('a','b'),('a','c')] and log [<a,b,c>,<a,c,b>,<a,d,b>],
457
+ the resulting log will contain traces describing [<a,b,c>,<a,c,b>].
458
+
459
+ :param log: Event log or Pandas DataFrame.
460
+ :param relations: List of activity name pairs, representing allowed or forbidden paths.
461
+ :param retain: Boolean indicating whether the paths should be kept (if True) or removed (if False).
462
+ :param activity_key: Attribute to be used for the activity.
463
+ :param timestamp_key: Attribute to be used for the timestamp.
464
+ :param case_id_key: Attribute to be used as case identifier.
465
+ :return: Filtered event log or Pandas DataFrame.
466
+
467
+ .. code-block:: python3
468
+
469
+ import pm4py
470
+
471
+ filtered_dataframe = pm4py.filter_directly_follows_relation(
472
+ dataframe,
473
+ [('A', 'B'), ('A', 'C')],
474
+ activity_key='concept:name',
475
+ case_id_key='case:concept:name',
476
+ timestamp_key='time:timestamp'
477
+ )
478
+ """
479
+ __event_log_deprecation_warning(log)
480
+
481
+ parameters = get_properties(
482
+ log,
483
+ activity_key=activity_key,
484
+ timestamp_key=timestamp_key,
485
+ case_id_key=case_id_key,
486
+ )
487
+ if _is_dataframe_like(log):
488
+ filtering_pkg = _get_dataframe_filtering_package(log)
489
+ paths_filter = filtering_pkg.paths.paths_filter
490
+
491
+ parameters[paths_filter.Parameters.POSITIVE] = retain
492
+ return paths_filter.apply(log, relations, parameters=parameters)
493
+ else:
494
+ from pm4py.algo.filtering.log.paths import paths_filter
495
+
496
+ parameters[paths_filter.Parameters.POSITIVE] = retain
497
+ return paths_filter.apply(log, relations, parameters=parameters)
498
+
499
+
500
+ def filter_eventually_follows_relation(
501
+ log: Union[EventLog, pd.DataFrame],
502
+ relations: List[str],
503
+ retain: bool = True,
504
+ activity_key: str = "concept:name",
505
+ timestamp_key: str = "time:timestamp",
506
+ case_id_key: str = "case:concept:name",
507
+ ) -> Union[EventLog, pd.DataFrame]:
508
+ """
509
+ Retains traces that contain any of the specified 'eventually follows' relations.
510
+ For example, if relations == [('a','b'),('a','c')] and log [<a,b,c>,<a,c,b>,<a,d,b>],
511
+ the resulting log will contain traces describing [<a,b,c>,<a,c,b>,<a,d,b>].
512
+
513
+ :param log: Event log or Pandas DataFrame.
514
+ :param relations: List of activity name pairs, representing allowed or forbidden paths.
515
+ :param retain: Boolean indicating whether the paths should be kept (if True) or removed (if False).
516
+ :param activity_key: Attribute to be used for the activity.
517
+ :param timestamp_key: Attribute to be used for the timestamp.
518
+ :param case_id_key: Attribute to be used as case identifier.
519
+ :return: Filtered event log or Pandas DataFrame.
520
+
521
+ .. code-block:: python3
522
+
523
+ import pm4py
524
+
525
+ filtered_dataframe = pm4py.filter_eventually_follows_relation(
526
+ dataframe,
527
+ [('A', 'B'), ('A', 'C')],
528
+ activity_key='concept:name',
529
+ case_id_key='case:concept:name',
530
+ timestamp_key='time:timestamp'
531
+ )
532
+ """
533
+ __event_log_deprecation_warning(log)
534
+
535
+ parameters = get_properties(
536
+ log,
537
+ activity_key=activity_key,
538
+ timestamp_key=timestamp_key,
539
+ case_id_key=case_id_key,
540
+ )
541
+ if _is_dataframe_like(log):
542
+ filtering_pkg = _get_dataframe_filtering_package(log)
543
+ ltl_checker = filtering_pkg.ltl.ltl_checker
544
+
545
+ parameters[ltl_checker.Parameters.POSITIVE] = retain
546
+
547
+ if not is_polars_lazyframe(log):
548
+ if retain:
549
+ cases = set()
550
+ else:
551
+ cases = set(log[case_id_key].to_numpy().tolist())
552
+ for path in relations:
553
+ filt_log = ltl_checker.eventually_follows(
554
+ log, path, parameters=parameters
555
+ )
556
+ this_traces = set(filt_log[case_id_key].to_numpy().tolist())
557
+ if retain:
558
+ cases = cases.union(this_traces)
559
+ else:
560
+ cases = cases.intersection(this_traces)
561
+ return log[log[case_id_key].isin(cases)]
562
+ else:
563
+ import polars as pl # type: ignore[import-untyped]
564
+
565
+ case_frames = []
566
+ for path in relations:
567
+ filt_log = ltl_checker.eventually_follows(
568
+ log, path, parameters=parameters
569
+ )
570
+ case_frames.append(
571
+ filt_log.select(pl.col(case_id_key)).unique()
572
+ )
573
+
574
+ if retain:
575
+ if not case_frames:
576
+ return log.filter(pl.lit(False))
577
+ cases_frame = pl.concat(case_frames).unique()
578
+ return log.join(cases_frame, on=case_id_key, how="inner", maintain_order="left")
579
+ else:
580
+ if not case_frames:
581
+ return log
582
+ cases_frame = case_frames[0]
583
+ for frame in case_frames[1:]:
584
+ cases_frame = cases_frame.join(
585
+ frame, on=case_id_key, how="inner",
586
+ maintain_order="left",
587
+ )
588
+ return log.join(cases_frame, on=case_id_key, how="inner", maintain_order="left")
589
+ else:
590
+ from pm4py.algo.filtering.log.ltl import ltl_checker
591
+
592
+ parameters[ltl_checker.Parameters.POSITIVE] = retain
593
+ if retain:
594
+ cases = set()
595
+ else:
596
+ cases = set(id(trace) for trace in log)
597
+ for path in relations:
598
+ filt_log = ltl_checker.eventually_follows(
599
+ log, path, parameters=parameters
600
+ )
601
+ this_traces = set(id(trace) for trace in filt_log)
602
+ if retain:
603
+ cases = cases.union(this_traces)
604
+ else:
605
+ cases = cases.intersection(this_traces)
606
+ filtered_log = EventLog(
607
+ attributes=log.attributes,
608
+ extensions=log.extensions,
609
+ omni_present=log.omni_present,
610
+ classifiers=log.classifiers,
611
+ properties=log.properties,
612
+ )
613
+ for trace in log:
614
+ if id(trace) in cases:
615
+ filtered_log.append(trace)
616
+ return filtered_log
617
+
618
+
619
+ def filter_time_range(
620
+ log: Union[EventLog, pd.DataFrame],
621
+ dt1: str,
622
+ dt2: str,
623
+ mode: str = "events",
624
+ timestamp_key: str = "time:timestamp",
625
+ case_id_key: str = "case:concept:name",
626
+ ) -> Union[EventLog, pd.DataFrame]:
627
+ """
628
+ Filters a log based on a time interval.
629
+
630
+ :param log: Event log or Pandas DataFrame.
631
+ :param dt1: Left extreme of the interval.
632
+ :param dt2: Right extreme of the interval.
633
+ :param mode: Modality of filtering. Supported:
634
+ - 'events': keep events within timeframe.
635
+ - 'traces_contained': keep traces fully contained in timeframe.
636
+ - 'traces_intersecting': keep traces intersecting timeframe.
637
+ - 'traces_starting_in': keep traces whose first event is in timeframe.
638
+ - 'traces_starting_in_exclude': exclude traces whose first event is in timeframe.
639
+ - 'traces_completing_in': keep traces whose last event is in timeframe.
640
+ - 'traces_completing_in_exclude': exclude traces whose last event is in timeframe.
641
+ :param timestamp_key: Attribute to be used for the timestamp.
642
+ :param case_id_key: Attribute to be used as case identifier.
643
+ :return: Filtered event log or Pandas DataFrame.
644
+ """
645
+ __event_log_deprecation_warning(log)
646
+
647
+ properties = get_properties(
648
+ log, timestamp_key=timestamp_key, case_id_key=case_id_key
649
+ )
650
+
651
+ # Helper: compute "positive" flag from mode for the new variants
652
+ def _positive_from_mode(m: str) -> bool:
653
+ return not (m.endswith("_exclude"))
654
+
655
+ if _is_dataframe_like(log):
656
+ filtering_pkg = _get_dataframe_filtering_package(log)
657
+ timestamp_filter = filtering_pkg.timestamp.timestamp_filter
658
+
659
+ if mode == "events":
660
+ return timestamp_filter.apply_events(
661
+ log, dt1, dt2, parameters=properties
662
+ )
663
+ elif mode == "traces_contained":
664
+ return timestamp_filter.filter_traces_contained(
665
+ log, dt1, dt2, parameters=properties
666
+ )
667
+ elif mode == "traces_intersecting":
668
+ return timestamp_filter.filter_traces_intersecting(
669
+ log, dt1, dt2, parameters=properties
670
+ )
671
+ elif mode in ("traces_starting_in", "traces_starting_in_exclude"):
672
+ params = dict(properties)
673
+ params["positive"] = _positive_from_mode(mode)
674
+ return timestamp_filter.filter_traces_starting_in_timeframe(
675
+ log, dt1, dt2, parameters=params
676
+ )
677
+ elif mode in ("traces_completing_in", "traces_completing_in_exclude"):
678
+ params = dict(properties)
679
+ params["positive"] = _positive_from_mode(mode)
680
+ return timestamp_filter.filter_traces_completing_in_timeframe(
681
+ log, dt1, dt2, parameters=params
682
+ )
683
+ else:
684
+ if constants.SHOW_INTERNAL_WARNINGS:
685
+ warnings.warn(
686
+ f"Mode provided: {mode} is not recognized; original log returned!"
687
+ )
688
+ return log
689
+ else:
690
+ from pm4py.algo.filtering.log.timestamp import timestamp_filter
691
+
692
+ if mode == "events":
693
+ return timestamp_filter.apply_events(
694
+ log, dt1, dt2, parameters=properties
695
+ )
696
+ elif mode == "traces_contained":
697
+ return timestamp_filter.filter_traces_contained(
698
+ log, dt1, dt2, parameters=properties
699
+ )
700
+ elif mode == "traces_intersecting":
701
+ return timestamp_filter.filter_traces_intersecting(
702
+ log, dt1, dt2, parameters=properties
703
+ )
704
+ elif mode in ("traces_starting_in", "traces_starting_in_exclude"):
705
+ params = dict(properties)
706
+ params["positive"] = _positive_from_mode(mode)
707
+ return timestamp_filter.filter_traces_starting_in_timeframe(
708
+ log, dt1, dt2, parameters=params
709
+ )
710
+ elif mode in ("traces_completing_in", "traces_completing_in_exclude"):
711
+ params = dict(properties)
712
+ params["positive"] = _positive_from_mode(mode)
713
+ return timestamp_filter.filter_traces_completing_in_timeframe(
714
+ log, dt1, dt2, parameters=params
715
+ )
716
+ else:
717
+ if constants.SHOW_INTERNAL_WARNINGS:
718
+ warnings.warn(
719
+ f"Mode provided: {mode} is not recognized; original log returned!"
720
+ )
721
+ return log
722
+
723
+
724
+ def filter_between(
725
+ log: Union[EventLog, pd.DataFrame],
726
+ act1: Union[str, List[str]],
727
+ act2: Union[str, List[str]],
728
+ activity_key: str = "concept:name",
729
+ timestamp_key: str = "time:timestamp",
730
+ case_id_key: str = "case:concept:name",
731
+ ) -> Union[EventLog, pd.DataFrame]:
732
+ """
733
+ Finds all the sub-cases leading from an event with activity "act1" to an event with activity "act2" in the log,
734
+ and returns a log containing only them.
735
+
736
+ Example:
737
+
738
+ Log
739
+ A B C D E F
740
+ A B E F C
741
+ A B F C B C B E F C
742
+
743
+ act1 = B
744
+ act2 = C
745
+
746
+ Returned sub-cases:
747
+ B C (from the first case)
748
+ B E F C (from the second case)
749
+ B F C (from the third case)
750
+ B C (from the third case)
751
+ B E F C (from the third case)
752
+
753
+ :param log: Event log or Pandas DataFrame.
754
+ :param act1: Source activity or collection of activities.
755
+ :param act2: Target activity or collection of activities.
756
+ :param activity_key: Attribute to be used for the activity.
757
+ :param timestamp_key: Attribute to be used for the timestamp.
758
+ :param case_id_key: Attribute to be used as case identifier.
759
+ :return: Filtered event log or Pandas DataFrame.
760
+
761
+ .. code-block:: python3
762
+
763
+ import pm4py
764
+
765
+ filtered_dataframe = pm4py.filter_between(
766
+ dataframe,
767
+ 'A',
768
+ 'D',
769
+ activity_key='concept:name',
770
+ case_id_key='case:concept:name',
771
+ timestamp_key='time:timestamp'
772
+ )
773
+ """
774
+ __event_log_deprecation_warning(log)
775
+
776
+ parameters = get_properties(
777
+ log,
778
+ activity_key=activity_key,
779
+ timestamp_key=timestamp_key,
780
+ case_id_key=case_id_key,
781
+ )
782
+ if _is_dataframe_like(log):
783
+ check_pandas_dataframe_columns(
784
+ log,
785
+ activity_key=activity_key,
786
+ timestamp_key=timestamp_key,
787
+ case_id_key=case_id_key,
788
+ )
789
+ filtering_pkg = _get_dataframe_filtering_package(log)
790
+ between_filter = filtering_pkg.between.between_filter
791
+
792
+ return between_filter.apply(log, act1, act2, parameters=parameters)
793
+ else:
794
+ from pm4py.algo.filtering.log.between import between_filter
795
+
796
+ return between_filter.apply(log, act1, act2, parameters=parameters)
797
+
798
+
799
+ def filter_case_size(
800
+ log: Union[EventLog, pd.DataFrame],
801
+ min_size: int,
802
+ max_size: int,
803
+ case_id_key: str = "case:concept:name",
804
+ ) -> Union[EventLog, pd.DataFrame]:
805
+ """
806
+ Filters the event log, keeping cases that have a length (number of events) between min_size and max_size.
807
+
808
+ :param log: Event log or Pandas DataFrame.
809
+ :param min_size: Minimum allowed number of events.
810
+ :param max_size: Maximum allowed number of events.
811
+ :param case_id_key: Attribute to be used as case identifier.
812
+ :return: Filtered event log or Pandas DataFrame.
813
+
814
+ .. code-block:: python3
815
+
816
+ import pm4py
817
+
818
+ filtered_dataframe = pm4py.filter_case_size(
819
+ dataframe,
820
+ 5,
821
+ 10,
822
+ case_id_key='case:concept:name'
823
+ )
824
+ """
825
+ __event_log_deprecation_warning(log)
826
+
827
+ parameters = get_properties(log, case_id_key=case_id_key)
828
+ if _is_dataframe_like(log):
829
+ check_pandas_dataframe_columns(log, case_id_key=case_id_key)
830
+ filtering_pkg = _get_dataframe_filtering_package(log)
831
+ case_filter = filtering_pkg.cases.case_filter
832
+
833
+ case_id = (
834
+ parameters[constants.PARAMETER_CONSTANT_CASEID_KEY]
835
+ if constants.PARAMETER_CONSTANT_CASEID_KEY in parameters
836
+ else constants.CASE_CONCEPT_NAME
837
+ )
838
+ return case_filter.filter_on_case_size(
839
+ log, case_id, min_size, max_size
840
+ )
841
+ else:
842
+ from pm4py.algo.filtering.log.cases import case_filter
843
+
844
+ return case_filter.filter_on_case_size(log, min_size, max_size)
845
+
846
+
847
+ def filter_case_performance(
848
+ log: Union[EventLog, pd.DataFrame],
849
+ min_performance: float,
850
+ max_performance: float,
851
+ timestamp_key: str = "time:timestamp",
852
+ case_id_key: str = "case:concept:name",
853
+ ) -> Union[EventLog, pd.DataFrame]:
854
+ """
855
+ Filters the event log, keeping cases that have a duration (the timestamp of the last event minus the timestamp
856
+ of the first event) between min_performance and max_performance.
857
+
858
+ :param log: Event log or Pandas DataFrame.
859
+ :param min_performance: Minimum allowed case duration.
860
+ :param max_performance: Maximum allowed case duration.
861
+ :param timestamp_key: Attribute to be used for the timestamp.
862
+ :param case_id_key: Attribute to be used as case identifier.
863
+ :return: Filtered event log or Pandas DataFrame.
864
+
865
+ .. code-block:: python3
866
+
867
+ import pm4py
868
+
869
+ filtered_dataframe = pm4py.filter_case_performance(
870
+ dataframe,
871
+ 3600.0,
872
+ 86400.0,
873
+ timestamp_key='time:timestamp',
874
+ case_id_key='case:concept:name'
875
+ )
876
+ """
877
+ __event_log_deprecation_warning(log)
878
+
879
+ parameters = get_properties(
880
+ log, timestamp_key=timestamp_key, case_id_key=case_id_key
881
+ )
882
+ if _is_dataframe_like(log):
883
+ check_pandas_dataframe_columns(
884
+ log, timestamp_key=timestamp_key, case_id_key=case_id_key
885
+ )
886
+ filtering_pkg = _get_dataframe_filtering_package(log)
887
+ case_filter = filtering_pkg.cases.case_filter
888
+
889
+ return case_filter.filter_case_performance(
890
+ log, min_performance, max_performance, parameters=parameters
891
+ )
892
+ else:
893
+ from pm4py.algo.filtering.log.cases import case_filter
894
+
895
+ return case_filter.filter_case_performance(
896
+ log, min_performance, max_performance, parameters=parameters
897
+ )
898
+
899
+
900
+ def filter_activities_rework(
901
+ log: Union[EventLog, pd.DataFrame],
902
+ activity: str,
903
+ min_occurrences: int = 2,
904
+ activity_key: str = "concept:name",
905
+ timestamp_key: str = "time:timestamp",
906
+ case_id_key: str = "case:concept:name",
907
+ ) -> Union[EventLog, pd.DataFrame]:
908
+ """
909
+ Filters the event log, keeping cases where the specified activity occurs at least min_occurrences times.
910
+
911
+ :param log: Event log or Pandas DataFrame.
912
+ :param activity: Activity to consider.
913
+ :param min_occurrences: Minimum desired number of occurrences.
914
+ :param activity_key: Attribute to be used for the activity.
915
+ :param timestamp_key: Attribute to be used for the timestamp.
916
+ :param case_id_key: Attribute to be used as case identifier.
917
+ :return: Filtered event log or Pandas DataFrame.
918
+
919
+ .. code-block:: python3
920
+
921
+ import pm4py
922
+
923
+ filtered_dataframe = pm4py.filter_activities_rework(
924
+ dataframe,
925
+ 'Approve Order',
926
+ 2,
927
+ activity_key='concept:name',
928
+ timestamp_key='time:timestamp',
929
+ case_id_key='case:concept:name'
930
+ )
931
+ """
932
+ __event_log_deprecation_warning(log)
933
+
934
+ parameters = get_properties(
935
+ log,
936
+ activity_key=activity_key,
937
+ timestamp_key=timestamp_key,
938
+ case_id_key=case_id_key,
939
+ )
940
+ parameters["min_occurrences"] = min_occurrences
941
+ is_polars = is_polars_lazyframe(log)
942
+ if _is_dataframe_like(log):
943
+ check_pandas_dataframe_columns(
944
+ log,
945
+ activity_key=activity_key,
946
+ timestamp_key=timestamp_key,
947
+ case_id_key=case_id_key,
948
+ )
949
+ filtering_pkg = _get_dataframe_filtering_package(log)
950
+ rework_filter = filtering_pkg.rework.rework_filter
951
+
952
+ if is_polars:
953
+ if hasattr(rework_filter, "apply_activity_set"):
954
+ return rework_filter.apply_activity_set(
955
+ log, {activity}, parameters=parameters
956
+ )
957
+ return rework_filter.apply(log, parameters=parameters)
958
+
959
+ return rework_filter.apply(log, activity, parameters=parameters)
960
+ else:
961
+ from pm4py.algo.filtering.log.rework import rework_filter
962
+
963
+ return rework_filter.apply(log, activity, parameters=parameters)
964
+
965
+
966
+ def filter_paths_performance(
967
+ log: Union[EventLog, pd.DataFrame],
968
+ path: Tuple[str, str],
969
+ min_performance: float,
970
+ max_performance: float,
971
+ keep: bool = True,
972
+ activity_key: str = "concept:name",
973
+ timestamp_key: str = "time:timestamp",
974
+ case_id_key: str = "case:concept:name",
975
+ ) -> Union[EventLog, pd.DataFrame]:
976
+ """
977
+ Filters the event log based on the performance of specified paths.
978
+
979
+ - If keep=True, retains cases having the specified path (tuple of 2 activities) with a duration between min_performance and max_performance.
980
+ - If keep=False, discards cases having the specified path with a duration between min_performance and max_performance.
981
+
982
+ :param log: Event log or Pandas DataFrame.
983
+ :param path: Tuple of two activities (source_activity, target_activity).
984
+ :param min_performance: Minimum allowed performance of the path.
985
+ :param max_performance: Maximum allowed performance of the path.
986
+ :param keep: Boolean indicating whether to keep (if True) or discard (if False) the cases with the specified performance.
987
+ :param activity_key: Attribute to be used for the activity.
988
+ :param timestamp_key: Attribute to be used for the timestamp.
989
+ :param case_id_key: Attribute to be used as case identifier.
990
+ :return: Filtered event log or Pandas DataFrame.
991
+
992
+ .. code-block:: python3
993
+
994
+ import pm4py
995
+
996
+ filtered_dataframe = pm4py.filter_paths_performance(
997
+ dataframe,
998
+ ('A', 'D'),
999
+ 3600.0,
1000
+ 86400.0,
1001
+ activity_key='concept:name',
1002
+ timestamp_key='time:timestamp',
1003
+ case_id_key='case:concept:name'
1004
+ )
1005
+ """
1006
+ __event_log_deprecation_warning(log)
1007
+
1008
+ parameters = get_properties(
1009
+ log,
1010
+ activity_key=activity_key,
1011
+ timestamp_key=timestamp_key,
1012
+ case_id_key=case_id_key,
1013
+ )
1014
+ parameters["positive"] = keep
1015
+ parameters["min_performance"] = min_performance
1016
+ parameters["max_performance"] = max_performance
1017
+
1018
+ path = tuple(path)
1019
+ if _is_dataframe_like(log):
1020
+ check_pandas_dataframe_columns(
1021
+ log,
1022
+ activity_key=activity_key,
1023
+ timestamp_key=timestamp_key,
1024
+ case_id_key=case_id_key,
1025
+ )
1026
+ filtering_pkg = _get_dataframe_filtering_package(log)
1027
+ paths_filter = filtering_pkg.paths.paths_filter
1028
+
1029
+ return paths_filter.apply_performance(log, path, parameters=parameters)
1030
+ else:
1031
+ from pm4py.algo.filtering.log.paths import paths_filter
1032
+
1033
+ return paths_filter.apply_performance(log, path, parameters=parameters)
1034
+
1035
+
1036
+ def filter_variants_top_k(
1037
+ log: Union[EventLog, pd.DataFrame],
1038
+ k: int,
1039
+ activity_key: str = "concept:name",
1040
+ timestamp_key: str = "time:timestamp",
1041
+ case_id_key: str = "case:concept:name",
1042
+ ) -> Union[EventLog, pd.DataFrame]:
1043
+ """
1044
+ Keeps the top-k variants of the log.
1045
+
1046
+ :param log: Event log or Pandas DataFrame.
1047
+ :param k: Number of variants to keep.
1048
+ :param activity_key: Attribute to be used for the activity.
1049
+ :param timestamp_key: Attribute to be used for the timestamp.
1050
+ :param case_id_key: Attribute to be used as case identifier.
1051
+ :return: Filtered event log or Pandas DataFrame.
1052
+
1053
+ .. code-block:: python3
1054
+
1055
+ import pm4py
1056
+
1057
+ filtered_dataframe = pm4py.filter_variants_top_k(
1058
+ dataframe,
1059
+ 5,
1060
+ activity_key='concept:name',
1061
+ timestamp_key='time:timestamp',
1062
+ case_id_key='case:concept:name'
1063
+ )
1064
+ """
1065
+ __event_log_deprecation_warning(log)
1066
+
1067
+ parameters = get_properties(
1068
+ log,
1069
+ activity_key=activity_key,
1070
+ timestamp_key=timestamp_key,
1071
+ case_id_key=case_id_key,
1072
+ )
1073
+ if _is_dataframe_like(log):
1074
+ check_pandas_dataframe_columns(
1075
+ log,
1076
+ activity_key=activity_key,
1077
+ timestamp_key=timestamp_key,
1078
+ case_id_key=case_id_key,
1079
+ )
1080
+ filtering_pkg = _get_dataframe_filtering_package(log)
1081
+ variants_filter = filtering_pkg.variants.variants_filter
1082
+
1083
+ return variants_filter.filter_variants_top_k(
1084
+ log, k, parameters=parameters
1085
+ )
1086
+ else:
1087
+ from pm4py.algo.filtering.log.variants import variants_filter
1088
+
1089
+ return variants_filter.filter_variants_top_k(
1090
+ log, k, parameters=parameters
1091
+ )
1092
+
1093
+
1094
+ def filter_variants_by_coverage_percentage(
1095
+ log: Union[EventLog, pd.DataFrame],
1096
+ min_coverage_percentage: float,
1097
+ activity_key: str = "concept:name",
1098
+ timestamp_key: str = "time:timestamp",
1099
+ case_id_key: str = "case:concept:name",
1100
+ ) -> Union[EventLog, pd.DataFrame]:
1101
+ """
1102
+ Filters the variants of the log based on a coverage percentage.
1103
+ For example, if min_coverage_percentage=0.4 and the log has 1000 cases with:
1104
+ - 500 cases of variant 1,
1105
+ - 400 cases of variant 2,
1106
+ - 100 cases of variant 3,
1107
+ the filter keeps only the traces of variant 1 and variant 2.
1108
+
1109
+ :param log: Event log or Pandas DataFrame.
1110
+ :param min_coverage_percentage: Minimum allowed percentage of coverage.
1111
+ :param activity_key: Attribute to be used for the activity.
1112
+ :param timestamp_key: Attribute to be used for the timestamp.
1113
+ :param case_id_key: Attribute to be used as case identifier.
1114
+ :return: Filtered event log or Pandas DataFrame.
1115
+
1116
+ .. code-block:: python3
1117
+
1118
+ import pm4py
1119
+
1120
+ filtered_dataframe = pm4py.filter_variants_by_coverage_percentage(
1121
+ dataframe,
1122
+ 0.1,
1123
+ activity_key='concept:name',
1124
+ timestamp_key='time:timestamp',
1125
+ case_id_key='case:concept:name'
1126
+ )
1127
+ """
1128
+ __event_log_deprecation_warning(log)
1129
+
1130
+ parameters = get_properties(
1131
+ log,
1132
+ activity_key=activity_key,
1133
+ timestamp_key=timestamp_key,
1134
+ case_id_key=case_id_key,
1135
+ )
1136
+ if _is_dataframe_like(log):
1137
+ check_pandas_dataframe_columns(
1138
+ log,
1139
+ activity_key=activity_key,
1140
+ timestamp_key=timestamp_key,
1141
+ case_id_key=case_id_key,
1142
+ )
1143
+ filtering_pkg = _get_dataframe_filtering_package(log)
1144
+ variants_filter = filtering_pkg.variants.variants_filter
1145
+
1146
+ return variants_filter.filter_variants_by_coverage_percentage(
1147
+ log, min_coverage_percentage, parameters=parameters
1148
+ )
1149
+ else:
1150
+ from pm4py.algo.filtering.log.variants import variants_filter
1151
+
1152
+ return variants_filter.filter_variants_by_coverage_percentage(
1153
+ log, min_coverage_percentage, parameters=parameters
1154
+ )
1155
+
1156
+
1157
+ def filter_prefixes(
1158
+ log: Union[EventLog, pd.DataFrame],
1159
+ activity: str,
1160
+ strict: bool = True,
1161
+ first_or_last: str = "first",
1162
+ activity_key: str = "concept:name",
1163
+ timestamp_key: str = "time:timestamp",
1164
+ case_id_key: str = "case:concept:name",
1165
+ ) -> Union[EventLog, pd.DataFrame]:
1166
+ """
1167
+ Filters the log, keeping the prefixes leading up to a given activity.
1168
+ For example, for a log with traces:
1169
+ - A,B,C,D
1170
+ - A,B,Z,A,B,C,D
1171
+ - A,B,C,D,C,E,C,F
1172
+
1173
+ The prefixes to "C" are respectively:
1174
+ - A,B
1175
+ - A,B,Z,A,B
1176
+ - A,B
1177
+
1178
+ :param log: Event log or Pandas DataFrame.
1179
+ :param activity: Target activity for the filter.
1180
+ :param strict: Applies the filter strictly, cutting the occurrences of the selected activity.
1181
+ :param first_or_last: Decides if the first or last occurrence of an activity should be selected as the baseline for the filter.
1182
+ :param activity_key: Attribute to be used for the activity.
1183
+ :param timestamp_key: Attribute to be used for the timestamp.
1184
+ :param case_id_key: Attribute to be used as case identifier.
1185
+ :return: Filtered event log or Pandas DataFrame.
1186
+
1187
+ .. code-block:: python3
1188
+
1189
+ import pm4py
1190
+
1191
+ filtered_dataframe = pm4py.filter_prefixes(
1192
+ dataframe,
1193
+ 'Act. C',
1194
+ activity_key='concept:name',
1195
+ timestamp_key='time:timestamp',
1196
+ case_id_key='case:concept:name'
1197
+ )
1198
+ """
1199
+ __event_log_deprecation_warning(log)
1200
+
1201
+ parameters = get_properties(
1202
+ log,
1203
+ activity_key=activity_key,
1204
+ timestamp_key=timestamp_key,
1205
+ case_id_key=case_id_key,
1206
+ )
1207
+ parameters["strict"] = strict
1208
+ parameters["first_or_last"] = first_or_last
1209
+
1210
+ if _is_dataframe_like(log):
1211
+ check_pandas_dataframe_columns(
1212
+ log,
1213
+ activity_key=activity_key,
1214
+ timestamp_key=timestamp_key,
1215
+ case_id_key=case_id_key,
1216
+ )
1217
+ filtering_pkg = _get_dataframe_filtering_package(log)
1218
+ prefix_filter = filtering_pkg.prefixes.prefix_filter
1219
+ prefixes_arg = (
1220
+ _normalize_sequence_argument(activity)
1221
+ if is_polars_lazyframe(log)
1222
+ else activity
1223
+ )
1224
+
1225
+ return prefix_filter.apply(log, prefixes_arg, parameters=parameters)
1226
+ else:
1227
+ from pm4py.algo.filtering.log.prefixes import prefix_filter
1228
+
1229
+ return prefix_filter.apply(log, activity, parameters=parameters)
1230
+
1231
+
1232
+ def filter_suffixes(
1233
+ log: Union[EventLog, pd.DataFrame],
1234
+ activity: str,
1235
+ strict: bool = True,
1236
+ first_or_last: str = "first",
1237
+ activity_key: str = "concept:name",
1238
+ timestamp_key: str = "time:timestamp",
1239
+ case_id_key: str = "case:concept:name",
1240
+ ) -> Union[EventLog, pd.DataFrame]:
1241
+ """
1242
+ Filters the log, keeping the suffixes starting from a given activity.
1243
+ For example, for a log with traces:
1244
+ - A,B,C,D
1245
+ - A,B,Z,A,B,C,D
1246
+ - A,B,C,D,C,E,C,F
1247
+
1248
+ The suffixes from "C" are respectively:
1249
+ - D
1250
+ - D
1251
+ - D,C,E,C,F
1252
+
1253
+ :param log: Event log or Pandas DataFrame.
1254
+ :param activity: Target activity for the filter.
1255
+ :param strict: Applies the filter strictly, cutting the occurrences of the selected activity.
1256
+ :param first_or_last: Decides if the first or last occurrence of an activity should be selected as the baseline for the filter.
1257
+ :param activity_key: Attribute to be used for the activity.
1258
+ :param timestamp_key: Attribute to be used for the timestamp.
1259
+ :param case_id_key: Attribute to be used as case identifier.
1260
+ :return: Filtered event log or Pandas DataFrame.
1261
+
1262
+ .. code-block:: python3
1263
+
1264
+ import pm4py
1265
+
1266
+ filtered_dataframe = pm4py.filter_suffixes(
1267
+ dataframe,
1268
+ 'Act. C',
1269
+ activity_key='concept:name',
1270
+ timestamp_key='time:timestamp',
1271
+ case_id_key='case:concept:name'
1272
+ )
1273
+ """
1274
+ __event_log_deprecation_warning(log)
1275
+
1276
+ parameters = get_properties(
1277
+ log,
1278
+ activity_key=activity_key,
1279
+ timestamp_key=timestamp_key,
1280
+ case_id_key=case_id_key,
1281
+ )
1282
+ parameters["strict"] = strict
1283
+ parameters["first_or_last"] = first_or_last
1284
+
1285
+ if _is_dataframe_like(log):
1286
+ check_pandas_dataframe_columns(
1287
+ log,
1288
+ activity_key=activity_key,
1289
+ timestamp_key=timestamp_key,
1290
+ case_id_key=case_id_key,
1291
+ )
1292
+ filtering_pkg = _get_dataframe_filtering_package(log)
1293
+ suffix_filter = filtering_pkg.suffixes.suffix_filter
1294
+ suffixes_arg = (
1295
+ _normalize_sequence_argument(activity)
1296
+ if is_polars_lazyframe(log)
1297
+ else activity
1298
+ )
1299
+
1300
+ return suffix_filter.apply(log, suffixes_arg, parameters=parameters)
1301
+ else:
1302
+ from pm4py.algo.filtering.log.suffixes import suffix_filter
1303
+
1304
+ return suffix_filter.apply(log, activity, parameters=parameters)
1305
+
1306
+
1307
+ def filter_ocel_event_attribute(
1308
+ ocel: OCEL,
1309
+ attribute_key: str,
1310
+ attribute_values: Collection[Any],
1311
+ positive: bool = True,
1312
+ ) -> OCEL:
1313
+ """
1314
+ Filters the object-centric event log based on the provided event attribute values.
1315
+
1316
+ :param ocel: Object-centric event log.
1317
+ :param attribute_key: Attribute at the event level to filter.
1318
+ :param attribute_values: Collection of attribute values to keep or remove.
1319
+ :param positive: Determines whether the values should be kept (True) or removed (False).
1320
+ :return: Filtered OCEL.
1321
+
1322
+ .. code-block:: python3
1323
+
1324
+ import pm4py
1325
+
1326
+ filtered_ocel = pm4py.filter_ocel_event_attribute(
1327
+ ocel,
1328
+ 'ocel:activity',
1329
+ ['A', 'B', 'D']
1330
+ )
1331
+ """
1332
+ from pm4py.algo.filtering.ocel import event_attributes
1333
+
1334
+ return event_attributes.apply(
1335
+ ocel,
1336
+ attribute_values,
1337
+ parameters={
1338
+ event_attributes.Parameters.ATTRIBUTE_KEY: attribute_key,
1339
+ event_attributes.Parameters.POSITIVE: positive,
1340
+ },
1341
+ )
1342
+
1343
+
1344
+ def filter_ocel_object_attribute(
1345
+ ocel: OCEL,
1346
+ attribute_key: str,
1347
+ attribute_values: Collection[Any],
1348
+ positive: bool = True,
1349
+ ) -> OCEL:
1350
+ """
1351
+ Filters the object-centric event log based on the provided object attribute values.
1352
+
1353
+ :param ocel: Object-centric event log.
1354
+ :param attribute_key: Attribute at the object level to filter.
1355
+ :param attribute_values: Collection of attribute values to keep or remove.
1356
+ :param positive: Determines whether the values should be kept (True) or removed (False).
1357
+ :return: Filtered OCEL.
1358
+
1359
+ .. code-block:: python3
1360
+
1361
+ import pm4py
1362
+
1363
+ filtered_ocel = pm4py.filter_ocel_object_attribute(
1364
+ ocel,
1365
+ 'ocel:type',
1366
+ ['order']
1367
+ )
1368
+ """
1369
+ from pm4py.algo.filtering.ocel import object_attributes
1370
+
1371
+ return object_attributes.apply(
1372
+ ocel,
1373
+ attribute_values,
1374
+ parameters={
1375
+ object_attributes.Parameters.ATTRIBUTE_KEY: attribute_key,
1376
+ object_attributes.Parameters.POSITIVE: positive,
1377
+ },
1378
+ )
1379
+
1380
+
1381
+ def filter_ocel_object_types_allowed_activities(
1382
+ ocel: OCEL, correspondence_dict: Dict[str, Collection[str]]
1383
+ ) -> OCEL:
1384
+ """
1385
+ Filters an object-centric event log, keeping only the specified object types with the specified set of allowed activities.
1386
+
1387
+ :param ocel: Object-centric event log.
1388
+ :param correspondence_dict: Dictionary containing, for every object type of interest, a collection of allowed activities.
1389
+ Example: {"order": ["Create Order"], "element": ["Create Order", "Create Delivery"]}.
1390
+ :return: Filtered OCEL.
1391
+
1392
+ .. code-block:: python3
1393
+
1394
+ import pm4py
1395
+
1396
+ filtered_ocel = pm4py.filter_ocel_object_types_allowed_activities(
1397
+ ocel,
1398
+ {'order': ['create order', 'pay order'], 'item': ['create item', 'deliver item']}
1399
+ )
1400
+ """
1401
+ from pm4py.algo.filtering.ocel import activity_type_matching
1402
+
1403
+ return activity_type_matching.apply(ocel, correspondence_dict)
1404
+
1405
+
1406
+ def filter_ocel_object_per_type_count(
1407
+ ocel: OCEL, min_num_obj_type: Dict[str, int]
1408
+ ) -> OCEL:
1409
+ """
1410
+ Filters the events of the object-centric logs that are related to at
1411
+ least the specified number of objects per type.
1412
+
1413
+ Example::
1414
+
1415
+ pm4py.filter_object_per_type_count(ocel, {"order": 1, "element": 2})
1416
+
1417
+ Would keep the following events::
1418
+
1419
+ ocel:eid ocel:timestamp ocel:activity ocel:type:element ocel:type:order
1420
+ 0 e1 1980-01-01 Create Order [i4, i1, i3, i2] [o1]
1421
+ 1 e11 1981-01-01 Create Order [i6, i5] [o2]
1422
+ 2 e14 1981-01-04 Create Order [i8, i7] [o3]
1423
+
1424
+ :param ocel: Object-centric event log.
1425
+ :param min_num_obj_type: Minimum number of objects per type.
1426
+ :return: Filtered OCEL.
1427
+
1428
+ .. code-block:: python3
1429
+
1430
+ import pm4py
1431
+
1432
+ filtered_ocel = pm4py.filter_ocel_object_per_type_count(
1433
+ ocel,
1434
+ {'order': 1, 'element': 2}
1435
+ )
1436
+
1437
+ """
1438
+ from pm4py.algo.filtering.ocel import objects_ot_count
1439
+
1440
+ return objects_ot_count.apply(ocel, min_num_obj_type)
1441
+
1442
+
1443
+ def filter_ocel_start_events_per_object_type(
1444
+ ocel: OCEL, object_type: str
1445
+ ) -> OCEL:
1446
+ """
1447
+ Filters the events in which a new object of the given object type is spawned.
1448
+ For example, an event with activity "Create Order" might spawn new orders.
1449
+
1450
+ :param ocel: Object-centric event log.
1451
+ :param object_type: Object type to consider.
1452
+ :return: Filtered OCEL.
1453
+
1454
+ .. code-block:: python3
1455
+
1456
+ import pm4py
1457
+
1458
+ filtered_ocel = pm4py.filter_ocel_start_events_per_object_type(
1459
+ ocel,
1460
+ 'delivery'
1461
+ )
1462
+ """
1463
+ from pm4py.algo.filtering.ocel import ot_endpoints
1464
+
1465
+ return ot_endpoints.filter_start_events_per_object_type(ocel, object_type)
1466
+
1467
+
1468
+ def filter_ocel_end_events_per_object_type(
1469
+ ocel: OCEL, object_type: str
1470
+ ) -> OCEL:
1471
+ """
1472
+ Filters the events in which an object of the given object type terminates its lifecycle.
1473
+ For example, an event with activity "Pay Order" might terminate an order.
1474
+
1475
+ :param ocel: Object-centric event log.
1476
+ :param object_type: Object type to consider.
1477
+ :return: Filtered OCEL.
1478
+
1479
+ .. code-block:: python3
1480
+
1481
+ import pm4py
1482
+
1483
+ filtered_ocel = pm4py.filter_ocel_end_events_per_object_type(
1484
+ ocel,
1485
+ 'delivery'
1486
+ )
1487
+ """
1488
+ from pm4py.algo.filtering.ocel import ot_endpoints
1489
+
1490
+ return ot_endpoints.filter_end_events_per_object_type(ocel, object_type)
1491
+
1492
+
1493
+ def filter_ocel_events_timestamp(
1494
+ ocel: OCEL,
1495
+ min_timest: Union[datetime.datetime, str],
1496
+ max_timest: Union[datetime.datetime, str],
1497
+ timestamp_key: str = "ocel:timestamp",
1498
+ ) -> OCEL:
1499
+ """
1500
+ Filters the object-centric event log, keeping events within the provided timestamp range.
1501
+
1502
+ :param ocel: Object-centric event log.
1503
+ :param min_timest: Left extreme of the allowed timestamp interval (format: YYYY-mm-dd HH:MM:SS).
1504
+ :param max_timest: Right extreme of the allowed timestamp interval (format: YYYY-mm-dd HH:MM:SS).
1505
+ :param timestamp_key: The attribute to use as timestamp (default: ocel:timestamp).
1506
+ :return: Filtered OCEL.
1507
+
1508
+ .. code-block:: python3
1509
+
1510
+ import pm4py
1511
+
1512
+ filtered_ocel = pm4py.filter_ocel_events_timestamp(
1513
+ ocel,
1514
+ '1990-01-01 00:00:00',
1515
+ '2010-01-01 00:00:00'
1516
+ )
1517
+ """
1518
+ from pm4py.algo.filtering.ocel import event_attributes
1519
+
1520
+ return event_attributes.apply_timestamp(
1521
+ ocel,
1522
+ min_timest,
1523
+ max_timest,
1524
+ parameters={"pm4py:param:timestamp_key": timestamp_key},
1525
+ )
1526
+
1527
+
1528
+ def filter_four_eyes_principle(
1529
+ log: Union[EventLog, pd.DataFrame],
1530
+ activity1: str,
1531
+ activity2: str,
1532
+ activity_key: str = "concept:name",
1533
+ timestamp_key: str = "time:timestamp",
1534
+ case_id_key: str = "case:concept:name",
1535
+ resource_key: str = "org:resource",
1536
+ keep_violations: bool = False,
1537
+ ) -> Union[EventLog, pd.DataFrame]:
1538
+ """
1539
+ Filters out the cases of the log that violate the four-eyes principle on the provided activities.
1540
+
1541
+ :param log: Event log or Pandas DataFrame.
1542
+ :param activity1: First activity.
1543
+ :param activity2: Second activity.
1544
+ :param activity_key: Attribute to be used for the activity.
1545
+ :param timestamp_key: Attribute to be used for the timestamp.
1546
+ :param case_id_key: Attribute to be used as case identifier.
1547
+ :param resource_key: Attribute to be used as resource.
1548
+ :param keep_violations: Boolean indicating whether to discard (if False) or retain (if True) the violations.
1549
+ :return: Filtered event log or Pandas DataFrame.
1550
+
1551
+ .. code-block:: python3
1552
+
1553
+ import pm4py
1554
+
1555
+ filtered_dataframe = pm4py.filter_four_eyes_principle(
1556
+ dataframe,
1557
+ 'Act. A',
1558
+ 'Act. B',
1559
+ activity_key='concept:name',
1560
+ resource_key='org:resource',
1561
+ timestamp_key='time:timestamp',
1562
+ case_id_key='case:concept:name'
1563
+ )
1564
+ """
1565
+ __event_log_deprecation_warning(log)
1566
+
1567
+ properties = get_properties(
1568
+ log,
1569
+ activity_key=activity_key,
1570
+ timestamp_key=timestamp_key,
1571
+ case_id_key=case_id_key,
1572
+ resource_key=resource_key,
1573
+ )
1574
+ properties["positive"] = not keep_violations
1575
+
1576
+ if _is_dataframe_like(log):
1577
+ check_pandas_dataframe_columns(
1578
+ log,
1579
+ activity_key=activity_key,
1580
+ timestamp_key=timestamp_key,
1581
+ case_id_key=case_id_key,
1582
+ )
1583
+
1584
+ filtering_pkg = _get_dataframe_filtering_package(log)
1585
+ ltl_checker = filtering_pkg.ltl.ltl_checker
1586
+
1587
+ return ltl_checker.four_eyes_principle(
1588
+ log, activity1, activity2, parameters=properties
1589
+ )
1590
+ else:
1591
+ from pm4py.algo.filtering.log.ltl import ltl_checker
1592
+
1593
+ return ltl_checker.four_eyes_principle(
1594
+ log, activity1, activity2, parameters=properties
1595
+ )
1596
+
1597
+
1598
+ def filter_activity_done_different_resources(
1599
+ log: Union[EventLog, pd.DataFrame],
1600
+ activity: str,
1601
+ activity_key: str = "concept:name",
1602
+ timestamp_key: str = "time:timestamp",
1603
+ case_id_key: str = "case:concept:name",
1604
+ resource_key: str = "org:resource",
1605
+ keep_violations: bool = True,
1606
+ ) -> Union[EventLog, pd.DataFrame]:
1607
+ """
1608
+ Filters the cases where an activity is performed by different resources multiple times.
1609
+
1610
+ :param log: Event log or Pandas DataFrame.
1611
+ :param activity: Activity to consider.
1612
+ :param activity_key: Attribute to be used for the activity.
1613
+ :param timestamp_key: Attribute to be used for the timestamp.
1614
+ :param case_id_key: Attribute to be used as case identifier.
1615
+ :param resource_key: Attribute to be used as resource.
1616
+ :param keep_violations: Boolean indicating whether to discard (if False) or retain (if True) the violations.
1617
+ :return: Filtered event log or Pandas DataFrame.
1618
+
1619
+ .. code-block:: python3
1620
+
1621
+ import pm4py
1622
+
1623
+ filtered_dataframe = pm4py.filter_activity_done_different_resources(
1624
+ dataframe,
1625
+ 'Act. A',
1626
+ activity_key='concept:name',
1627
+ resource_key='org:resource',
1628
+ timestamp_key='time:timestamp',
1629
+ case_id_key='case:concept:name'
1630
+ )
1631
+ """
1632
+ __event_log_deprecation_warning(log)
1633
+
1634
+ properties = get_properties(
1635
+ log,
1636
+ activity_key=activity_key,
1637
+ timestamp_key=timestamp_key,
1638
+ case_id_key=case_id_key,
1639
+ resource_key=resource_key,
1640
+ )
1641
+ properties["positive"] = keep_violations
1642
+
1643
+ if _is_dataframe_like(log):
1644
+ check_pandas_dataframe_columns(
1645
+ log,
1646
+ activity_key=activity_key,
1647
+ timestamp_key=timestamp_key,
1648
+ case_id_key=case_id_key,
1649
+ )
1650
+
1651
+ filtering_pkg = _get_dataframe_filtering_package(log)
1652
+ ltl_checker = filtering_pkg.ltl.ltl_checker
1653
+
1654
+ return ltl_checker.attr_value_different_persons(
1655
+ log, activity, parameters=properties
1656
+ )
1657
+ else:
1658
+ from pm4py.algo.filtering.log.ltl import ltl_checker
1659
+
1660
+ return ltl_checker.attr_value_different_persons(
1661
+ log, activity, parameters=properties
1662
+ )
1663
+
1664
+
1665
+ def filter_trace_segments(
1666
+ log: Union[EventLog, pd.DataFrame],
1667
+ admitted_traces: List[List[str]],
1668
+ positive: bool = True,
1669
+ activity_key: str = "concept:name",
1670
+ timestamp_key: str = "time:timestamp",
1671
+ case_id_key: str = "case:concept:name",
1672
+ ) -> Union[EventLog, pd.DataFrame]:
1673
+ """
1674
+ Filters an event log based on a set of trace segments. A trace is a
1675
+ sequence of activities and "...".
1676
+
1677
+ where:
1678
+
1679
+ - "..." before an activity indicates that other activities can precede the given activity.
1680
+ - "..." after an activity indicates that other activities can follow the given activity.
1681
+
1682
+ Examples:
1683
+
1684
+ - pm4py.filter_trace_segments(log, [["A", "B"]]) retains only cases with the exact process variant A,B.
1685
+ - pm4py.filter_trace_segments(log, [["...", "A", "B"]]) retains only cases ending with activities A,B.
1686
+ - pm4py.filter_trace_segments(log, [["A", "B", "..."]]) retains only cases starting with activities A,B.
1687
+ - pm4py.filter_trace_segments(log, [["...", "A", "B", "C", "..."], ["...", "D", "E", "F", "..."]]) retains cases where:
1688
+ - At any point, there is A followed by B followed by C,
1689
+ - And at any other point, there is D followed by E followed by F.
1690
+
1691
+ :param log: Event log or Pandas DataFrame.
1692
+ :param admitted_traces: Collection of trace segments to admit based on the criteria above.
1693
+ :param positive: Boolean indicating whether to keep (if True) or discard (if False) the cases satisfying the filter.
1694
+ :param activity_key: Attribute to be used for the activity.
1695
+ :param timestamp_key: Attribute to be used for the timestamp.
1696
+ :param case_id_key: Attribute to be used as case identifier.
1697
+ :return: Filtered event log or Pandas DataFrame.
1698
+
1699
+ .. code-block:: python3
1700
+
1701
+ import pm4py
1702
+
1703
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
1704
+
1705
+ filtered_log = pm4py.filter_trace_segments(
1706
+ log,
1707
+ [["...", "check ticket", "decide", "reinitiate request", "..."]]
1708
+ )
1709
+ print(filtered_log)
1710
+
1711
+ """
1712
+ __event_log_deprecation_warning(log)
1713
+
1714
+ parameters = get_properties(
1715
+ log,
1716
+ activity_key=activity_key,
1717
+ timestamp_key=timestamp_key,
1718
+ case_id_key=case_id_key,
1719
+ )
1720
+ parameters["positive"] = positive
1721
+
1722
+ if _is_dataframe_like(log):
1723
+ check_pandas_dataframe_columns(
1724
+ log,
1725
+ activity_key=activity_key,
1726
+ timestamp_key=timestamp_key,
1727
+ case_id_key=case_id_key,
1728
+ )
1729
+ filtering_pkg = _get_dataframe_filtering_package(log)
1730
+ trace_filter = filtering_pkg.traces.trace_filter
1731
+
1732
+ return trace_filter.apply(log, admitted_traces, parameters=parameters)
1733
+ else:
1734
+ from pm4py.algo.filtering.log.traces import trace_filter
1735
+
1736
+ return trace_filter.apply(log, admitted_traces, parameters=parameters)
1737
+
1738
+
1739
+ def filter_ocel_object_types(
1740
+ ocel: OCEL,
1741
+ obj_types: Collection[str],
1742
+ positive: bool = True,
1743
+ level: int = 1,
1744
+ ) -> OCEL:
1745
+ """
1746
+ Filters the object types of an object-centric event log.
1747
+
1748
+ :param ocel: Object-centric event log.
1749
+ :param obj_types: Object types to keep or remove.
1750
+ :param positive: Boolean indicating whether to keep (True) or remove (False) the specified object types.
1751
+ :param level: Recursively expands the set of object identifiers until the specified level.
1752
+ :return: Filtered OCEL.
1753
+
1754
+ .. code-block:: python3
1755
+
1756
+ import pm4py
1757
+
1758
+ ocel = pm4py.read_ocel('log.jsonocel')
1759
+ filtered_ocel = pm4py.filter_ocel_object_types(
1760
+ ocel,
1761
+ ['order']
1762
+ )
1763
+ """
1764
+ from copy import copy
1765
+ from pm4py.objects.ocel.util import filtering_utils
1766
+
1767
+ if level == 1:
1768
+ filtered_ocel = copy(ocel)
1769
+ if positive:
1770
+ filtered_ocel.objects = filtered_ocel.objects[
1771
+ filtered_ocel.objects[filtered_ocel.object_type_column].isin(
1772
+ obj_types
1773
+ )
1774
+ ]
1775
+ else:
1776
+ filtered_ocel.objects = filtered_ocel.objects[
1777
+ ~filtered_ocel.objects[filtered_ocel.object_type_column].isin(
1778
+ obj_types
1779
+ )
1780
+ ]
1781
+ return filtering_utils.propagate_object_filtering(filtered_ocel)
1782
+ else:
1783
+ object_ids = pandas_utils.format_unique(
1784
+ ocel.objects[
1785
+ ocel.objects[ocel.object_type_column].isin(obj_types)
1786
+ ][ocel.object_id_column].unique()
1787
+ )
1788
+ return filter_ocel_objects(
1789
+ ocel, object_ids, level=level, positive=positive
1790
+ )
1791
+
1792
+
1793
+ def filter_ocel_objects(
1794
+ ocel: OCEL,
1795
+ object_identifiers: Collection[str],
1796
+ positive: bool = True,
1797
+ level: int = 1,
1798
+ ) -> OCEL:
1799
+ """
1800
+ Filters the object identifiers of an object-centric event log.
1801
+
1802
+ :param ocel: Object-centric event log.
1803
+ :param object_identifiers: Object identifiers to keep or remove.
1804
+ :param positive: Boolean indicating whether to keep (True) or remove (False) the specified object identifiers.
1805
+ :param level: Recursively expands the set of object identifiers until the specified level.
1806
+ :return: Filtered OCEL.
1807
+
1808
+ .. code-block:: python3
1809
+
1810
+ import pm4py
1811
+
1812
+ ocel = pm4py.read_ocel('log.jsonocel')
1813
+ filtered_ocel = pm4py.filter_ocel_objects(
1814
+ ocel,
1815
+ ['o1'],
1816
+ level=1
1817
+ )
1818
+ """
1819
+ object_identifiers = set(object_identifiers)
1820
+ if level > 1:
1821
+ ev_rel_obj = (
1822
+ ocel.relations.groupby(ocel.event_id_column)[ocel.object_id_column]
1823
+ .agg(list)
1824
+ .to_dict()
1825
+ )
1826
+ objects_ids = ocel.objects[ocel.object_id_column].to_numpy().tolist()
1827
+ graph = {o: set() for o in objects_ids}
1828
+ for ev in ev_rel_obj:
1829
+ rel_obj = ev_rel_obj[ev]
1830
+ for o1 in rel_obj:
1831
+ for o2 in rel_obj:
1832
+ if o1 != o2:
1833
+ graph[o1].add(o2)
1834
+ while level > 1:
1835
+ curr = list(object_identifiers)
1836
+ for el in curr:
1837
+ for el2 in graph[el]:
1838
+ object_identifiers.add(el2)
1839
+ level = level - 1
1840
+ from copy import copy
1841
+ from pm4py.objects.ocel.util import filtering_utils
1842
+
1843
+ filtered_ocel = copy(ocel)
1844
+ if positive:
1845
+ filtered_ocel.objects = filtered_ocel.objects[
1846
+ filtered_ocel.objects[ocel.object_id_column].isin(
1847
+ object_identifiers
1848
+ )
1849
+ ]
1850
+ else:
1851
+ filtered_ocel.objects = filtered_ocel.objects[
1852
+ ~filtered_ocel.objects[ocel.object_id_column].isin(
1853
+ object_identifiers
1854
+ )
1855
+ ]
1856
+ filtered_ocel = filtering_utils.propagate_object_filtering(filtered_ocel)
1857
+ return filtered_ocel
1858
+
1859
+ def filter_ocel_events(
1860
+ ocel: OCEL, event_identifiers: Collection[str], positive: bool = True
1861
+ ) -> OCEL:
1862
+ """
1863
+ Filters the event identifiers of an object-centric event log.
1864
+
1865
+ :param ocel: Object-centric event log.
1866
+ :param event_identifiers: Event identifiers to keep or remove.
1867
+ :param positive: Boolean indicating whether to keep (True) or remove (False) the specified event identifiers.
1868
+ :return: Filtered OCEL.
1869
+
1870
+ .. code-block:: python3
1871
+
1872
+ import pm4py
1873
+
1874
+ ocel = pm4py.read_ocel('log.jsonocel')
1875
+ filtered_ocel = pm4py.filter_ocel_events(
1876
+ ocel,
1877
+ ['e1']
1878
+ )
1879
+ """
1880
+ from copy import copy
1881
+ from pm4py.objects.ocel.util import filtering_utils
1882
+
1883
+ filtered_ocel = copy(ocel)
1884
+ if positive:
1885
+ filtered_ocel.events = filtered_ocel.events[
1886
+ filtered_ocel.events[ocel.event_id_column].isin(event_identifiers)
1887
+ ]
1888
+ else:
1889
+ filtered_ocel.events = filtered_ocel.events[
1890
+ ~filtered_ocel.events[ocel.event_id_column].isin(event_identifiers)
1891
+ ]
1892
+ return filtering_utils.propagate_event_filtering(filtered_ocel)
1893
+
1894
+
1895
+ def filter_ocel_activities_connected_object_type(
1896
+ ocel: OCEL, object_type: str
1897
+ ) -> OCEL:
1898
+ """
1899
+ Filter an OCEL on the set of activities executed on objects of the given object type.
1900
+
1901
+ :param ocel: object-centric event log
1902
+ :param object_type: object type
1903
+ :rtype: ``OCEL``
1904
+
1905
+ .. code-block:: python3
1906
+
1907
+ import pm4py
1908
+
1909
+ ocel = pm4py.read_ocel2("tests/input_data/ocel/ocel20_example.xmlocel")
1910
+ filtered_ocel = pm4py.filter_ocel_activities_connected_object_type(ocel, "Purchase Order")
1911
+ print(filtered_ocel)
1912
+ """
1913
+ from copy import copy
1914
+ from pm4py.objects.ocel.util import filtering_utils
1915
+
1916
+ relations = ocel.relations[
1917
+ ocel.relations[ocel.object_type_column] == object_type
1918
+ ]
1919
+ activities = relations[ocel.event_activity].unique()
1920
+ filtered_ocel = copy(ocel)
1921
+ filtered_ocel.relations = filtered_ocel.relations[
1922
+ filtered_ocel.relations[ocel.event_activity].isin(activities)
1923
+ ]
1924
+
1925
+ return filtering_utils.propagate_relations_filtering(filtered_ocel)
1926
+
1927
+
1928
+ def filter_ocel_cc_object(
1929
+ ocel: OCEL,
1930
+ object_id: str,
1931
+ conn_comp: Optional[List[List[str]]] = None,
1932
+ return_conn_comp: bool = False,
1933
+ ) -> Union[OCEL, Tuple[OCEL, List[List[str]]]]:
1934
+ """
1935
+ Returns the connected component of the object-centric event log to which the specified object belongs.
1936
+
1937
+ :param ocel: Object-centric event log.
1938
+ :param object_id: Object identifier.
1939
+ :param conn_comp: (Optional) Precomputed connected components of the OCEL objects.
1940
+ :param return_conn_comp: If True, returns the filtered OCEL along with the computed connected components.
1941
+ :return: Filtered OCEL, optionally with the list of connected components.
1942
+
1943
+ .. code-block:: python3
1944
+
1945
+ import pm4py
1946
+
1947
+ ocel = pm4py.read_ocel('log.jsonocel')
1948
+ filtered_ocel = pm4py.filter_ocel_cc_object(
1949
+ ocel,
1950
+ 'order1'
1951
+ )
1952
+ """
1953
+ if conn_comp is None:
1954
+ from pm4py.algo.transformation.ocel.graphs import (
1955
+ object_interaction_graph,
1956
+ )
1957
+
1958
+ g0 = object_interaction_graph.apply(ocel)
1959
+ g = nx_utils.Graph()
1960
+
1961
+ for edge in g0:
1962
+ g.add_edge(edge[0], edge[1])
1963
+
1964
+ conn_comp = list(nx_utils.connected_components(g))
1965
+
1966
+ for cc in conn_comp:
1967
+ if object_id in cc:
1968
+ if return_conn_comp:
1969
+ return filter_ocel_objects(ocel, cc), conn_comp
1970
+ else:
1971
+ return filter_ocel_objects(ocel, cc)
1972
+
1973
+ if return_conn_comp:
1974
+ return filter_ocel_objects(ocel, [object_id]), conn_comp
1975
+ else:
1976
+ return filter_ocel_objects(ocel, [object_id])
1977
+
1978
+
1979
+ def filter_ocel_cc_length(
1980
+ ocel: OCEL, min_cc_length: int, max_cc_length: int
1981
+ ) -> OCEL:
1982
+ """
1983
+ Keeps only the objects in an OCEL belonging to a connected component with a length
1984
+ falling within the specified range.
1985
+
1986
+ Reference:
1987
+ Adams, Jan Niklas, et al. "Defining cases and variants for object-centric event data."
1988
+ 2022 4th International Conference on Process Mining (ICPM). IEEE, 2022.
1989
+
1990
+ :param ocel: Object-centric event log.
1991
+ :param min_cc_length: Minimum allowed length for the connected component.
1992
+ :param max_cc_length: Maximum allowed length for the connected component.
1993
+ :return: Filtered OCEL.
1994
+
1995
+ .. code-block:: python3
1996
+
1997
+ import pm4py
1998
+
1999
+ filtered_ocel = pm4py.filter_ocel_cc_length(
2000
+ ocel,
2001
+ 2,
2002
+ 10
2003
+ )
2004
+ """
2005
+ from pm4py.algo.transformation.ocel.graphs import object_interaction_graph
2006
+
2007
+ g0 = object_interaction_graph.apply(ocel)
2008
+ g = nx_utils.Graph()
2009
+
2010
+ for edge in g0:
2011
+ g.add_edge(edge[0], edge[1])
2012
+
2013
+ conn_comp = list(nx_utils.connected_components(g))
2014
+ conn_comp = [
2015
+ x for x in conn_comp if min_cc_length <= len(x) <= max_cc_length
2016
+ ]
2017
+ objs = [y for x in conn_comp for y in x]
2018
+
2019
+ return filter_ocel_objects(ocel, objs)
2020
+
2021
+
2022
+ def filter_ocel_cc_otype(
2023
+ ocel: OCEL, otype: str, positive: bool = True
2024
+ ) -> OCEL:
2025
+ """
2026
+ Filters the objects belonging to connected components that have at least one object of the specified type.
2027
+
2028
+ Reference:
2029
+ Adams, Jan Niklas, et al. "Defining cases and variants for object-centric event data."
2030
+ 2022 4th International Conference on Process Mining (ICPM). IEEE, 2022.
2031
+
2032
+ :param ocel: Object-centric event log.
2033
+ :param otype: Object type to consider.
2034
+ :param positive: Boolean indicating whether to keep (True) or discard (False) the objects in these components.
2035
+ :return: Filtered OCEL.
2036
+
2037
+ .. code-block:: python3
2038
+
2039
+ import pm4py
2040
+
2041
+ ocel = pm4py.read_ocel('log.jsonocel')
2042
+ filtered_ocel = pm4py.filter_ocel_cc_otype(
2043
+ ocel,
2044
+ 'order'
2045
+ )
2046
+ """
2047
+ if positive:
2048
+ objs = set(
2049
+ ocel.objects[ocel.objects[ocel.object_type_column] == otype][
2050
+ ocel.object_id_column
2051
+ ]
2052
+ )
2053
+ else:
2054
+ objs = set(
2055
+ ocel.objects[~(ocel.objects[ocel.object_type_column] == otype)][
2056
+ ocel.object_id_column
2057
+ ]
2058
+ )
2059
+
2060
+ from pm4py.algo.transformation.ocel.graphs import object_interaction_graph
2061
+
2062
+ g0 = object_interaction_graph.apply(ocel)
2063
+ g = nx_utils.Graph()
2064
+
2065
+ for edge in g0:
2066
+ g.add_edge(edge[0], edge[1])
2067
+
2068
+ conn_comp = list(nx_utils.connected_components(g))
2069
+ conn_comp = [x for x in conn_comp if len(set(x).intersection(objs)) > 0]
2070
+
2071
+ objs = [y for x in conn_comp for y in x]
2072
+
2073
+ return filter_ocel_objects(ocel, objs)
2074
+
2075
+
2076
+ def filter_ocel_cc_activity(ocel: OCEL, activity: str) -> OCEL:
2077
+ """
2078
+ Filters the objects belonging to connected components that include at least one event with the specified activity.
2079
+
2080
+ Reference:
2081
+ Adams, Jan Niklas, et al. "Defining cases and variants for object-centric event data."
2082
+ 2022 4th International Conference on Process Mining (ICPM). IEEE, 2022.
2083
+
2084
+ :param ocel: Object-centric event log.
2085
+ :param activity: Activity to consider.
2086
+ :return: Filtered OCEL.
2087
+
2088
+ .. code-block:: python3
2089
+
2090
+ import pm4py
2091
+
2092
+ ocel = pm4py.read_ocel('log.jsonocel')
2093
+ filtered_ocel = pm4py.filter_ocel_cc_activity(
2094
+ ocel,
2095
+ 'Create Order'
2096
+ )
2097
+ """
2098
+ evs = (
2099
+ ocel.events[ocel.events[ocel.event_activity] == activity][
2100
+ ocel.event_id_column
2101
+ ]
2102
+ .to_numpy()
2103
+ .tolist()
2104
+ )
2105
+ objs = pandas_utils.format_unique(
2106
+ ocel.relations[ocel.relations[ocel.event_id_column].isin(evs)][
2107
+ ocel.object_id_column
2108
+ ].unique()
2109
+ )
2110
+
2111
+ from pm4py.algo.transformation.ocel.graphs import object_interaction_graph
2112
+
2113
+ g0 = object_interaction_graph.apply(ocel)
2114
+ g = nx_utils.Graph()
2115
+
2116
+ for edge in g0:
2117
+ g.add_edge(edge[0], edge[1])
2118
+
2119
+ conn_comp = list(nx_utils.connected_components(g))
2120
+ conn_comp = [x for x in conn_comp if len(set(x).intersection(objs)) > 0]
2121
+
2122
+ objs = [y for x in conn_comp for y in x]
2123
+
2124
+ return filter_ocel_objects(ocel, objs)
2125
+
2126
+
2127
+ def filter_dfg_activities_percentage(
2128
+ dfg: Dict[Tuple[str, str], int],
2129
+ start_activities: Dict[str, int],
2130
+ end_activities: Dict[str, int],
2131
+ percentage: float = 0.2,
2132
+ ) -> Tuple[Dict[Tuple[str, str], int], Dict[str, int], Dict[str, int]]:
2133
+ """
2134
+ Filters the DFG on the provided percentage of activities.
2135
+
2136
+ :param dfg: frequency directly-follows graph
2137
+ :param start_activities: dictionary of the start activities
2138
+ :param end_activities: dictionary of the end activities
2139
+ :param percentage: percentage of activities to keep
2140
+
2141
+ .. code-block:: python3
2142
+
2143
+ import pm4py
2144
+
2145
+ log = pm4py.read_xes('tests/input_data/receipt.xes')
2146
+ dfg, sa, ea = pm4py.discover_dfg(log)
2147
+ dfg, sa, ea = pm4py.filter_dfg_activities_percentage(dfg, sa, ea, percentage=0.2)
2148
+ pm4py.view_dfg(dfg, sa, ea, format='svg')
2149
+ """
2150
+ activities_entering_arcs = Counter()
2151
+ activities_exiting_arcs = Counter()
2152
+ all_activities = set()
2153
+ for arc, count in dfg.items():
2154
+ activities_entering_arcs[arc[0]] += count
2155
+ activities_exiting_arcs[arc[1]] += count
2156
+ all_activities.add(arc[0])
2157
+ all_activities.add(arc[1])
2158
+ activities_frequency = {
2159
+ a: max(activities_entering_arcs[a], activities_exiting_arcs[a])
2160
+ for a in all_activities
2161
+ }
2162
+
2163
+ from pm4py.algo.filtering.dfg.dfg_filtering import (
2164
+ filter_dfg_on_activities_percentage,
2165
+ )
2166
+
2167
+ dfg, start_activities, end_activities, activities_frequency = (
2168
+ filter_dfg_on_activities_percentage(
2169
+ dfg,
2170
+ start_activities,
2171
+ end_activities,
2172
+ activities_frequency,
2173
+ percentage=percentage,
2174
+ )
2175
+ )
2176
+
2177
+ return dfg, start_activities, end_activities
2178
+
2179
+
2180
+ def filter_dfg_paths_percentage(
2181
+ dfg: Dict[Tuple[str, str], int],
2182
+ start_activities: Dict[str, int],
2183
+ end_activities: Dict[str, int],
2184
+ percentage: float = 0.2,
2185
+ ) -> Tuple[Dict[Tuple[str, str], int], Dict[str, int], Dict[str, int]]:
2186
+ """
2187
+ Filters the DFG on the provided percentage of paths.
2188
+
2189
+ :param dfg: frequency directly-follows graph
2190
+ :param start_activities: dictionary of the start activities
2191
+ :param end_activities: dictionary of the end activities
2192
+ :param percentage: percentage of paths to keep
2193
+
2194
+ .. code-block:: python3
2195
+
2196
+ import pm4py
2197
+
2198
+ log = pm4py.read_xes('tests/input_data/receipt.xes')
2199
+ dfg, sa, ea = pm4py.discover_dfg(log)
2200
+ dfg, sa, ea = pm4py.filter_dfg_paths_percentage(dfg, sa, ea, percentage=0.2)
2201
+ pm4py.view_dfg(dfg, sa, ea, format='svg')
2202
+ """
2203
+ activities_entering_arcs = Counter()
2204
+ activities_exiting_arcs = Counter()
2205
+ all_activities = set()
2206
+ for arc, count in dfg.items():
2207
+ activities_entering_arcs[arc[0]] += count
2208
+ activities_exiting_arcs[arc[1]] += count
2209
+ all_activities.add(arc[0])
2210
+ all_activities.add(arc[1])
2211
+ activities_frequency = {
2212
+ a: max(activities_entering_arcs[a], activities_exiting_arcs[a])
2213
+ for a in all_activities
2214
+ }
2215
+
2216
+ from pm4py.algo.filtering.dfg.dfg_filtering import (
2217
+ filter_dfg_on_paths_percentage,
2218
+ )
2219
+
2220
+ dfg, start_activities, end_activities, activities_frequency = (
2221
+ filter_dfg_on_paths_percentage(
2222
+ dfg,
2223
+ start_activities,
2224
+ end_activities,
2225
+ activities_frequency,
2226
+ percentage=percentage,
2227
+ )
2228
+ )
2229
+
2230
+ return dfg, start_activities, end_activities
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/hof.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ __doc__ = """
23
+ """
24
+
25
+ import warnings
26
+ from pm4py.util import constants
27
+ from typing import Callable, Any, Union
28
+
29
+ from pm4py.objects.log import obj as log_inst
30
+ from pm4py.utils import __event_log_deprecation_warning
31
+ from pm4py.util import deprecation
32
+
33
+
34
+ @deprecation.deprecated(
35
+ deprecated_in="2.3.0",
36
+ removed_in="3.0.0",
37
+ details="the EventLog class will be removed in a future release.",
38
+ )
39
+ def filter_log(
40
+ f: Callable[[Any], bool], log: log_inst.EventLog
41
+ ) -> Union[log_inst.EventLog, log_inst.EventStream]:
42
+ """
43
+ Filters the log according to a given (lambda) function.
44
+
45
+ :param f: function that specifies the filter criterion, may be a lambda
46
+ :param log: event log; either EventLog or EventStream Object
47
+ :rtype: ``Union[log_inst.EventLog, log_inst.EventStream]``
48
+ """
49
+ __event_log_deprecation_warning(log)
50
+
51
+ if isinstance(log, log_inst.EventLog):
52
+ return log_inst.EventLog(
53
+ list(filter(f, log)),
54
+ attributes=log.attributes,
55
+ classifiers=log.classifiers,
56
+ omni_present=log.omni_present,
57
+ extensions=log.extensions,
58
+ properties=log.properties,
59
+ )
60
+ elif isinstance(log, log_inst.EventStream):
61
+ return log_inst.EventStream(
62
+ list(filter(f, log)),
63
+ attributes=log.attributes,
64
+ classifiers=log.classifiers,
65
+ omni_present=log.omni_present,
66
+ extensions=log.extensions,
67
+ properties=log.properties,
68
+ )
69
+ else:
70
+ if constants.SHOW_INTERNAL_WARNINGS:
71
+ warnings.warn(
72
+ "input log object not of appropriate type, filter() not applied"
73
+ )
74
+ return log
75
+
76
+
77
+ def filter_trace(
78
+ f: Callable[[Any], bool], trace: log_inst.Trace
79
+ ) -> log_inst.Trace:
80
+ """
81
+ Filters the trace according to a given (lambda) function.
82
+
83
+ :param f: function that specifies the filter criterion, may be a lambda
84
+ :param trace: trace; PM4Py trace object
85
+ :rtype: ``log_inst.Trace``
86
+ """
87
+ __event_log_deprecation_warning(trace)
88
+
89
+ if isinstance(trace, log_inst.Trace):
90
+ return log_inst.Trace(
91
+ list(filter(f, trace)), attributes=trace.attributes
92
+ )
93
+ else:
94
+ if constants.SHOW_INTERNAL_WARNINGS:
95
+ warnings.warn(
96
+ "input trace object is not of the appropriate type, filter() not applied"
97
+ )
98
+ return trace
99
+
100
+
101
+ @deprecation.deprecated(
102
+ deprecated_in="2.3.0",
103
+ removed_in="3.0.0",
104
+ details="the EventLog class will be removed in a future release.",
105
+ )
106
+ def sort_log(
107
+ log: log_inst.EventLog, key, reverse: bool = False
108
+ ) -> Union[log_inst.EventLog, log_inst.EventStream]:
109
+ """
110
+ Sorts the event log according to a given key.
111
+
112
+ :param log: event log object; either EventLog or EventStream
113
+ :param key: sorting key
114
+ :param reverse: indicates whether sorting should be reversed or not
115
+ :rtype: ``Union[log_inst.EventLog, log_inst.EventStream]``
116
+ """
117
+ __event_log_deprecation_warning(log)
118
+
119
+ if isinstance(log, log_inst.EventLog):
120
+ return log_inst.EventLog(
121
+ sorted(log, key=key, reverse=reverse),
122
+ attributes=log.attributes,
123
+ classifiers=log.classifiers,
124
+ omni_present=log.omni_present,
125
+ extensions=log.extensions,
126
+ properties=log.properties,
127
+ )
128
+ elif isinstance(log, log_inst.EventStream):
129
+ return log_inst.EventStream(
130
+ sorted(log, key=key, reverse=reverse),
131
+ attributes=log.attributes,
132
+ classifiers=log.classifiers,
133
+ omni_present=log.omni_present,
134
+ extensions=log.extensions,
135
+ properties=log.properties,
136
+ )
137
+ else:
138
+ if constants.SHOW_INTERNAL_WARNINGS:
139
+ warnings.warn(
140
+ "input log object not of appropriate type, sorted() not applied"
141
+ )
142
+ return log
143
+
144
+
145
+ @deprecation.deprecated(
146
+ deprecated_in="2.3.0",
147
+ removed_in="3.0.0",
148
+ details="the EventLog class will be removed in a future release.",
149
+ )
150
+ def sort_trace(
151
+ trace: log_inst.Trace, key, reverse: bool = False
152
+ ) -> log_inst.Trace:
153
+ """
154
+ Sorts the events in a trace according to a given key.
155
+
156
+ :param trace: input trace
157
+ :param key: sorting key
158
+ :param reverse: indicates whether sorting should be reversed (default False)
159
+ :rtype: ``log_inst.Trace``
160
+ """
161
+ __event_log_deprecation_warning(trace)
162
+
163
+ if isinstance(trace, log_inst.Trace):
164
+ return log_inst.Trace(sorted(trace, key=key, reverse=reverse))
165
+ else:
166
+ if constants.SHOW_INTERNAL_WARNINGS:
167
+ warnings.warn(
168
+ "input trace object not of appropriate type, sorted() not applied"
169
+ )
170
+ return trace
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/llm.py ADDED
@@ -0,0 +1,971 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+
23
+ import pandas as pd
24
+ from pm4py.objects.log.obj import EventLog, EventStream, Trace
25
+ from typing import Union, Optional, Dict, Tuple, List, Any
26
+ from pm4py.utils import get_properties, constants, check_is_pandas_dataframe
27
+ from pm4py.utils import __event_log_deprecation_warning
28
+ from pm4py.objects.ocel.obj import OCEL
29
+ from tempfile import NamedTemporaryFile
30
+ from copy import copy
31
+ import re
32
+ from pm4py.objects.petri_net.obj import PetriNet, Marking
33
+
34
+
35
+ def openai_query(
36
+ prompt: str,
37
+ api_key: Optional[str] = None,
38
+ openai_model: Optional[str] = None,
39
+ api_url: Optional[str] = None,
40
+ extra_payload: Optional[Dict[Any, Any]] = None,
41
+ **kwargs
42
+ ) -> str:
43
+ r"""
44
+ Executes the provided prompt, obtaining the answer from the OpenAI APIs.
45
+
46
+ :param prompt: The prompt to be executed.
47
+ :param api_key: (Optional) OpenAI API key.
48
+ :param openai_model: (Optional) OpenAI model to be used (default: "gpt-3.5-turbo").
49
+ :param api_url: (Optional) OpenAI API URL.
50
+ :param extra_payload: (Optional) Additional payload fields merged into the request body.
51
+ :param \**kwargs: Additional parameters to pass to the OpenAI API.
52
+ :return: The response from the OpenAI API as a string.
53
+
54
+ .. code-block:: python3
55
+
56
+ import pm4py
57
+
58
+ resp = pm4py.llm.openai_query('What is the result of 3+3?', api_key="sk-382393", openai_model="gpt-3.5-turbo")
59
+ print(resp)
60
+ """
61
+ parameters = copy(kwargs) if kwargs is not None else {}
62
+ if api_url is not None:
63
+ parameters["api_url"] = api_url
64
+ if api_key is not None:
65
+ parameters["api_key"] = api_key
66
+ if openai_model is not None:
67
+ parameters["openai_model"] = openai_model
68
+ if extra_payload is not None:
69
+ parameters["extra_payload"] = extra_payload
70
+
71
+ from pm4py.algo.querying.llm.connectors import openai as perform_query
72
+
73
+ return perform_query.apply(prompt, parameters=parameters)
74
+
75
+
76
+ def google_query(
77
+ prompt: str,
78
+ api_key: Optional[str] = None,
79
+ model: Optional[str] = None,
80
+ extra_payload: Optional[Dict[Any, Any]] = None,
81
+ **kwargs
82
+ ) -> str:
83
+ """
84
+ Executes the provided prompt, obtaining the answer from the Google APIs.
85
+
86
+ :param prompt: prompt that should be executed
87
+ :param api_key: API key
88
+ :param model: Model to be used (default: gemini-1.5-flash-002)
89
+ :param extra_payload: (Optional) Additional payload fields merged into the request body.
90
+ :rtype: ``str``
91
+
92
+ .. code-block:: python3
93
+
94
+ import pm4py
95
+
96
+ resp = pm4py.llm.google_query('what is the result of 3+3?', api_key="sk-382393", model="gemini-1.5-flash-002")
97
+ print(resp)
98
+ """
99
+ parameters = copy(kwargs) if kwargs is not None else {}
100
+ if api_key is not None:
101
+ parameters["api_key"] = api_key
102
+ if model is not None:
103
+ parameters["google_model"] = model
104
+ if extra_payload is not None:
105
+ parameters["extra_payload"] = extra_payload
106
+
107
+ from pm4py.algo.querying.llm.connectors import google as perform_query
108
+
109
+ return perform_query.apply(prompt, parameters=parameters)
110
+
111
+
112
+ def anthropic_query(
113
+ prompt: str,
114
+ api_key: Optional[str] = None,
115
+ model: Optional[str] = None,
116
+ extra_payload: Optional[Dict[Any, Any]] = None,
117
+ **kwargs
118
+ ) -> str:
119
+ """
120
+ Executes the provided prompt, obtaining the answer from the Google APIs.
121
+
122
+ :param prompt: prompt that should be executed
123
+ :param api_key: API key
124
+ :param model: Model to be used (default: claude-3-5-sonnet-20241022)
125
+ :param extra_payload: (Optional) Additional payload fields merged into the request body.
126
+ :rtype: ``str``
127
+
128
+ .. code-block:: python3
129
+
130
+ import pm4py
131
+
132
+ resp = pm4py.llm.anthropic_query('what is the result of 3+3?', api_key="sk-382393", model="claude-3-5-sonnet-20241022")
133
+ print(resp)
134
+ """
135
+ parameters = copy(kwargs) if kwargs is not None else {}
136
+ if api_key is not None:
137
+ parameters["api_key"] = api_key
138
+ if model is not None:
139
+ parameters["anthropic_model"] = model
140
+ if extra_payload is not None:
141
+ parameters["extra_payload"] = extra_payload
142
+
143
+ from pm4py.algo.querying.llm.connectors import anthropic as perform_query
144
+
145
+ return perform_query.apply(prompt, parameters=parameters)
146
+
147
+
148
+ def abstract_dfg(
149
+ log_obj: Union[pd.DataFrame, EventLog, EventStream],
150
+ max_len: int = constants.OPENAI_MAX_LEN,
151
+ include_performance: bool = True,
152
+ relative_frequency: bool = False,
153
+ response_header: bool = True,
154
+ primary_performance_aggregation: str = "mean",
155
+ secondary_performance_aggregation: Optional[str] = None,
156
+ activity_key: str = "concept:name",
157
+ timestamp_key: str = "time:timestamp",
158
+ case_id_key: str = "case:concept:name",
159
+ ) -> str:
160
+ """
161
+ Obtains the DFG (Directly-Follows Graph) abstraction of a traditional event log.
162
+
163
+ :param log_obj: The log object to abstract.
164
+ :param max_len: Maximum length of the string abstraction (default: constants.OPENAI_MAX_LEN).
165
+ :param include_performance: Whether to include the performance of the paths in the abstraction.
166
+ :param relative_frequency: Whether to use relative instead of absolute frequency of the paths.
167
+ :param response_header: Whether to include a short header before the paths, describing the abstraction.
168
+ :param primary_performance_aggregation: Primary aggregation method for the arc's performance (default: "mean"). Other options: "median", "min", "max", "sum", "stdev".
169
+ :param secondary_performance_aggregation: (Optional) Secondary aggregation method for the arc's performance (default: None). Other options: "mean", "median", "min", "max", "sum", "stdev".
170
+ :param activity_key: The column name to be used as activity.
171
+ :param timestamp_key: The column name to be used as timestamp.
172
+ :param case_id_key: The column name to be used as case identifier.
173
+ :return: The DFG abstraction as a string.
174
+
175
+ .. code-block:: python3
176
+
177
+ import pm4py
178
+
179
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes")
180
+ print(pm4py.llm.abstract_dfg(log))
181
+ """
182
+ __event_log_deprecation_warning(log_obj)
183
+
184
+ parameters = get_properties(
185
+ log_obj,
186
+ activity_key=activity_key,
187
+ timestamp_key=timestamp_key,
188
+ case_id_key=case_id_key,
189
+ )
190
+ parameters["max_len"] = max_len
191
+ parameters["include_performance"] = include_performance
192
+ parameters["relative_frequency"] = relative_frequency
193
+ parameters["response_header"] = response_header
194
+ parameters["primary_performance_aggregation"] = (
195
+ primary_performance_aggregation
196
+ )
197
+ parameters["secondary_performance_aggregation"] = (
198
+ secondary_performance_aggregation
199
+ )
200
+
201
+ from pm4py.algo.querying.llm.abstractions import log_to_dfg_descr
202
+
203
+ return log_to_dfg_descr.apply(log_obj, parameters=parameters)
204
+
205
+
206
+ def abstract_variants(
207
+ log_obj: Union[pd.DataFrame, EventLog, EventStream],
208
+ max_len: int = constants.OPENAI_MAX_LEN,
209
+ include_performance: bool = True,
210
+ relative_frequency: bool = False,
211
+ response_header: bool = True,
212
+ primary_performance_aggregation: str = "mean",
213
+ secondary_performance_aggregation: Optional[str] = None,
214
+ activity_key: str = "concept:name",
215
+ timestamp_key: str = "time:timestamp",
216
+ case_id_key: str = "case:concept:name",
217
+ **kwargs
218
+ ) -> str:
219
+ """
220
+ Obtains the variants abstraction of a traditional event log.
221
+
222
+ :param log_obj: The log object to abstract.
223
+ :param max_len: Maximum length of the string abstraction (default: constants.OPENAI_MAX_LEN).
224
+ :param include_performance: Whether to include the performance of the variants in the abstraction.
225
+ :param relative_frequency: Whether to use relative instead of absolute frequency of the variants.
226
+ :param response_header: Whether to include a short header before the variants, describing the abstraction.
227
+ :param primary_performance_aggregation: Primary aggregation method for the variants' performance (default: "mean"). Other options: "median", "min", "max", "sum", "stdev".
228
+ :param secondary_performance_aggregation: (Optional) Secondary aggregation method for the variants' performance (default: None). Other options: "mean", "median", "min", "max", "sum", "stdev".
229
+ :param activity_key: The column name to be used as activity.
230
+ :param timestamp_key: The column name to be used as timestamp.
231
+ :param case_id_key: The column name to be used as case identifier.
232
+ :return: The variants abstraction as a string.
233
+
234
+ .. code-block:: python3
235
+
236
+ import pm4py
237
+
238
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes")
239
+ print(pm4py.llm.abstract_variants(log))
240
+ """
241
+ __event_log_deprecation_warning(log_obj)
242
+
243
+ parameters = get_properties(
244
+ log_obj,
245
+ activity_key=activity_key,
246
+ timestamp_key=timestamp_key,
247
+ case_id_key=case_id_key,
248
+ )
249
+ parameters["max_len"] = max_len
250
+ parameters["include_performance"] = include_performance
251
+ parameters["relative_frequency"] = relative_frequency
252
+ parameters["response_header"] = response_header
253
+ parameters["primary_performance_aggregation"] = (
254
+ primary_performance_aggregation
255
+ )
256
+ parameters["secondary_performance_aggregation"] = (
257
+ secondary_performance_aggregation
258
+ )
259
+
260
+ from pm4py.algo.querying.llm.abstractions import log_to_variants_descr
261
+
262
+ return log_to_variants_descr.apply(log_obj, parameters=parameters)
263
+
264
+
265
+ def abstract_ocel(ocel: OCEL, include_timestamps: bool = True) -> str:
266
+ """
267
+ Obtains the abstraction of an object-centric event log, including the list of events and the objects of the OCEL.
268
+
269
+ :param ocel: The object-centric event log to abstract.
270
+ :param include_timestamps: Whether to include timestamp information in the abstraction.
271
+ :return: The OCEL abstraction as a string.
272
+
273
+ .. code-block:: python3
274
+
275
+ import pm4py
276
+
277
+ ocel = pm4py.read_ocel("tests/input_data/ocel/example_log.jsonocel")
278
+ print(pm4py.llm.abstract_ocel(ocel))
279
+ """
280
+ parameters = {}
281
+ parameters["include_timestamps"] = include_timestamps
282
+
283
+ from pm4py.algo.transformation.ocel.description import (
284
+ algorithm as ocel_description,
285
+ )
286
+
287
+ return ocel_description.apply(ocel, parameters=parameters)
288
+
289
+
290
+ def abstract_ocel_ocdfg(
291
+ ocel: OCEL,
292
+ include_header: bool = True,
293
+ include_timestamps: bool = True,
294
+ max_len: int = constants.OPENAI_MAX_LEN,
295
+ ) -> str:
296
+ """
297
+ Obtains the abstraction of an object-centric event log, representing the object-centric directly-follows graph in text.
298
+
299
+ :param ocel: The object-centric event log to abstract.
300
+ :param include_header: Whether to include a header in the abstraction.
301
+ :param include_timestamps: Whether to include timestamp information in the abstraction.
302
+ :param max_len: Maximum length of the abstraction (default: constants.OPENAI_MAX_LEN).
303
+ :return: The object-centric DFG abstraction as a string.
304
+
305
+ .. code-block:: python3
306
+
307
+ import pm4py
308
+
309
+ ocel = pm4py.read_ocel("tests/input_data/ocel/example_log.jsonocel")
310
+ print(pm4py.llm.abstract_ocel_ocdfg(ocel))
311
+ """
312
+ parameters = {}
313
+ parameters["include_header"] = include_header
314
+ parameters["include_timestamps"] = include_timestamps
315
+ parameters["max_len"] = max_len
316
+
317
+ from pm4py.algo.querying.llm.abstractions import ocel_ocdfg_descr
318
+
319
+ return ocel_ocdfg_descr.apply(ocel, parameters=parameters)
320
+
321
+
322
+ def abstract_ocel_features(
323
+ ocel: OCEL,
324
+ obj_type: str,
325
+ include_header: bool = True,
326
+ max_len: int = constants.OPENAI_MAX_LEN,
327
+ debug: bool = False,
328
+ enable_object_lifecycle_paths: bool = True,
329
+ ) -> str:
330
+ """
331
+ Obtains the abstraction of an object-centric event log, representing the features and their values in text.
332
+
333
+ :param ocel: The object-centric event log to abstract.
334
+ :param obj_type: The object type to consider in feature extraction.
335
+ :param include_header: Whether to include a header in the abstraction.
336
+ :param max_len: Maximum length of the abstraction (default: constants.OPENAI_MAX_LEN).
337
+ :param debug: Enables debugging mode, providing insights into feature extraction steps.
338
+ :param enable_object_lifecycle_paths: Enables the "lifecycle paths" feature in the abstraction.
339
+ :return: The OCEL features abstraction as a string.
340
+
341
+ .. code-block:: python3
342
+
343
+ import pm4py
344
+
345
+ ocel = pm4py.read_ocel("tests/input_data/ocel/example_log.jsonocel")
346
+ print(pm4py.llm.abstract_ocel_features(ocel, obj_type="Resource"))
347
+ """
348
+ parameters = {}
349
+ parameters["include_header"] = include_header
350
+ parameters["max_len"] = max_len
351
+ parameters["debug"] = debug
352
+ parameters["enable_object_lifecycle_paths"] = enable_object_lifecycle_paths
353
+
354
+ from pm4py.algo.querying.llm.abstractions import ocel_fea_descr
355
+
356
+ return ocel_fea_descr.apply(ocel, obj_type, parameters=parameters)
357
+
358
+
359
+ def abstract_event_stream(
360
+ log_obj: Union[pd.DataFrame, EventLog, EventStream],
361
+ max_len: int = constants.OPENAI_MAX_LEN,
362
+ response_header: bool = True,
363
+ activity_key: str = "concept:name",
364
+ timestamp_key: str = "time:timestamp",
365
+ case_id_key: str = "case:concept:name",
366
+ ) -> str:
367
+ """
368
+ Obtains the event stream abstraction of a traditional event log.
369
+
370
+ :param log_obj: The log object to abstract.
371
+ :param max_len: Maximum length of the string abstraction (default: constants.OPENAI_MAX_LEN).
372
+ :param response_header: Whether to include a short header before the event stream, describing the abstraction.
373
+ :param activity_key: The column name to be used as activity.
374
+ :param timestamp_key: The column name to be used as timestamp.
375
+ :param case_id_key: The column name to be used as case identifier.
376
+ :return: The event stream abstraction as a string.
377
+
378
+ .. code-block:: python3
379
+
380
+ import pm4py
381
+
382
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes")
383
+ print(pm4py.llm.abstract_event_stream(log))
384
+ """
385
+ __event_log_deprecation_warning(log_obj)
386
+
387
+ parameters = get_properties(
388
+ log_obj,
389
+ activity_key=activity_key,
390
+ timestamp_key=timestamp_key,
391
+ case_id_key=case_id_key,
392
+ )
393
+ parameters["max_len"] = max_len
394
+ parameters["response_header"] = response_header
395
+
396
+ from pm4py.algo.querying.llm.abstractions import stream_to_descr
397
+
398
+ return stream_to_descr.apply(log_obj, parameters=parameters)
399
+
400
+
401
+ def abstract_petri_net(
402
+ net: PetriNet, im: Marking, fm: Marking, response_header: bool = True
403
+ ) -> str:
404
+ """
405
+ Obtains an abstraction of a Petri net.
406
+
407
+ :param net: The Petri net to abstract.
408
+ :param im: The initial marking of the Petri net.
409
+ :param fm: The final marking of the Petri net.
410
+ :param response_header: Whether to include a header in the abstraction.
411
+ :return: The Petri net abstraction as a string.
412
+
413
+ .. code-block:: python3
414
+
415
+ import pm4py
416
+
417
+ net, im, fm = pm4py.read_pnml('tests/input_data/running-example.pnml')
418
+ print(pm4py.llm.abstract_petri_net(net, im, fm))
419
+ """
420
+ parameters = {}
421
+ parameters["response_header"] = response_header
422
+
423
+ from pm4py.algo.querying.llm.abstractions import net_to_descr
424
+
425
+ return net_to_descr.apply(net, im, fm, parameters=parameters)
426
+
427
+
428
+ def abstract_log_attributes(
429
+ log_obj: Union[pd.DataFrame, EventLog, EventStream],
430
+ max_len: int = constants.OPENAI_MAX_LEN,
431
+ activity_key: str = "concept:name",
432
+ timestamp_key: str = "time:timestamp",
433
+ case_id_key: str = "case:concept:name",
434
+ ) -> str:
435
+ """
436
+ Abstracts the attributes of a log by reporting their names, types, and top values.
437
+
438
+ :param log_obj: The log object whose attributes are to be abstracted.
439
+ :param max_len: Maximum length of the string abstraction (default: constants.OPENAI_MAX_LEN).
440
+ :param activity_key: The column name to be used as activity.
441
+ :param timestamp_key: The column name to be used as timestamp.
442
+ :param case_id_key: The column name to be used as case identifier.
443
+ :return: The log attributes abstraction as a string.
444
+
445
+ .. code-block:: python3
446
+
447
+ import pm4py
448
+
449
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes")
450
+ print(pm4py.llm.abstract_log_attributes(log))
451
+ """
452
+ __event_log_deprecation_warning(log_obj)
453
+
454
+ parameters = get_properties(
455
+ log_obj,
456
+ activity_key=activity_key,
457
+ timestamp_key=timestamp_key,
458
+ case_id_key=case_id_key,
459
+ )
460
+ parameters["max_len"] = max_len
461
+
462
+ from pm4py.algo.querying.llm.abstractions import log_to_cols_descr
463
+
464
+ return log_to_cols_descr.apply(log_obj, parameters=parameters)
465
+
466
+
467
+ def abstract_log_features(
468
+ log_obj: Union[pd.DataFrame, EventLog, EventStream],
469
+ max_len: int = constants.OPENAI_MAX_LEN,
470
+ include_header: bool = True,
471
+ activity_key: str = "concept:name",
472
+ timestamp_key: str = "time:timestamp",
473
+ case_id_key: str = "case:concept:name",
474
+ ) -> str:
475
+ """
476
+ Abstracts the machine learning features obtained from a log by reporting the top features until the desired length is achieved.
477
+
478
+ :param log_obj: The log object from which to extract features.
479
+ :param max_len: Maximum length of the string abstraction (default: constants.OPENAI_MAX_LEN).
480
+ :param include_header: Whether to include a header in the abstraction.
481
+ :param activity_key: The column name to be used as activity.
482
+ :param timestamp_key: The column name to be used as timestamp.
483
+ :param case_id_key: The column name to be used as case identifier.
484
+ :return: The log features abstraction as a string.
485
+
486
+ .. code-block:: python3
487
+
488
+ import pm4py
489
+
490
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes")
491
+ print(pm4py.llm.abstract_log_features(log))
492
+ """
493
+ __event_log_deprecation_warning(log_obj)
494
+
495
+ parameters = get_properties(
496
+ log_obj,
497
+ activity_key=activity_key,
498
+ timestamp_key=timestamp_key,
499
+ case_id_key=case_id_key,
500
+ )
501
+ parameters["max_len"] = max_len
502
+ parameters["include_header"] = include_header
503
+
504
+ from pm4py.algo.querying.llm.abstractions import log_to_fea_descr
505
+
506
+ return log_to_fea_descr.apply(log_obj, parameters=parameters)
507
+
508
+
509
+ def abstract_temporal_profile(
510
+ temporal_profile: Dict[Tuple[str, str], Tuple[float, float]],
511
+ include_header: bool = True,
512
+ ) -> str:
513
+ """
514
+ Abstracts a temporal profile model into a descriptive string.
515
+
516
+ :param temporal_profile: The temporal profile model to abstract.
517
+ :param include_header: Whether to include a header in the abstraction describing the temporal profile.
518
+ :return: The temporal profile abstraction as a string.
519
+
520
+ .. code-block:: python3
521
+
522
+ import pm4py
523
+
524
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes", return_legacy_log_object=True)
525
+ temporal_profile = pm4py.discover_temporal_profile(log)
526
+ text_abstr = pm4py.llm.abstract_temporal_profile(temporal_profile, include_header=True)
527
+ print(text_abstr)
528
+ """
529
+ parameters = {}
530
+ parameters["include_header"] = include_header
531
+
532
+ from pm4py.algo.querying.llm.abstractions import tempprofile_to_descr
533
+
534
+ return tempprofile_to_descr.apply(temporal_profile, parameters=parameters)
535
+
536
+
537
+ def abstract_case(
538
+ case: Trace,
539
+ include_case_attributes: bool = True,
540
+ include_event_attributes: bool = True,
541
+ include_timestamp: bool = True,
542
+ include_header: bool = True,
543
+ activity_key: str = "concept:name",
544
+ timestamp_key: str = "time:timestamp",
545
+ ) -> str:
546
+ """
547
+ Textually abstracts a single case from an event log.
548
+
549
+ :param case: The case object to abstract.
550
+ :param include_case_attributes: Whether to include attributes at the case level.
551
+ :param include_event_attributes: Whether to include attributes at the event level.
552
+ :param include_timestamp: Whether to include event timestamps in the abstraction.
553
+ :param include_header: Whether to include a header in the abstraction.
554
+ :param activity_key: The column name to be used as activity.
555
+ :param timestamp_key: The column name to be used as timestamp.
556
+ :return: The case abstraction as a string.
557
+
558
+ .. code-block:: python3
559
+
560
+ import pm4py
561
+
562
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes", return_legacy_log_object=True)
563
+ print(pm4py.llm.abstract_case(log[0]))
564
+ """
565
+ parameters = {}
566
+ parameters["include_case_attributes"] = include_case_attributes
567
+ parameters["include_event_attributes"] = include_event_attributes
568
+ parameters["include_timestamp"] = include_timestamp
569
+ parameters["include_header"] = include_header
570
+ parameters[constants.PARAMETER_CONSTANT_ACTIVITY_KEY] = activity_key
571
+ parameters[constants.PARAMETER_CONSTANT_TIMESTAMP_KEY] = timestamp_key
572
+
573
+ from pm4py.algo.querying.llm.abstractions import case_to_descr
574
+
575
+ return case_to_descr.apply(case, parameters=parameters)
576
+
577
+
578
+ def abstract_declare(declare_model, include_header: bool = True) -> str:
579
+ """
580
+ Textually abstracts a DECLARE model.
581
+
582
+ :param declare_model: The DECLARE model to abstract.
583
+ :param include_header: Whether to include a header in the abstraction.
584
+ :return: The DECLARE model abstraction as a string.
585
+
586
+ .. code-block:: python3
587
+
588
+ import pm4py
589
+
590
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes", return_legacy_log_object=True)
591
+ log_ske = pm4py.discover_declare(log)
592
+ print(pm4py.llm.abstract_declare(log_ske))
593
+ """
594
+ parameters = {}
595
+ parameters["include_header"] = include_header
596
+
597
+ from pm4py.algo.querying.llm.abstractions import declare_to_descr
598
+
599
+ return declare_to_descr.apply(declare_model, parameters=parameters)
600
+
601
+
602
+ def abstract_log_skeleton(log_skeleton, include_header: bool = True) -> str:
603
+ """
604
+ Textually abstracts a log skeleton process model.
605
+
606
+ :param log_skeleton: The log skeleton to abstract.
607
+ :param include_header: Whether to include a header in the abstraction.
608
+ :return: The log skeleton abstraction as a string.
609
+
610
+ .. code-block:: python3
611
+
612
+ import pm4py
613
+
614
+ log = pm4py.read_xes("tests/input_data/roadtraffic100traces.xes", return_legacy_log_object=True)
615
+ log_ske = pm4py.discover_log_skeleton(log)
616
+ print(pm4py.llm.abstract_log_skeleton(log_ske))
617
+ """
618
+ parameters = {}
619
+ parameters["include_header"] = include_header
620
+
621
+ from pm4py.algo.querying.llm.abstractions import logske_to_descr
622
+
623
+ return logske_to_descr.apply(log_skeleton, parameters=parameters)
624
+
625
+
626
+ def clustering(log: pd.DataFrame, executor=openai_query, case_id_key: str = "case:concept:name", activity_key: str = "concept:name", **kwargs) -> List[Tuple[str, pd.DataFrame]]:
627
+ """
628
+ Performs LLM-based clustering on the variants' list.
629
+
630
+ Parameters
631
+ -----------------
632
+ log
633
+ Pandas dataframe
634
+ executor
635
+ The connector that should be used (openai, google, anthropic)
636
+ case_id_key
637
+ Column representing the case ID
638
+ activity_key
639
+ Column representing the activity
640
+
641
+ Returns
642
+ -----------------
643
+ final_clusters
644
+ A list of tuples. The first element is the name associated to the cluster, the second one is the sub-event-log.
645
+ """
646
+ import pm4py, json, re
647
+
648
+ prompt = pm4py.llm.abstract_variants(log, include_performance=False, **kwargs)
649
+ prompt += "\n\nCould you identify clusters of traces in the provided list? "
650
+ prompt += "Please provide a JSON list, contained in the ```json tags, containing a dictionary for each cluster. "
651
+ prompt += " The dictionary has a key 'name' and a key 'regex'."
652
+ prompt += " The 'name' should be a meaningful name for the cluster. The 'regex' should be a regular expression,"
653
+ prompt += "that I can use to filter the traces."
654
+
655
+ result = executor(prompt, **kwargs)
656
+ result = json.loads(result.split("```json")[1].split("```")[0])
657
+
658
+ final_clusters = []
659
+ agg0 = log.groupby(case_id_key, sort=False)[activity_key].agg(list).reset_index()
660
+ agg0["concept:name"] = agg0["concept:name"].apply(lambda x: " -> ".join(x))
661
+
662
+ for res in result:
663
+ reg = re.compile(res["regex"])
664
+ agg = agg0[agg0[activity_key].str.contains(reg)]
665
+ df = log[log[case_id_key].isin(agg[case_id_key])]
666
+
667
+ final_clusters.append((res["name"], df))
668
+
669
+ return final_clusters
670
+
671
+
672
+ def __validate_safe_select_query(sql_query: str) -> str:
673
+ """
674
+ Validates that a SQL query is read-only and free from statements/functions
675
+ that could access or modify local files/databases.
676
+ """
677
+ query = sql_query.strip()
678
+ if query.endswith(";"):
679
+ query = query[:-1].strip()
680
+
681
+ if not query:
682
+ raise ValueError("The response does not contain a valid SQL query.")
683
+
684
+ if ";" in query:
685
+ raise ValueError("Only a single SQL statement is allowed.")
686
+
687
+ if "--" in query or "/*" in query or "*/" in query:
688
+ raise ValueError("SQL comments are not allowed in auto-executed queries.")
689
+
690
+ normalized = " ".join(query.lower().split())
691
+ if not (normalized.startswith("select ") or normalized.startswith("with ")):
692
+ raise ValueError("Only read-only SELECT queries can be auto-executed.")
693
+
694
+ forbidden_patterns = [
695
+ r"\b(insert|update|delete|drop|alter|create|replace|truncate|merge)\b",
696
+ r"\b(attach|detach|copy|call|pragma|install|load|export|import|vacuum)\b",
697
+ r"\b(read_csv|read_csv_auto|read_parquet|read_json|read_json_auto)\b",
698
+ r"\bwrite_(csv|parquet)\b",
699
+ ]
700
+
701
+ for pattern in forbidden_patterns:
702
+ if re.search(pattern, normalized):
703
+ raise ValueError("Unsafe SQL detected in LLM-generated query.")
704
+
705
+ return query
706
+
707
+
708
+ def __execute_prompt_to_db_query(
709
+ log: pd.DataFrame,
710
+ prompt: str,
711
+ executor=openai_query,
712
+ execute_query: bool = True,
713
+ **kwargs
714
+ ) -> Union[str, pd.DataFrame]:
715
+ """
716
+ Internal method to retrieve (and execute) a SQL query corresponding to a prompt
717
+ """
718
+ if check_is_pandas_dataframe(log):
719
+ kwargs["table_name"] = "dataframe"
720
+ dataframe = log
721
+
722
+ response = executor(prompt, **kwargs)
723
+
724
+ sql_query = ""
725
+ if "```sql" in response:
726
+ sql_query = response.split("```sql")[1].split("```")[0]
727
+ sql_query = sql_query.strip()
728
+
729
+ if not sql_query:
730
+ raise Exception(
731
+ "The response does not contain a valid SQL query: " + response
732
+ )
733
+
734
+ if execute_query:
735
+ safe_sql_query = __validate_safe_select_query(sql_query)
736
+ import duckdb
737
+
738
+ result = duckdb.query(safe_sql_query).to_df()
739
+
740
+ if check_is_pandas_dataframe(log):
741
+ return result
742
+
743
+ return sql_query
744
+
745
+
746
+ def nlp_to_log_query(
747
+ log: pd.DataFrame,
748
+ query: str,
749
+ executor=openai_query,
750
+ obtain_query: bool = True,
751
+ execute_query: bool = True,
752
+ **kwargs
753
+ ) -> Union[str, pd.DataFrame]:
754
+ """
755
+ Translates a natural language statement into a database (SQL) query executable against the event log.
756
+
757
+ :param log: event log object
758
+ :param query: query expressed in natural language
759
+ :param executor: the connector to the LLM (e.g., pm4py.llm.openai_query)
760
+ :param obtain_query: executes the prompt, to transform the natural statements into a database (SQL) query
761
+ :param execute_query: executes the database (SQL) query against the event data
762
+ :param kwargs: additional keyword arguments to the method
763
+ :rtype: ``Union[str, pd.DataFrame]``
764
+
765
+ .. code-block:: python3
766
+
767
+ import pm4py
768
+
769
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
770
+ resp = pm4py.llm.nlp_to_log_query(log, "How many cases are contained in the event log?", api_key="sk-5HNn")
771
+ print(resp)
772
+ """
773
+ from pm4py.algo.querying.llm.injection import (
774
+ algorithm as domain_knowledge_injector,
775
+ )
776
+
777
+ prompt = (
778
+ "Could you provide a database query for the following question?\n\n"
779
+ + query
780
+ )
781
+ prompt += domain_knowledge_injector.apply(log, parameters=kwargs)
782
+ prompt += "\n\nPlease include the SQL query between the ```sql and the ``` tags.\n\n"
783
+
784
+ if obtain_query:
785
+ return __execute_prompt_to_db_query(
786
+ log,
787
+ prompt,
788
+ executor=executor,
789
+ execute_query=execute_query,
790
+ **kwargs
791
+ )
792
+
793
+ return prompt
794
+
795
+
796
+ def nlp_to_log_filter(
797
+ log: pd.DataFrame,
798
+ filter_query: str,
799
+ executor=openai_query,
800
+ obtain_query: bool = True,
801
+ execute_query: bool = True,
802
+ **kwargs
803
+ ) -> Union[str, pd.DataFrame]:
804
+ """
805
+ Translates a filtering query expressed in natural language into a database (SQL) query that is used to filter the
806
+ event log.
807
+
808
+ :param log: event log object
809
+ :param filter_query: filtering query expressed in natural language
810
+ :param executor: the connector to the LLM (e.g., pm4py.llm.openai_query)
811
+ :param obtain_query: executes the prompt, to transform the natural statements into a database (SQL) query
812
+ :param execute_query: executes the database (SQL) query against the event data
813
+ :param kwargs: additional keyword arguments to the method
814
+ :rtype: ``Union[str, pd.DataFrame]``
815
+
816
+ .. code-block:: python3
817
+
818
+ import pm4py
819
+
820
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
821
+ resp = pm4py.llm.nlp_to_log_filter(log, "There is an event with activity: pay compensation", api_key="sk-5HNn")
822
+ print(resp)
823
+ """
824
+ from pm4py.algo.querying.llm.injection import (
825
+ algorithm as domain_knowledge_injector,
826
+ )
827
+
828
+ prompt = (
829
+ "Could you provide a database query to filter all the events of the cases for which at least an event (row) is satisfying the following filtering query?\n\n" +
830
+ filter_query)
831
+ prompt += domain_knowledge_injector.apply(log, parameters=kwargs)
832
+ prompt += "\n\nPlease include the SQL query between the ```sql and the ``` tags.\n\n"
833
+
834
+ if obtain_query:
835
+ return __execute_prompt_to_db_query(
836
+ log,
837
+ prompt,
838
+ executor=executor,
839
+ execute_query=execute_query,
840
+ **kwargs
841
+ )
842
+
843
+ return prompt
844
+
845
+
846
+ def automated_hypotheses_formulation(
847
+ dataframe: pd.DataFrame,
848
+ executor=openai_query,
849
+ obtain_query: bool = True,
850
+ execute_query: bool = True,
851
+ max_len=10000,
852
+ **kwargs
853
+ ) -> Union[str, List[Tuple[str, str, Union[str, None]]]]:
854
+ """
855
+ Automatically formulate some hypotheses on the event data.
856
+ The result of this method is either:
857
+ - The prompt (to be executed manually against the LLM) when obtain_query=False
858
+ - A list of different hypotheses. Each hypothesis comes with a description (position 0), the SQL query (position 1),
859
+ and (if execute_query=True) the result of the execution of the query in position 2.
860
+
861
+ :param dataframe: event log object
862
+ :param executor: the connector to the LLM (e.g., pm4py.llm.openai_query)
863
+ :param obtain_query: executes the prompt and get the hypotheses along with the corresponding SQL queries
864
+ :param execute_query: executes the obtained SQL queries and stores the results
865
+ :param kwargs: additional keyword arguments to the method
866
+ :param max_len: maximum length of the obtained prompt
867
+ :rtype: ``Union[str, List[Tuple[str, str, Union[str, None]]]]``
868
+
869
+ .. code-block:: python3
870
+
871
+ import pm4py
872
+
873
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
874
+ result = pm4py.llm.automated_hypotheses_formulation(log, api_key="sk-5HN")
875
+ print(result)
876
+ """
877
+ import duckdb
878
+ from pm4py.algo.querying.llm.abstractions import log_to_cols_descr
879
+
880
+ from pm4py.algo.querying.llm.injection import (
881
+ algorithm as domain_knowledge_injector,
882
+ )
883
+
884
+ prompt = "Could you formulate some hypotheses over the event data? The directly-follows graph, the list of attributes, and additional process mining/database knowledge follow.\n\n"
885
+ prompt += abstract_dfg(dataframe, max_len=int(max_len / 3))
886
+ prompt += "\n\n"
887
+ prompt += log_to_cols_descr.apply(
888
+ dataframe, parameters={"max_len": int(max_len / 3)}
889
+ )
890
+ prompt += "\n\n"
891
+ prompt += domain_knowledge_injector.apply(dataframe, parameters=kwargs)
892
+ prompt += "Please provide each hypothesis along with a SQL query. Please include the SQL queries between the ```sql and the ``` tags.\n"
893
+ prompt += "Can you please include also a description of each hypothesis between some <description> and </description> tags?\n\n"
894
+
895
+ if obtain_query:
896
+ response = executor(prompt, **kwargs)
897
+
898
+ obtained_queries = response.split("```sql")
899
+ obtained_descriptions = response.split("<description>")
900
+
901
+ if (
902
+ len(obtained_queries) > 1
903
+ and len(obtained_descriptions) > 1
904
+ and len(obtained_queries) == len(obtained_descriptions)
905
+ ):
906
+ del obtained_queries[0]
907
+ del obtained_descriptions[0]
908
+
909
+ obtained_queries = [x.split("```")[0] for x in obtained_queries]
910
+ obtained_descriptions = [
911
+ x.split("</description>")[0].strip()
912
+ for x in obtained_descriptions
913
+ ]
914
+ obtained_results = [None] * len(obtained_descriptions)
915
+
916
+ if execute_query:
917
+ for i in range(len(obtained_queries)):
918
+ try:
919
+ obtained_results[i] = duckdb.sql(
920
+ obtained_queries[i]
921
+ ).to_df()
922
+ except BaseException:
923
+ print("Exception executing query nr. %d" % i)
924
+
925
+ return [
926
+ (
927
+ obtained_descriptions[i],
928
+ obtained_queries[i],
929
+ obtained_results[i],
930
+ )
931
+ for i in range(len(obtained_queries))
932
+ ]
933
+
934
+ return prompt
935
+
936
+
937
+ def explain_visualization(
938
+ vis_saver, *args, connector=openai_query, **kwargs
939
+ ) -> str:
940
+ r"""Explains a process mining visualization using LLMs by saving it as a
941
+ .png image and providing the image to the Large Language Model along with a
942
+ description.
943
+
944
+ :param vis_saver: The visualizer function used to save the visualization to disk.
945
+ :param args: Positional arguments required by the visualizer function.
946
+ :param connector: (Optional) The connector method to communicate with the large language model (default: openai_query).
947
+ :param \**kwargs: Additional keyword arguments for the visualizer function or the connector (e.g., annotations, API key).
948
+ :return: The explanation of the visualization as a string.
949
+
950
+ .. code-block:: python3
951
+
952
+ import pm4py
953
+
954
+ log = pm4py.read_xes("tests/input_data/running-example.xes")
955
+ descr = pm4py.llm.explain_visualization(pm4py.save_vis_dotted_chart, log, api_key="sk-5HN", show_legend=False)
956
+ print(descr)
957
+ """
958
+ F = NamedTemporaryFile(suffix=".png")
959
+ image_path = F.name
960
+ F.close()
961
+
962
+ description = vis_saver(*args, image_path, **kwargs)
963
+
964
+ parameters = copy(kwargs) if kwargs is not None else {}
965
+ parameters["image_path"] = image_path
966
+
967
+ return connector(
968
+ "Could you explain the included process mining visualization?\n\n"
969
+ + description,
970
+ **parameters
971
+ )
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/meta.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ __name__ = "pm4py"
23
+ __version__ = "2.7.23.11"
24
+ VERSION = __version__
25
+ __doc__ = "Process mining for Python"
26
+ __author__ = "Process Intelligence Solutions (PIS)"
27
+ __author_email__ = "info@processintelligence.solutions"
28
+ __maintainer__ = "Process Intelligence Solutions (PIS)"
29
+ __maintainer_email__ = "info@processintelligence.solutions"
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/ml.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ __doc__ = """
23
+ The ``pm4py.ml`` module contains the machine learning features offered in ``pm4py``.
24
+ """
25
+
26
+ from typing import Union, Tuple, Any, List, Collection, Optional
27
+ import pandas as pd
28
+ import numpy as np
29
+ from pm4py.objects.ocel.obj import OCEL
30
+ from pm4py.objects.log.obj import EventLog
31
+ from pm4py.utils import __event_log_deprecation_warning
32
+ import random
33
+ from copy import copy
34
+ from pm4py.util.pandas_utils import (
35
+ check_is_pandas_dataframe,
36
+ check_pandas_dataframe_columns,
37
+ )
38
+ from pm4py.utils import get_properties, constants, pandas_utils, is_polars_lazyframe, check_is_pandas_dataframe
39
+
40
+
41
+ def split_train_test(
42
+ log: Union[EventLog, pd.DataFrame],
43
+ train_percentage: float = 0.8,
44
+ case_id_key: str = "case:concept:name",
45
+ ) -> Union[Tuple[EventLog, EventLog], Tuple[pd.DataFrame, pd.DataFrame]]:
46
+ """
47
+ Splits an event log into a training log and a test log for machine learning purposes.
48
+
49
+ This function separates the provided log into two parts based on the specified training percentage.
50
+ It ensures that entire cases are included in either the training set or the test set.
51
+
52
+ :param log: The event log or Pandas DataFrame to be split.
53
+ :param train_percentage: Fraction of cases to be included in the training log (between 0.0 and 1.0).
54
+ :param case_id_key: Attribute to be used as the case identifier.
55
+ :return: A tuple containing the training and test event logs or DataFrames.
56
+ :rtype: ``Union[Tuple[EventLog, EventLog], Tuple[pd.DataFrame, pd.DataFrame]]``
57
+
58
+ .. code-block:: python3
59
+
60
+ import pm4py
61
+
62
+ train_df, test_df = pm4py.split_train_test(dataframe, train_percentage=0.75)
63
+ """
64
+ __event_log_deprecation_warning(log)
65
+
66
+ if check_is_pandas_dataframe(log):
67
+ check_pandas_dataframe_columns(log)
68
+ cases = pandas_utils.format_unique(log[case_id_key].unique())
69
+ train_cases = set()
70
+ test_cases = set()
71
+ for c in cases:
72
+ r = random.random()
73
+ if r <= train_percentage:
74
+ train_cases.add(c)
75
+ else:
76
+ test_cases.add(c)
77
+ train_df = log[log[case_id_key].isin(train_cases)]
78
+ test_df = log[log[case_id_key].isin(test_cases)]
79
+ return train_df, test_df
80
+ else:
81
+ from pm4py.objects.log.util import split_train_test
82
+
83
+ return split_train_test.split(log, train_percentage=train_percentage)
84
+
85
+
86
+ def get_prefixes_from_log(
87
+ log: Union[EventLog, pd.DataFrame],
88
+ length: int,
89
+ case_id_key: str = "case:concept:name",
90
+ ) -> Union[EventLog, pd.DataFrame]:
91
+ """
92
+ Retrieves prefixes of traces in a log up to a specified length.
93
+
94
+ The returned log contains prefixes of each trace:
95
+
96
+ - If a trace has a length less than or equal to the specified length, it is included as-is.
97
+ - If a trace exceeds the specified length, it is truncated to that length.
98
+
99
+ :param log: The event log or Pandas DataFrame from which to extract prefixes.
100
+ :param length: The maximum length of prefixes to extract.
101
+ :param case_id_key: Attribute to be used as the case identifier.
102
+ :return: A log containing the prefixes of the original log.
103
+ :rtype: ``Union[EventLog, pd.DataFrame]``
104
+
105
+ .. code-block:: python3
106
+
107
+ import pm4py
108
+
109
+ trimmed_df = pm4py.get_prefixes_from_log(dataframe, length=5, case_id_key='case:concept:name')
110
+ """
111
+ __event_log_deprecation_warning(log)
112
+
113
+ if check_is_pandas_dataframe(log):
114
+ check_pandas_dataframe_columns(log, case_id_key=case_id_key)
115
+ from pm4py.util import pandas_utils
116
+
117
+ log = pandas_utils.insert_ev_in_tr_index(log, case_id=case_id_key)
118
+ return log[log[constants.DEFAULT_INDEX_IN_TRACE_KEY] <= (length - 1)]
119
+ else:
120
+ from pm4py.objects.log.util import get_prefixes
121
+
122
+ return get_prefixes.get_prefixes_from_log(log, length)
123
+
124
+
125
+ def extract_outcome_enriched_dataframe(
126
+ log: Union[EventLog, pd.DataFrame],
127
+ activity_key: str = "concept:name",
128
+ timestamp_key: str = "time:timestamp",
129
+ case_id_key: str = "case:concept:name",
130
+ start_timestamp_key: str = "time:timestamp",
131
+ ) -> pd.DataFrame:
132
+ """
133
+ Enriches a dataframe with additional outcome-related columns computed from the entire case.
134
+
135
+ This function adds columns that model the outcome of each case by computing metrics such as
136
+ arrival rates and service waiting times.
137
+
138
+ :param log: The event log or Pandas DataFrame to be enriched.
139
+ :param activity_key: Attribute to be used for the activity.
140
+ :param timestamp_key: Attribute to be used for the timestamp.
141
+ :param case_id_key: Attribute to be used as the case identifier.
142
+ :param start_timestamp_key: Attribute to be used as the start timestamp.
143
+ :return: An enriched Pandas DataFrame with additional outcome-related columns.
144
+ :rtype: ``pd.DataFrame``
145
+
146
+ .. code-block:: python3
147
+
148
+ import pm4py
149
+
150
+ enriched_df = pm4py.extract_outcome_enriched_dataframe(
151
+ log,
152
+ activity_key='concept:name',
153
+ timestamp_key='time:timestamp',
154
+ case_id_key='case:concept:name',
155
+ start_timestamp_key='time:timestamp'
156
+ )
157
+ """
158
+ __event_log_deprecation_warning(log)
159
+
160
+ properties = get_properties(
161
+ log,
162
+ activity_key=activity_key,
163
+ case_id_key=case_id_key,
164
+ timestamp_key=timestamp_key,
165
+ )
166
+
167
+ if not check_is_pandas_dataframe(log):
168
+ from pm4py.objects.conversion.log import converter as log_converter
169
+ log = log_converter.apply(
170
+ log,
171
+ variant=log_converter.Variants.TO_DATA_FRAME,
172
+ parameters=properties,
173
+ )
174
+
175
+ log = copy(log)
176
+ fea_df = extract_features_dataframe(
177
+ log,
178
+ activity_key=activity_key,
179
+ timestamp_key=timestamp_key,
180
+ case_id_key=case_id_key,
181
+ include_case_id=True,
182
+ )
183
+ log = pandas_utils.insert_case_arrival_finish_rate(
184
+ log,
185
+ timestamp_column=timestamp_key,
186
+ case_id_column=case_id_key,
187
+ start_timestamp_column=start_timestamp_key,
188
+ )
189
+ log = pandas_utils.insert_case_service_waiting_time(
190
+ log,
191
+ timestamp_column=timestamp_key,
192
+ case_id_column=case_id_key,
193
+ start_timestamp_column=start_timestamp_key,
194
+ )
195
+
196
+ if is_polars_lazyframe(log):
197
+ return log.join(fea_df, on=case_id_key, maintain_order="left")
198
+ else:
199
+ return log.merge(fea_df, on=case_id_key)
200
+
201
+
202
+ def extract_features_dataframe(
203
+ log: Union[EventLog, pd.DataFrame],
204
+ str_tr_attr: Optional[List[str]] = None,
205
+ num_tr_attr: Optional[List[str]] = None,
206
+ str_ev_attr: Optional[List[str]] = None,
207
+ num_ev_attr: Optional[List[str]] = None,
208
+ str_evsucc_attr: Optional[List[str]] = None,
209
+ activity_key: str = "concept:name",
210
+ timestamp_key: str = "time:timestamp",
211
+ case_id_key: Optional[str] = None,
212
+ resource_key: str = "org:resource",
213
+ include_case_id: bool = False,
214
+ count_occurrences: bool = False,
215
+ enable_numeric_attribute_statistics: bool = False,
216
+ numeric_attribute_aggregations: Optional[Collection[str]] = None,
217
+ **kwargs,
218
+ ) -> pd.DataFrame:
219
+ r"""
220
+ Extracts a dataframe containing features for each case in the provided
221
+ log object.
222
+
223
+ This function processes the log to generate a set of features that can be used for machine learning tasks.
224
+ Features can include both case-level and event-level attributes, with options for one-hot encoding.
225
+
226
+ :param log: The event log or Pandas DataFrame from which to extract features.
227
+ :param str_tr_attr: (Optional) List of string attributes at the case level to extract as features.
228
+ :param num_tr_attr: (Optional) List of numeric attributes at the case level to extract as features.
229
+ :param str_ev_attr: (Optional) List of string attributes at the event level to extract as features (one-hot encoded).
230
+ :param num_ev_attr: (Optional) List of numeric attributes at the event level to extract as features
231
+ (uses the last value per attribute in a case).
232
+ :param str_evsucc_attr: (Optional) List of string successor attributes at the event level to extract as features.
233
+ :param activity_key: Attribute to be used as the activity identifier.
234
+ :param timestamp_key: Attribute to be used for timestamps.
235
+ :param case_id_key: (Optional) Attribute to be used as the case identifier. If not provided, the default is used.
236
+ :param resource_key: Attribute to be used as the resource identifier.
237
+ :param include_case_id: Whether to include the case identifier column in the features table.
238
+ :param count_occurrences: If True, count occurrences of string attributes instead of binary encoding.
239
+ :param enable_numeric_attribute_statistics: If True, expand numeric attributes to aggregation columns. If False,
240
+ keep the existing ``ATTRIBUTE`` last-value column unless
241
+ ``numeric_attribute_aggregations`` is provided. If not provided,
242
+ defaults to False.
243
+ :param numeric_attribute_aggregations: Optional collection of numeric aggregations to compute. Supported values are
244
+ ``last``, ``first``, ``min``, ``max``, ``mean``, ``median``, ``stdev``,
245
+ and ``sum``. Applied only to numeric attributes whose names do not start
246
+ with ``@@``.
247
+ :param \**kwargs: Additional keyword arguments to pass to the feature extraction algorithm.
248
+ :return: A Pandas DataFrame containing the extracted features for each case.
249
+ :rtype: ``pd.DataFrame``
250
+
251
+ .. code-block:: python3
252
+
253
+ import pm4py
254
+
255
+ features_df = pm4py.extract_features_dataframe(
256
+ dataframe,
257
+ activity_key='concept:name',
258
+ case_id_key='case:concept:name',
259
+ timestamp_key='time:timestamp'
260
+ )
261
+ """
262
+ __event_log_deprecation_warning(log)
263
+
264
+ parameters = kwargs if kwargs else {}
265
+
266
+ properties = get_properties(
267
+ log,
268
+ activity_key=activity_key,
269
+ timestamp_key=timestamp_key,
270
+ case_id_key=case_id_key,
271
+ )
272
+ for prop in properties:
273
+ parameters[prop] = properties[prop]
274
+
275
+ parameters["str_tr_attr"] = str_tr_attr or []
276
+ parameters["num_tr_attr"] = num_tr_attr or []
277
+ parameters["str_ev_attr"] = str_ev_attr or []
278
+ parameters["num_ev_attr"] = num_ev_attr or []
279
+ parameters["str_evsucc_attr"] = str_evsucc_attr or []
280
+ parameters["add_case_identifier_column"] = include_case_id
281
+ parameters["count_occurrences"] = count_occurrences
282
+ if enable_numeric_attribute_statistics is None:
283
+ enable_numeric_attribute_statistics = False
284
+ parameters["enable_numeric_attribute_statistics"] = (
285
+ enable_numeric_attribute_statistics
286
+ )
287
+ if numeric_attribute_aggregations is not None:
288
+ parameters["numeric_attribute_aggregations"] = (
289
+ numeric_attribute_aggregations
290
+ )
291
+
292
+ from pm4py.algo.transformation.trace_encodings import (
293
+ algorithm as trace_encodings,
294
+ )
295
+
296
+ if check_is_pandas_dataframe(log):
297
+ check_pandas_dataframe_columns(
298
+ log,
299
+ activity_key=activity_key,
300
+ case_id_key=case_id_key,
301
+ timestamp_key=timestamp_key,
302
+ )
303
+
304
+ data, feature_names = trace_encodings.apply(log, parameters=parameters)
305
+ if is_polars_lazyframe(data):
306
+ return data
307
+
308
+ return pandas_utils.instantiate_dataframe(data, columns=feature_names)
309
+
310
+
311
+ def extract_ocel_features(
312
+ ocel: OCEL,
313
+ obj_type: str,
314
+ enable_object_lifecycle_paths: bool = True,
315
+ enable_object_work_in_progress: bool = False,
316
+ object_str_attributes: Optional[Collection[str]] = None,
317
+ object_num_attributes: Optional[Collection[str]] = None,
318
+ include_obj_id: bool = False,
319
+ debug: bool = False,
320
+ ) -> pd.DataFrame:
321
+ """
322
+ Extracts a set of features from an object-centric event log (OCEL) for objects of a specified type.
323
+
324
+ This function computes various features based on the lifecycle paths and work-in-progress metrics
325
+ of objects within the OCEL. It also supports encoding of string and numeric object attributes.
326
+
327
+ The approach is based on:
328
+ Berti, A., Herforth, J., Qafari, M.S. et al. Graph-based feature extraction on object-centric event logs.
329
+ Int J Data Sci Anal (2023). https://doi.org/10.1007/s41060-023-00428-2
330
+
331
+ :param ocel: The object-centric event log from which to extract features.
332
+ :param obj_type: The object type to consider for feature extraction.
333
+ :param enable_object_lifecycle_paths: Whether to enable the "lifecycle paths" feature.
334
+ :param enable_object_work_in_progress: Whether to enable the "work in progress" feature,
335
+ which has a high computational cost.
336
+ :param object_str_attributes: (Optional) Collection of string attributes at the object level to one-hot encode.
337
+ :param object_num_attributes: (Optional) Collection of numeric attributes at the object level to encode.
338
+ :param include_obj_id: Whether to include the object identifier as a column in the features DataFrame.
339
+ :param debug: Whether to enable debugging mode to track the feature extraction process.
340
+ :return: A Pandas DataFrame containing the extracted features for the specified object type.
341
+ :rtype: ``pd.DataFrame``
342
+
343
+ .. code-block:: python3
344
+
345
+ import pm4py
346
+
347
+ ocel = pm4py.read_ocel('log.jsonocel')
348
+ fea_df = pm4py.extract_ocel_features(ocel, "item")
349
+ """
350
+ if object_str_attributes is None:
351
+ object_str_attributes = []
352
+
353
+ if object_num_attributes is None:
354
+ object_num_attributes = []
355
+
356
+ parameters = {
357
+ "filter_per_type": obj_type,
358
+ "enable_object_lifecycle_paths": enable_object_lifecycle_paths,
359
+ "enable_object_work_in_progress": enable_object_work_in_progress,
360
+ "enable_object_str_attributes": bool(object_str_attributes),
361
+ "enable_object_num_attributes": bool(object_num_attributes),
362
+ "str_obj_attr": object_str_attributes,
363
+ "num_obj_attr": object_num_attributes,
364
+ "debug": debug,
365
+ }
366
+
367
+ from pm4py.algo.transformation.ocel.features.objects import (
368
+ algorithm as ocel_feature_extraction,
369
+ )
370
+
371
+ data, feature_names = ocel_feature_extraction.apply(
372
+ ocel, parameters=parameters
373
+ )
374
+
375
+ dataframe = pandas_utils.instantiate_dataframe(data, columns=feature_names)
376
+ dataframe = dataframe.dropna(how="any", axis=1)
377
+ dataframe = dataframe.select_dtypes(include=np.number)
378
+
379
+ if include_obj_id:
380
+ objects_with_type = ocel.objects[
381
+ [ocel.object_id_column, ocel.object_type_column]
382
+ ].to_dict(orient="records")
383
+ objects_with_type = [
384
+ x[ocel.object_id_column]
385
+ for x in objects_with_type
386
+ if x[ocel.object_type_column] == obj_type
387
+ ]
388
+ dataframe[ocel.object_id_column] = objects_with_type
389
+
390
+ return dataframe
391
+
392
+
393
+ def extract_temporal_features_dataframe(
394
+ log: Union[EventLog, pd.DataFrame],
395
+ grouper_freq: str = "W",
396
+ activity_key: str = "concept:name",
397
+ timestamp_key: str = "time:timestamp",
398
+ case_id_key: Optional[str] = None,
399
+ start_timestamp_key: str = "time:timestamp",
400
+ resource_key: str = "org:resource",
401
+ ) -> pd.DataFrame:
402
+ """
403
+ Extracts temporal features from a log object and returns them as a dataframe.
404
+
405
+ This function computes temporal metrics based on the specified grouping frequency, which can be
406
+ daily (D), weekly (W), monthly (M), or yearly (Y). These features are useful for analyzing
407
+ system dynamics and simulation in the context of process mining.
408
+
409
+ The approach is based on:
410
+ Pourbafrani, Mahsa, Sebastiaan J. van Zelst, and Wil MP van der Aalst.
411
+ "Supporting automatic system dynamics model generation for simulation in the context of process mining."
412
+ International Conference on Business Information Systems. Springer, Cham, 2020.
413
+
414
+ :param log: The event log or Pandas DataFrame from which to extract temporal features.
415
+ :param grouper_freq: The frequency to use for grouping (e.g., 'D' for daily, 'W' for weekly,
416
+ 'M' for monthly, 'Y' for yearly).
417
+ :param activity_key: Attribute to be used as the activity identifier.
418
+ :param timestamp_key: Attribute to be used for timestamps.
419
+ :param case_id_key: (Optional) Attribute to be used as the case identifier. If not provided, the default is used.
420
+ :param start_timestamp_key: Attribute to be used as the start timestamp.
421
+ :param resource_key: Attribute to be used as the resource identifier.
422
+ :return: A Pandas DataFrame containing the extracted temporal features.
423
+ :rtype: ``pd.DataFrame``
424
+
425
+ .. code-block:: python3
426
+
427
+ import pm4py
428
+
429
+ temporal_features_df = pm4py.extract_temporal_features_dataframe(
430
+ dataframe,
431
+ activity_key='concept:name',
432
+ case_id_key='case:concept:name',
433
+ timestamp_key='time:timestamp'
434
+ )
435
+ """
436
+ __event_log_deprecation_warning(log)
437
+
438
+ parameters = get_properties(
439
+ log,
440
+ activity_key=activity_key,
441
+ timestamp_key=timestamp_key,
442
+ case_id_key=case_id_key,
443
+ )
444
+
445
+ parameters["grouper_freq"] = grouper_freq
446
+ parameters["pm4py:param:activity_key"] = activity_key
447
+ parameters["pm4py:param:timestamp_key"] = timestamp_key
448
+ if case_id_key is not None:
449
+ parameters["pm4py:param:case_id_key"] = case_id_key
450
+ parameters["pm4py:param:start_timestamp_key"] = (
451
+ start_timestamp_key
452
+ )
453
+ parameters["pm4py:param:resource_key"] = resource_key
454
+
455
+ if is_polars_lazyframe(log):
456
+ from pm4py.algo.transformation.trace_encodings.variants import temporal_lazy as temporal
457
+ else:
458
+ from pm4py.algo.transformation.trace_encodings.variants import temporal
459
+
460
+ return temporal.apply(log, parameters=parameters)
461
+
462
+
463
+ def extract_target_vector(
464
+ log: Union[EventLog, pd.DataFrame],
465
+ variant: str,
466
+ activity_key: str = "concept:name",
467
+ timestamp_key: str = "time:timestamp",
468
+ case_id_key: str = "case:concept:name",
469
+ ) -> Tuple[Any, List[str]]:
470
+ """
471
+ Extracts the target vector from a log object for a specific machine learning use case.
472
+
473
+ Supported variants include:
474
+
475
+ - 'next_activity': Predicts the next activity in a case.
476
+ - 'next_time': Predicts the timestamp of the next activity.
477
+ - 'remaining_time': Predicts the remaining time for the case.
478
+
479
+ :param log: The event log or Pandas DataFrame from which to extract the target vector.
480
+ :param variant: The variant of the algorithm to use. Must be one of:
481
+ 'next_activity', 'next_time', 'remaining_time'.
482
+ :param activity_key: Attribute to be used as the activity identifier.
483
+ :param timestamp_key: Attribute to be used for timestamps.
484
+ :param case_id_key: Attribute to be used as the case identifier.
485
+ :return: A tuple containing the target vector and a list of class labels (if applicable).
486
+ :rtype: ``Tuple[Any, List[str]]``
487
+
488
+ :raises Exception: If an unsupported variant is provided.
489
+
490
+ .. code-block:: python3
491
+
492
+ import pm4py
493
+
494
+ vector_next_act, class_next_act = pm4py.extract_target_vector(
495
+ log,
496
+ 'next_activity',
497
+ activity_key='concept:name',
498
+ timestamp_key='time:timestamp',
499
+ case_id_key='case:concept:name'
500
+ )
501
+ vector_next_time, class_next_time = pm4py.extract_target_vector(
502
+ log,
503
+ 'next_time',
504
+ activity_key='concept:name',
505
+ timestamp_key='time:timestamp',
506
+ case_id_key='case:concept:name'
507
+ )
508
+ vector_rem_time, class_rem_time = pm4py.extract_target_vector(
509
+ log,
510
+ 'remaining_time',
511
+ activity_key='concept:name',
512
+ timestamp_key='time:timestamp',
513
+ case_id_key='case:concept:name'
514
+ )
515
+ """
516
+ __event_log_deprecation_warning(log)
517
+
518
+ parameters = get_properties(
519
+ log,
520
+ activity_key=activity_key,
521
+ timestamp_key=timestamp_key,
522
+ case_id_key=case_id_key,
523
+ )
524
+
525
+ from pm4py.algo.transformation.log_to_target import (
526
+ algorithm as log_to_target,
527
+ )
528
+
529
+ var_map = {
530
+ "next_activity": log_to_target.Variants.NEXT_ACTIVITY,
531
+ "next_time": log_to_target.Variants.NEXT_TIME,
532
+ "remaining_time": log_to_target.Variants.REMAINING_TIME,
533
+ }
534
+
535
+ if variant not in var_map:
536
+ raise Exception(
537
+ "Please provide the variant as one of the following: 'next_activity', 'next_time', 'remaining_time'."
538
+ )
539
+
540
+ target, classes = log_to_target.apply(
541
+ log, variant=var_map[variant], parameters=parameters
542
+ )
543
+ return target, classes
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/__init__.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.util import constants as pm4_constants
23
+
24
+ if pm4_constants.ENABLE_INTERNAL_IMPORTS:
25
+ from pm4py.objects import (
26
+ log,
27
+ petri_net,
28
+ transition_system,
29
+ conversion,
30
+ process_tree,
31
+ dfg,
32
+ trie,
33
+ org,
34
+ heuristics_net,
35
+ genetic_matrix,
36
+ ocel,
37
+ powl,
38
+ random_variables,
39
+ )
40
+ import importlib.util
41
+
42
+ if importlib.util.find_spec("networkx"):
43
+ from pm4py.objects import bpmn
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.util import constants as pm4_constants
23
+
24
+ if pm4_constants.ENABLE_INTERNAL_IMPORTS:
25
+ from pm4py.objects.bpmn import obj, exporter, layout, semantics, util
26
+ import importlib.util
27
+
28
+ if importlib.util.find_spec("lxml"):
29
+ from pm4py.objects.bpmn import importer
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.objects.bpmn.exporter import exporter, variants
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/exporter.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from enum import Enum
23
+
24
+ from pm4py.objects.bpmn.exporter.variants import etree
25
+ from pm4py.util import exec_utils
26
+
27
+
28
+ class Variants(Enum):
29
+ ETREE = etree
30
+
31
+
32
+ DEFAULT_VARIANT = Variants.ETREE
33
+
34
+
35
+ def apply(bpmn_graph, target_path, variant=DEFAULT_VARIANT, parameters=None):
36
+ """
37
+ Exports the BPMN diagram to a file
38
+
39
+ Parameters
40
+ -------------
41
+ bpmn_graph
42
+ BPMN diagram
43
+ target_path
44
+ Target path
45
+ variant
46
+ Variant of the algorithm to use, possible values:
47
+ - Variants.ETREE
48
+ parameters
49
+ Possible parameters of the algorithm
50
+ """
51
+ if parameters is None:
52
+ parameters = {}
53
+
54
+ return exec_utils.get_variant(variant).apply(
55
+ bpmn_graph, target_path, parameters=parameters
56
+ )
57
+
58
+
59
+ def serialize(bpmn_graph, variant=DEFAULT_VARIANT, parameters=None):
60
+ """
61
+ Serializes the BPMN object into a binary string
62
+
63
+ Parameters
64
+ -------------
65
+ bpmn_graph
66
+ BPMN diagram
67
+ variant
68
+ Variant of the algorithm to use, possible values:
69
+ - Variants.ETREE
70
+ parameters
71
+ Possible parameters of the algorithm
72
+
73
+ Returns
74
+ -------------
75
+ serialization
76
+ Binary string (BPMN 2.0 XML standard)
77
+ """
78
+ if parameters is None:
79
+ parameters = {}
80
+
81
+ return exec_utils.get_variant(variant).get_xml_string(
82
+ bpmn_graph, parameters=parameters
83
+ )
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/variants/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.objects.bpmn.exporter.variants import etree
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/exporter/variants/etree.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ import uuid
23
+
24
+ from pm4py.objects.bpmn.obj import BPMN
25
+ from pm4py.util import constants, exec_utils
26
+ from enum import Enum
27
+
28
+
29
+ class Parameters(Enum):
30
+ ENCODING = "encoding"
31
+ ENABLE_BPMN_PLANE_EXPORTING = "enble_bpmn_plane_exporting"
32
+ ENABLE_INCOMING_OUTGOING_EXPORTING = "enable_incoming_outgoing_exporting"
33
+
34
+
35
+ def apply(bpmn_graph, target_path, parameters=None):
36
+ """
37
+ Exports the BPMN diagram to a file
38
+
39
+ Parameters
40
+ -------------
41
+ bpmn_graph
42
+ BPMN diagram
43
+ target_path
44
+ Target path
45
+ parameters
46
+ Possible parameters of the algorithm
47
+ """
48
+ xml_string = get_xml_string(bpmn_graph, parameters=parameters)
49
+ F = open(target_path, "wb")
50
+ F.write(xml_string)
51
+ F.close()
52
+
53
+
54
+ def get_xml_string(bpmn_graph, parameters=None):
55
+ if parameters is None:
56
+ parameters = {}
57
+
58
+ encoding = exec_utils.get_param_value(
59
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
60
+ )
61
+ enble_bpmn_plane_exporting = exec_utils.get_param_value(
62
+ Parameters.ENABLE_BPMN_PLANE_EXPORTING, parameters, True
63
+ )
64
+ enable_incoming_outgoing_exporting = exec_utils.get_param_value(
65
+ Parameters.ENABLE_INCOMING_OUTGOING_EXPORTING, parameters, True
66
+ )
67
+
68
+ layout = bpmn_graph.get_layout()
69
+
70
+ import xml.etree.ElementTree as ET
71
+ from xml.dom import minidom
72
+
73
+ definitions = ET.Element("bpmn:definitions")
74
+ definitions.set(
75
+ "xmlns:bpmn", "http://www.omg.org/spec/BPMN/20100524/MODEL"
76
+ )
77
+ definitions.set("xmlns:bpmndi", "http://www.omg.org/spec/BPMN/20100524/DI")
78
+ definitions.set("xmlns:omgdc", "http://www.omg.org/spec/DD/20100524/DC")
79
+ definitions.set("xmlns:omgdi", "http://www.omg.org/spec/DD/20100524/DI")
80
+ definitions.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
81
+ definitions.set("targetNamespace", "http://www.signavio.com/bpmn20")
82
+ definitions.set("typeLanguage", "http://www.w3.org/2001/XMLSchema")
83
+ definitions.set("expressionLanguage", "http://www.w3.org/1999/XPath")
84
+ definitions.set("xmlns:xsd", "http://www.w3.org/2001/XMLSchema")
85
+
86
+ all_processes = set()
87
+ process_planes = {}
88
+ process_process = {}
89
+ process_collaboration = None
90
+
91
+ for node in bpmn_graph.get_nodes():
92
+ all_processes.add(node.get_process())
93
+ for flow in bpmn_graph.get_flows():
94
+ all_processes.add(flow.get_process())
95
+
96
+ if len(all_processes) > 1:
97
+ # when several swimlanes exist, their elements should be annexed to the
98
+ # same BPMN plane
99
+ collaboration_nodes = [
100
+ x
101
+ for x in bpmn_graph.get_nodes()
102
+ if isinstance(x, BPMN.Collaboration)
103
+ ]
104
+ if collaboration_nodes:
105
+ bpmn_plane_id = collaboration_nodes[0].get_id()
106
+
107
+ process_collaboration = ET.SubElement(
108
+ definitions, "bpmn:collaboration", {"id": bpmn_plane_id}
109
+ )
110
+
111
+ participant_nodes = [
112
+ x
113
+ for x in bpmn_graph.get_nodes()
114
+ if isinstance(x, BPMN.Participant)
115
+ ]
116
+ if participant_nodes:
117
+ for process in participant_nodes:
118
+ ET.SubElement(
119
+ process_collaboration,
120
+ "bpmn:participant",
121
+ {
122
+ "id": process.get_id(),
123
+ "name": process.get_name(),
124
+ "processRef": "id" + process.process_ref,
125
+ },
126
+ )
127
+ all_processes.add(process.process_ref)
128
+ else:
129
+ bpmn_plane_id = "id" + list(all_processes)[0]
130
+
131
+ for process in all_processes:
132
+ if process != bpmn_plane_id:
133
+ p = ET.SubElement(
134
+ definitions,
135
+ "bpmn:process",
136
+ {
137
+ "id": "id" + process,
138
+ "isClosed": "false",
139
+ "isExecutable": "false",
140
+ "processType": "None",
141
+ },
142
+ )
143
+ process_process[process] = p
144
+ elif process_collaboration is not None:
145
+ process_process[process] = process_collaboration
146
+
147
+ diagram = ET.SubElement(
148
+ definitions,
149
+ "bpmndi:BPMNDiagram",
150
+ {"id": "id" + str(uuid.uuid4()), "name": "diagram"},
151
+ )
152
+
153
+ if enble_bpmn_plane_exporting:
154
+ plane = ET.SubElement(
155
+ diagram,
156
+ "bpmndi:BPMNPlane",
157
+ {"bpmnElement": bpmn_plane_id, "id": "id" + str(uuid.uuid4())},
158
+ )
159
+ for process in all_processes:
160
+ process_planes[process] = plane
161
+
162
+ for node in bpmn_graph.get_nodes():
163
+ process = node.get_process()
164
+
165
+ if process != bpmn_plane_id:
166
+ node_shape = ET.SubElement(
167
+ process_planes[process],
168
+ "bpmndi:BPMNShape",
169
+ {
170
+ "bpmnElement": node.get_id(),
171
+ "id": node.get_id() + "_gui",
172
+ },
173
+ )
174
+ node_shape_layout = ET.SubElement(
175
+ node_shape,
176
+ "omgdc:Bounds",
177
+ {
178
+ "height": str(layout.get(node).get_height()),
179
+ "width": str(layout.get(node).get_width()),
180
+ "x": str(layout.get(node).get_x()),
181
+ "y": str(layout.get(node).get_y()),
182
+ },
183
+ )
184
+
185
+ for flow in bpmn_graph.get_flows():
186
+ process = flow.get_process()
187
+
188
+ flow_shape = ET.SubElement(
189
+ process_planes[process],
190
+ "bpmndi:BPMNEdge",
191
+ {
192
+ "bpmnElement": "id" + str(flow.get_id()),
193
+ "id": "id" + str(flow.get_id()) + "_gui",
194
+ },
195
+ )
196
+ for x, y in layout.get(flow).get_waypoints():
197
+ waypoint = ET.SubElement(
198
+ flow_shape, "omgdi:waypoint", {"x": str(x), "y": str(y)}
199
+ )
200
+
201
+ for node in bpmn_graph.get_nodes():
202
+ process = process_process[node.get_process()]
203
+
204
+ if isinstance(node, BPMN.TextAnnotation):
205
+ annotation = ET.SubElement(
206
+ process, "bpmn:textAnnotation", {"id": node.get_id()}
207
+ )
208
+ text = ET.SubElement(annotation, "bpmn:text")
209
+ text.text = node.text
210
+ elif isinstance(node, BPMN.StartEvent):
211
+ isInterrupting = "true" if node.get_isInterrupting() else "false"
212
+ parallelMultiple = (
213
+ "true" if node.get_parallelMultiple() else "false"
214
+ )
215
+ task = ET.SubElement(
216
+ process,
217
+ "bpmn:startEvent",
218
+ {
219
+ "id": node.get_id(),
220
+ "isInterrupting": isInterrupting,
221
+ "name": node.get_name(),
222
+ "parallelMultiple": parallelMultiple,
223
+ },
224
+ )
225
+ elif isinstance(node, BPMN.EndEvent):
226
+ task = ET.SubElement(
227
+ process,
228
+ "bpmn:endEvent",
229
+ {"id": node.get_id(), "name": node.get_name()},
230
+ )
231
+ elif isinstance(node, BPMN.IntermediateCatchEvent):
232
+ task = ET.SubElement(
233
+ process,
234
+ "bpmn:intermediateCatchEvent",
235
+ {"id": node.get_id(), "name": node.get_name()},
236
+ )
237
+ messageEventDefinition = ET.SubElement(
238
+ task, "bpmn:messageEventDefinition"
239
+ )
240
+ elif isinstance(node, BPMN.IntermediateThrowEvent):
241
+ task = ET.SubElement(
242
+ process,
243
+ "bpmn:intermediateThrowEvent",
244
+ {"id": node.get_id(), "name": node.get_name()},
245
+ )
246
+ elif isinstance(node, BPMN.BoundaryEvent):
247
+ task = ET.SubElement(
248
+ process,
249
+ "bpmn:boundaryEvent",
250
+ {"id": node.get_id(), "name": node.get_name()},
251
+ )
252
+ elif isinstance(node, BPMN.Task):
253
+ if isinstance(node, BPMN.UserTask):
254
+ task = ET.SubElement(
255
+ process,
256
+ "bpmn:userTask",
257
+ {"id": node.get_id(), "name": node.get_name()},
258
+ )
259
+ elif isinstance(node, BPMN.SendTask):
260
+ task = ET.SubElement(
261
+ process,
262
+ "bpmn:sendTask",
263
+ {"id": node.get_id(), "name": node.get_name()},
264
+ )
265
+ else:
266
+ task = ET.SubElement(
267
+ process,
268
+ "bpmn:task",
269
+ {"id": node.get_id(), "name": node.get_name()},
270
+ )
271
+ elif isinstance(node, BPMN.SubProcess):
272
+ task = ET.SubElement(
273
+ process,
274
+ "bpmn:subProcess",
275
+ {"id": node.get_id(), "name": node.get_name()},
276
+ )
277
+ elif isinstance(node, BPMN.ExclusiveGateway):
278
+ task = ET.SubElement(
279
+ process,
280
+ "bpmn:exclusiveGateway",
281
+ {
282
+ "id": node.get_id(),
283
+ "gatewayDirection": node.get_gateway_direction().value,
284
+ "name": node.get_name(),
285
+ },
286
+ )
287
+ elif isinstance(node, BPMN.ParallelGateway):
288
+ task = ET.SubElement(
289
+ process,
290
+ "bpmn:parallelGateway",
291
+ {
292
+ "id": node.get_id(),
293
+ "gatewayDirection": node.get_gateway_direction().value,
294
+ "name": node.get_name(),
295
+ },
296
+ )
297
+ elif isinstance(node, BPMN.InclusiveGateway):
298
+ task = ET.SubElement(
299
+ process,
300
+ "bpmn:inclusiveGateway",
301
+ {
302
+ "id": node.get_id(),
303
+ "gatewayDirection": node.get_gateway_direction().value,
304
+ "name": node.get_name(),
305
+ },
306
+ )
307
+ elif isinstance(node, BPMN.EventBasedGateway):
308
+ task = ET.SubElement(
309
+ process,
310
+ "bpmn:eventBasedGateway",
311
+ {
312
+ "id": node.get_id(),
313
+ "gatewayDirection": node.get_gateway_direction().value,
314
+ "name": node.get_name(),
315
+ },
316
+ )
317
+
318
+ if enable_incoming_outgoing_exporting:
319
+ for in_arc in node.get_in_arcs():
320
+ arc_xml = ET.SubElement(task, "bpmn:incoming")
321
+ arc_xml.text = "id" + str(in_arc.get_id())
322
+
323
+ for out_arc in node.get_out_arcs():
324
+ arc_xml = ET.SubElement(task, "bpmn:outgoing")
325
+ arc_xml.text = "id" + str(out_arc.get_id())
326
+
327
+ for flow in bpmn_graph.get_flows():
328
+ process = process_process[flow.get_process()]
329
+
330
+ source = flow.get_source()
331
+ target = flow.get_target()
332
+
333
+ if isinstance(flow, BPMN.SequenceFlow):
334
+ flow_xml = ET.SubElement(
335
+ process,
336
+ "bpmn:sequenceFlow",
337
+ {
338
+ "id": "id" + str(flow.get_id()),
339
+ "name": flow.get_name(),
340
+ "sourceRef": str(source.get_id()),
341
+ "targetRef": str(target.get_id()),
342
+ },
343
+ )
344
+ elif isinstance(flow, BPMN.MessageFlow):
345
+ flow_xml = ET.SubElement(
346
+ process,
347
+ "bpmn:messageFlow",
348
+ {
349
+ "id": "id" + str(flow.get_id()),
350
+ "name": flow.get_name(),
351
+ "sourceRef": str(source.get_id()),
352
+ "targetRef": str(target.get_id()),
353
+ },
354
+ )
355
+
356
+ elif isinstance(flow, BPMN.Association):
357
+ flow_xml = ET.SubElement(
358
+ process,
359
+ "bpmn:association",
360
+ {
361
+ "id": "id" + str(flow.get_id()),
362
+ "sourceRef": str(source.get_id()),
363
+ "targetRef": str(target.get_id()),
364
+ },
365
+ )
366
+
367
+ return minidom.parseString(ET.tostring(definitions)).toprettyxml(
368
+ encoding=encoding
369
+ )
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.objects.bpmn.importer import importer, variants
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/importer.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from enum import Enum
23
+
24
+ from pm4py.objects.bpmn.importer.variants import lxml
25
+ from pm4py.util import exec_utils
26
+
27
+
28
+ class Variants(Enum):
29
+ LXML = lxml
30
+
31
+
32
+ DEFAULT_VARIANT = Variants.LXML
33
+
34
+
35
+ def apply(path, variant=DEFAULT_VARIANT, parameters=None):
36
+ """
37
+ Imports a BPMN diagram from a file
38
+
39
+ Parameters
40
+ -------------
41
+ path
42
+ Path to the file
43
+ variant
44
+ Variant of the algorithm to use, possible values:
45
+ - Variants.LXML
46
+ parameters
47
+ Parameters of the algorithm
48
+
49
+ Returns
50
+ -------------
51
+ bpmn_graph
52
+ BPMN graph
53
+ """
54
+ if parameters is None:
55
+ parameters = {}
56
+
57
+ return exec_utils.get_variant(variant).apply(path, parameters=parameters)
58
+
59
+
60
+ def deserialize(bpmn_string, variant=DEFAULT_VARIANT, parameters=None):
61
+ """
62
+ Deserialize a text/binary string representing a BPMN 2.0
63
+
64
+ Parameters
65
+ -------------
66
+ bpmn_string
67
+ BPMN string
68
+ variant
69
+ Variant of the algorithm to use, possible values:
70
+ - Variants.LXML
71
+ parameters
72
+ Parameters of the algorithm
73
+
74
+ Returns
75
+ -------------
76
+ bpmn_graph
77
+ BPMN graph
78
+ """
79
+ if parameters is None:
80
+ parameters = {}
81
+
82
+ return exec_utils.get_variant(variant).import_from_string(
83
+ bpmn_string, parameters=parameters
84
+ )
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/variants/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.objects.bpmn.importer.variants import lxml
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/importer/variants/lxml.py ADDED
@@ -0,0 +1,736 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.objects.bpmn.obj import BPMN
23
+ from pm4py.util import constants, exec_utils
24
+ from enum import Enum
25
+
26
+
27
+ class Parameters(Enum):
28
+ ENCODING = "encoding"
29
+
30
+
31
+ class Counts:
32
+ def __init__(self):
33
+ self.number_processes = 0
34
+
35
+
36
+ def parse_element(
37
+ bpmn_graph,
38
+ counts,
39
+ curr_el,
40
+ parents,
41
+ incoming_dict,
42
+ outgoing_dict,
43
+ nodes_dict,
44
+ nodes_bounds,
45
+ flow_info,
46
+ process=None,
47
+ node=None,
48
+ bpmn_element=None,
49
+ flow=None,
50
+ rec_depth=0,
51
+ ):
52
+ """
53
+ Parses a BPMN element from the XML file
54
+ """
55
+ layout = bpmn_graph.get_layout()
56
+ tag = curr_el.tag.lower()
57
+
58
+ if curr_el.get("id") is not None:
59
+ if tag.endswith("collaboration"):
60
+ collaboration_id = curr_el.get("id")
61
+ collaboration = BPMN.Collaboration(
62
+ id=collaboration_id, process=collaboration_id
63
+ )
64
+ bpmn_graph.add_node(collaboration)
65
+ nodes_dict[collaboration_id] = collaboration
66
+ elif tag.endswith("participant"):
67
+ participant_id = curr_el.get("id")
68
+ name = (
69
+ curr_el.get("name").replace("\r", "").replace("\n", "")
70
+ if "name" in curr_el.attrib
71
+ else ""
72
+ )
73
+ process_ref = curr_el.get("processRef")
74
+ participant = BPMN.Participant(
75
+ id=participant_id,
76
+ name=name,
77
+ process=None,
78
+ process_ref=process_ref,
79
+ )
80
+ bpmn_graph.add_node(participant)
81
+ nodes_dict[participant_id] = participant
82
+ elif tag.endswith("textannotation"):
83
+ annotation_id = curr_el.get("id")
84
+ text = ""
85
+ for child in curr_el:
86
+ text = child.text
87
+ annotation = BPMN.TextAnnotation(
88
+ id=annotation_id, text=text, process=process
89
+ )
90
+ bpmn_graph.add_node(annotation)
91
+ nodes_dict[annotation_id] = annotation
92
+ elif tag.endswith("subprocess"): # subprocess invocation
93
+ name = (
94
+ curr_el.get("name").replace("\r", "").replace("\n", "")
95
+ if "name" in curr_el.attrib
96
+ else ""
97
+ )
98
+ subprocess = BPMN.SubProcess(
99
+ id=curr_el.get("id"),
100
+ name=name,
101
+ process=process,
102
+ depth=rec_depth,
103
+ )
104
+ bpmn_graph.add_node(subprocess)
105
+ node = subprocess
106
+ process = curr_el.get("id")
107
+ nodes_dict[process] = node
108
+ elif tag.endswith("process"): # process of the current subtree
109
+ process = curr_el.get("id")
110
+ name = (
111
+ curr_el.get("name").replace("\r", "").replace("\n", "")
112
+ if "name" in curr_el.attrib
113
+ else ""
114
+ )
115
+ bpmn_graph.set_process_id(process)
116
+ bpmn_graph.set_name(name)
117
+ elif tag.endswith(
118
+ "shape"
119
+ ): # shape of a node, contains x,y,width,height information
120
+ bpmn_element = curr_el.get("bpmnElement")
121
+ elif tag.endswith("task"): # simple task object
122
+ id = curr_el.get("id")
123
+ name = (
124
+ curr_el.get("name").replace("\r", "").replace("\n", "")
125
+ if "name" in curr_el.attrib
126
+ else ""
127
+ )
128
+ # this_type = str(curr_el.tag)
129
+ # this_type = this_type[this_type.index("}") + 1:]
130
+ if tag.endswith("usertask"):
131
+ task = BPMN.UserTask(id=id, name=name, process=process)
132
+ elif tag.endswith("sendtask"):
133
+ task = BPMN.SendTask(id=id, name=name, process=process)
134
+ else:
135
+ task = BPMN.Task(id=id, name=name, process=process)
136
+ bpmn_graph.add_node(task)
137
+ node = task
138
+ nodes_dict[id] = node
139
+ elif tag.endswith(
140
+ "startevent"
141
+ ): # start node starting the (sub)process
142
+ id = curr_el.get("id")
143
+ name = (
144
+ curr_el.get("name").replace("\r", " ").replace("\n", " ")
145
+ if "name" in curr_el.attrib
146
+ else ""
147
+ )
148
+ event_definitions = [
149
+ child.tag.lower().replace("eventdefinition", "")
150
+ for child in curr_el
151
+ if child.tag.lower().endswith("eventdefinition")
152
+ ]
153
+ if len(event_definitions) > 0:
154
+ event_type = event_definitions[0]
155
+ if event_type.endswith("message"):
156
+ start_event = BPMN.MessageStartEvent(
157
+ id=curr_el.get("id"), name=name, process=process
158
+ )
159
+ else: # TODO: expand functionality, support more start event types
160
+ start_event = BPMN.NormalStartEvent(
161
+ id=curr_el.get("id"), name=name, process=process
162
+ )
163
+ else:
164
+ start_event = BPMN.NormalStartEvent(
165
+ id=curr_el.get("id"), name=name, process=process
166
+ )
167
+ bpmn_graph.add_node(start_event)
168
+ node = start_event
169
+ nodes_dict[id] = node
170
+ elif tag.endswith("endevent"): # end node ending the (sub)process
171
+ id = curr_el.get("id")
172
+ name = (
173
+ curr_el.get("name").replace("\r", " ").replace("\n", " ")
174
+ if "name" in curr_el.attrib
175
+ else ""
176
+ )
177
+ event_definitions = [
178
+ child.tag.lower().replace("eventdefinition", "")
179
+ for child in curr_el
180
+ if child.tag.lower().endswith("eventdefinition")
181
+ ]
182
+ if len(event_definitions) > 0:
183
+ event_type = event_definitions[0]
184
+ if event_type.endswith("message"):
185
+ end_event = BPMN.MessageEndEvent(
186
+ id=curr_el.get("id"), name=name, process=process
187
+ )
188
+ elif event_type.endswith("terminate"):
189
+ end_event = BPMN.TerminateEndEvent(
190
+ id=curr_el.get("id"), name=name, process=process
191
+ )
192
+ elif event_type.endswith("error"):
193
+ end_event = BPMN.ErrorEndEvent(
194
+ id=curr_el.get("id"), name=name, process=process
195
+ )
196
+ elif event_type.endswith("cancel"):
197
+ end_event = BPMN.CancelEndEvent(
198
+ id=curr_el.get("id"), name=name, process=process
199
+ )
200
+ else: # TODO: expand functionality, support more start event types
201
+ end_event = BPMN.NormalEndEvent(
202
+ id=curr_el.get("id"), name=name, process=process
203
+ )
204
+ else:
205
+ end_event = BPMN.NormalEndEvent(
206
+ id=curr_el.get("id"), name=name, process=process
207
+ )
208
+ bpmn_graph.add_node(end_event)
209
+ node = end_event
210
+ nodes_dict[id] = node
211
+ elif tag.endswith(
212
+ "intermediatecatchevent"
213
+ ): # intermediate event that happens (externally) and can be catched
214
+ id = curr_el.get("id")
215
+ name = (
216
+ curr_el.get("name").replace("\r", " ").replace("\n", " ")
217
+ if "name" in curr_el.attrib
218
+ else ""
219
+ )
220
+ event_definitions = [
221
+ child.tag.lower().replace("eventdefinition", "")
222
+ for child in curr_el
223
+ if child.tag.lower().endswith("eventdefinition")
224
+ ]
225
+ if len(event_definitions) > 0:
226
+ event_type = event_definitions[0]
227
+ if event_type.endswith("message"):
228
+ intermediate_catch_event = (
229
+ BPMN.MessageIntermediateCatchEvent(
230
+ id=curr_el.get("id"), name=name, process=process
231
+ )
232
+ )
233
+ elif event_type.endswith("error"):
234
+ intermediate_catch_event = (
235
+ BPMN.ErrorIntermediateCatchEvent(
236
+ id=curr_el.get("id"), name=name, process=process
237
+ )
238
+ )
239
+ elif event_type.endswith("cancel"):
240
+ intermediate_catch_event = (
241
+ BPMN.CancelIntermediateCatchEvent(
242
+ id=curr_el.get("id"), name=name, process=process
243
+ )
244
+ )
245
+ else:
246
+ intermediate_catch_event = BPMN.IntermediateCatchEvent(
247
+ id=curr_el.get("id"), name=name, process=process
248
+ )
249
+ else:
250
+ intermediate_catch_event = BPMN.IntermediateCatchEvent(
251
+ id=curr_el.get("id"), name=name, process=process
252
+ )
253
+ bpmn_graph.add_node(intermediate_catch_event)
254
+ node = intermediate_catch_event
255
+ nodes_dict[id] = node
256
+ elif tag.endswith(
257
+ "intermediatethrowevent"
258
+ ): # intermediate event that is activated through the (sub)process
259
+ id = curr_el.get("id")
260
+ name = (
261
+ curr_el.get("name").replace("\r", " ").replace("\n", " ")
262
+ if "name" in curr_el.attrib
263
+ else ""
264
+ )
265
+ event_definitions = [
266
+ child.tag.lower().replace("eventdefinition", "")
267
+ for child in curr_el
268
+ if child.tag.lower().endswith("eventdefinition")
269
+ ]
270
+ if len(event_definitions) > 0:
271
+ event_type = event_definitions[0]
272
+ if event_type.endswith("message"):
273
+ intermediate_throw_event = (
274
+ BPMN.MessageIntermediateThrowEvent(
275
+ id=curr_el.get("id"), name=name, process=process
276
+ )
277
+ )
278
+ else:
279
+ intermediate_throw_event = (
280
+ BPMN.NormalIntermediateThrowEvent(
281
+ id=curr_el.get("id"), name=name, process=process
282
+ )
283
+ )
284
+ else:
285
+ intermediate_throw_event = BPMN.NormalIntermediateThrowEvent(
286
+ id=curr_el.get("id"), name=name, process=process
287
+ )
288
+ bpmn_graph.add_node(intermediate_throw_event)
289
+ node = intermediate_throw_event
290
+ nodes_dict[id] = node
291
+ elif tag.endswith("boundaryevent"):
292
+ id = curr_el.get("id")
293
+ ref_activity = curr_el.get("attachedToRef")
294
+ name = (
295
+ curr_el.get("name").replace("\r", " ").replace("\n", " ")
296
+ if "name" in curr_el.attrib
297
+ else ""
298
+ )
299
+ event_definitions = [
300
+ child.tag.lower().replace("eventdefinition", "")
301
+ for child in curr_el
302
+ if child.tag.lower().endswith("eventdefinition")
303
+ ]
304
+ if len(event_definitions) > 0:
305
+ event_type = event_definitions[0]
306
+ if event_type.endswith("message"):
307
+ boundary_event = BPMN.MessageBoundaryEvent(
308
+ id=curr_el.get("id"),
309
+ name=name,
310
+ process=process,
311
+ activity=ref_activity,
312
+ )
313
+ elif event_type.endswith("error"):
314
+ boundary_event = BPMN.ErrorBoundaryEvent(
315
+ id=curr_el.get("id"),
316
+ name=name,
317
+ process=process,
318
+ activity=ref_activity,
319
+ )
320
+ elif event_type.endswith("cancel"):
321
+ boundary_event = BPMN.CancelBoundaryEvent(
322
+ id=curr_el.get("id"),
323
+ name=name,
324
+ process=process,
325
+ activity=ref_activity,
326
+ )
327
+ else:
328
+ boundary_event = BPMN.BoundaryEvent(
329
+ id=curr_el.get("id"),
330
+ name=name,
331
+ process=process,
332
+ activity=ref_activity,
333
+ )
334
+ else:
335
+ boundary_event = BPMN.BoundaryEvent(
336
+ id=curr_el.get("id"),
337
+ name=name,
338
+ process=process,
339
+ activity=ref_activity,
340
+ )
341
+ bpmn_graph.add_node(boundary_event)
342
+ node = boundary_event
343
+ nodes_dict[id] = node
344
+ elif tag.endswith("edge"): # related to the x, y information of an arc
345
+ bpmnElement = curr_el.get("bpmnElement")
346
+ flow = bpmnElement
347
+ elif tag.endswith("exclusivegateway"):
348
+ id = curr_el.get("id")
349
+ name = (
350
+ curr_el.get("name").replace("\r", "").replace("\n", "")
351
+ if "name" in curr_el.attrib
352
+ else ""
353
+ )
354
+ try:
355
+ direction = BPMN.Gateway.Direction[
356
+ curr_el.get("gatewayDirection").upper()
357
+ ]
358
+ exclusive_gateway = BPMN.ExclusiveGateway(
359
+ id=curr_el.get("id"),
360
+ name=name,
361
+ gateway_direction=direction,
362
+ process=process,
363
+ )
364
+ except BaseException:
365
+ exclusive_gateway = BPMN.ExclusiveGateway(
366
+ id=curr_el.get("id"),
367
+ name=name,
368
+ gateway_direction=BPMN.Gateway.Direction.UNSPECIFIED,
369
+ process=process,
370
+ )
371
+ bpmn_graph.add_node(exclusive_gateway)
372
+ node = exclusive_gateway
373
+ nodes_dict[id] = node
374
+ elif tag.endswith("parallelgateway"):
375
+ id = curr_el.get("id")
376
+ name = (
377
+ curr_el.get("name").replace("\r", "").replace("\n", "")
378
+ if "name" in curr_el.attrib
379
+ else ""
380
+ )
381
+ try:
382
+ direction = BPMN.Gateway.Direction[
383
+ curr_el.get("gatewayDirection").upper()
384
+ ]
385
+ parallel_gateway = BPMN.ParallelGateway(
386
+ id=curr_el.get("id"),
387
+ name=name,
388
+ gateway_direction=direction,
389
+ process=process,
390
+ )
391
+ except BaseException:
392
+ parallel_gateway = BPMN.ParallelGateway(
393
+ id=curr_el.get("id"),
394
+ name=name,
395
+ gateway_direction=BPMN.Gateway.Direction.UNSPECIFIED,
396
+ process=process,
397
+ )
398
+ bpmn_graph.add_node(parallel_gateway)
399
+ node = parallel_gateway
400
+ nodes_dict[id] = node
401
+ elif tag.endswith("inclusivegateway"):
402
+ id = curr_el.get("id")
403
+ name = (
404
+ curr_el.get("name").replace("\r", "").replace("\n", "")
405
+ if "name" in curr_el.attrib
406
+ else ""
407
+ )
408
+ try:
409
+ direction = BPMN.Gateway.Direction[
410
+ curr_el.get("gatewayDirection").upper()
411
+ ]
412
+ inclusive_gateway = BPMN.InclusiveGateway(
413
+ id=curr_el.get("id"),
414
+ name=name,
415
+ gateway_direction=direction,
416
+ process=process,
417
+ )
418
+ except BaseException:
419
+ inclusive_gateway = BPMN.InclusiveGateway(
420
+ id=curr_el.get("id"),
421
+ name=name,
422
+ gateway_direction=BPMN.Gateway.Direction.UNSPECIFIED,
423
+ process=process,
424
+ )
425
+ bpmn_graph.add_node(inclusive_gateway)
426
+ node = inclusive_gateway
427
+ nodes_dict[id] = node
428
+ elif tag.endswith("eventbasedgateway"):
429
+ id = curr_el.get("id")
430
+ name = (
431
+ curr_el.get("name").replace("\r", "").replace("\n", "")
432
+ if "name" in curr_el.attrib
433
+ else ""
434
+ )
435
+ try:
436
+ direction = BPMN.Gateway.Direction[
437
+ curr_el.get("gatewayDirection").upper()
438
+ ]
439
+ event_based_gateway = BPMN.EventBasedGateway(
440
+ id=curr_el.get("id"),
441
+ name=name,
442
+ gateway_direction=direction,
443
+ process=process,
444
+ )
445
+ except BaseException:
446
+ event_based_gateway = BPMN.EventBasedGateway(
447
+ id=curr_el.get("id"),
448
+ name=name,
449
+ gateway_direction=BPMN.Gateway.Direction.UNSPECIFIED,
450
+ process=process,
451
+ )
452
+ bpmn_graph.add_node(event_based_gateway)
453
+ node = event_based_gateway
454
+ nodes_dict[id] = node
455
+ # FIXED: Moved the flow handling inside the id block
456
+ elif (
457
+ tag.endswith("sequenceflow")
458
+ or tag.endswith("messageflow")
459
+ or tag.endswith("association")
460
+ ):
461
+ seq_flow_id = curr_el.get("id")
462
+ source_ref = curr_el.get("sourceRef")
463
+ target_ref = curr_el.get("targetRef")
464
+ name = (
465
+ curr_el.get("name").replace("\r", "").replace("\n", "")
466
+ if "name" in curr_el.attrib
467
+ else ""
468
+ )
469
+ if source_ref is not None and target_ref is not None:
470
+ incoming_dict[seq_flow_id] = (
471
+ target_ref,
472
+ process,
473
+ tag,
474
+ name,
475
+ parents,
476
+ )
477
+ outgoing_dict[seq_flow_id] = (
478
+ source_ref,
479
+ process,
480
+ tag,
481
+ name,
482
+ parents,
483
+ )
484
+ elif tag.endswith("incoming"): # incoming flow of a node
485
+ name = (
486
+ curr_el.get("name").replace("\r", "").replace("\n", "")
487
+ if "name" in curr_el.attrib
488
+ else ""
489
+ )
490
+ if node is not None:
491
+ if curr_el.text.strip() not in incoming_dict:
492
+ incoming_dict[curr_el.text.strip()] = (
493
+ node,
494
+ process,
495
+ tag,
496
+ name,
497
+ parents,
498
+ )
499
+ elif tag.endswith("outgoing"): # outgoing flow of a node
500
+ name = (
501
+ curr_el.get("name").replace("\r", "").replace("\n", "")
502
+ if "name" in curr_el.attrib
503
+ else ""
504
+ )
505
+ if node is not None:
506
+ if curr_el.text.strip() not in outgoing_dict:
507
+ outgoing_dict[curr_el.text.strip()] = (
508
+ node,
509
+ process,
510
+ tag,
511
+ name,
512
+ parents,
513
+ )
514
+ elif tag.endswith(
515
+ "waypoint"
516
+ ): # contains information of x, y values of an edge
517
+ if flow is not None:
518
+ x = float(curr_el.get("x"))
519
+ y = float(curr_el.get("y"))
520
+ if flow not in flow_info:
521
+ flow_info[flow] = []
522
+ flow_info[flow].append((x, y))
523
+ elif tag.endswith(
524
+ "label"
525
+ ): # label of a node, mostly at the end of a shape object
526
+ bpmn_element = None
527
+ elif tag.endswith(
528
+ "bounds"
529
+ ): # contains information of width, height, x, y of a node
530
+ if bpmn_element is not None:
531
+ x = float(curr_el.get("x"))
532
+ y = float(curr_el.get("y"))
533
+ width = float(curr_el.get("width"))
534
+ height = float(curr_el.get("height"))
535
+ nodes_bounds[bpmn_element] = {
536
+ "x": x,
537
+ "y": y,
538
+ "width": width,
539
+ "height": height,
540
+ }
541
+
542
+ for child in curr_el:
543
+ bpmn_graph = parse_element(
544
+ bpmn_graph,
545
+ counts,
546
+ child,
547
+ list(parents) + [child],
548
+ incoming_dict,
549
+ outgoing_dict,
550
+ nodes_dict,
551
+ nodes_bounds,
552
+ flow_info,
553
+ process=process,
554
+ node=node,
555
+ bpmn_element=bpmn_element,
556
+ flow=flow,
557
+ rec_depth=rec_depth + 1,
558
+ )
559
+ # afterprocessing when the xml tree has been recursively parsed already
560
+ if rec_depth == 0:
561
+ # bpmn_graph.set_process_id(process)
562
+ for seq_flow_id in incoming_dict:
563
+ if incoming_dict[seq_flow_id][0] in nodes_dict:
564
+ incoming_dict[seq_flow_id] = (
565
+ nodes_dict[incoming_dict[seq_flow_id][0]],
566
+ incoming_dict[seq_flow_id][1],
567
+ incoming_dict[seq_flow_id][2],
568
+ incoming_dict[seq_flow_id][3],
569
+ incoming_dict[seq_flow_id][4],
570
+ )
571
+ for seq_flow_id in outgoing_dict:
572
+ if outgoing_dict[seq_flow_id][0] in nodes_dict:
573
+ outgoing_dict[seq_flow_id] = (
574
+ nodes_dict[outgoing_dict[seq_flow_id][0]], outgoing_dict[seq_flow_id][1], outgoing_dict[seq_flow_id][2],
575
+ outgoing_dict[seq_flow_id][3], outgoing_dict[seq_flow_id][4])
576
+
577
+ # also supports flows without waypoints
578
+ flows_without_waypoints = set(flow_info).union(
579
+ set(outgoing_dict).intersection(set(incoming_dict))
580
+ )
581
+ for flow_id in flows_without_waypoints:
582
+ flow_info[flow_id] = []
583
+
584
+ for flow_id in flow_info:
585
+ if flow_id in outgoing_dict and flow_id in incoming_dict:
586
+ flow = None
587
+ flow_type = outgoing_dict[flow_id][2]
588
+
589
+ if flow_type.endswith("messageflow"):
590
+ collaboration_id = None
591
+ for par in outgoing_dict[flow_id][4]:
592
+ par_tag = str(par.tag).lower()
593
+ if par_tag.endswith("collaboration"):
594
+ collaboration_id = par.get("id")
595
+ flow = BPMN.MessageFlow(
596
+ outgoing_dict[flow_id][0],
597
+ incoming_dict[flow_id][0],
598
+ id=flow_id,
599
+ name=outgoing_dict[flow_id][3],
600
+ process=collaboration_id,
601
+ )
602
+ elif flow_type.endswith("association"):
603
+ flow = BPMN.Association(
604
+ outgoing_dict[flow_id][0],
605
+ incoming_dict[flow_id][0],
606
+ id=flow_id,
607
+ name=outgoing_dict[flow_id][3],
608
+ process=outgoing_dict[flow_id][1],
609
+ )
610
+ else:
611
+ flow = BPMN.SequenceFlow(
612
+ outgoing_dict[flow_id][0],
613
+ incoming_dict[flow_id][0],
614
+ id=flow_id,
615
+ name=outgoing_dict[flow_id][3],
616
+ process=outgoing_dict[flow_id][1],
617
+ )
618
+
619
+ if flow is not None:
620
+ bpmn_graph.add_flow(flow)
621
+ layout.get(flow).del_waypoints()
622
+ for waypoint in flow_info[flow_id]:
623
+ layout.get(flow).add_waypoint(waypoint)
624
+
625
+ for node_id in nodes_bounds:
626
+ if node_id in nodes_dict:
627
+ bounds = nodes_bounds[node_id]
628
+ node = nodes_dict[node_id]
629
+ layout.get(node).set_x(bounds["x"])
630
+ layout.get(node).set_y(bounds["y"])
631
+ layout.get(node).set_width(bounds["width"])
632
+ layout.get(node).set_height(bounds["height"])
633
+ return bpmn_graph
634
+
635
+
636
+ def import_xml_tree_from_root(root):
637
+ """
638
+ Imports a BPMN graph from (the root of) an XML tree
639
+
640
+ Parameters
641
+ -------------
642
+ root
643
+ Root of the tree
644
+
645
+ Returns
646
+ -------------
647
+ bpmn_graph
648
+ BPMN graph
649
+ """
650
+ bpmn_graph = BPMN()
651
+ counts = Counts()
652
+ incoming_dict = {}
653
+ outgoing_dict = {}
654
+ nodes_dict = {}
655
+ nodes_bounds = {}
656
+ flow_info = {}
657
+
658
+ return parse_element(
659
+ bpmn_graph,
660
+ counts,
661
+ root,
662
+ [],
663
+ incoming_dict,
664
+ outgoing_dict,
665
+ nodes_dict,
666
+ nodes_bounds,
667
+ flow_info,
668
+ )
669
+
670
+
671
+ def apply(path, parameters=None):
672
+ """
673
+ Imports a BPMN diagram from a file
674
+
675
+ Parameters
676
+ -------------
677
+ path
678
+ Path to the file
679
+ parameters
680
+ Parameters of the algorithm
681
+
682
+ Returns
683
+ -------------
684
+ bpmn_graph
685
+ BPMN graph
686
+ """
687
+ if parameters is None:
688
+ parameters = {}
689
+
690
+ encoding = exec_utils.get_param_value(
691
+ Parameters.ENCODING, parameters, None
692
+ )
693
+
694
+ from lxml import etree, objectify
695
+
696
+ parser = etree.XMLParser(remove_comments=True, encoding=encoding)
697
+
698
+ F = open(path, "rb")
699
+ xml_tree = objectify.parse(F, parser=parser)
700
+ F.close()
701
+
702
+ return import_xml_tree_from_root(xml_tree.getroot())
703
+
704
+
705
+ def import_from_string(bpmn_string, parameters=None):
706
+ """
707
+ Imports a BPMN diagram from a string
708
+
709
+ Parameters
710
+ -------------
711
+ path
712
+ Path to the file
713
+ parameters
714
+ Parameters of the algorithm
715
+
716
+ Returns
717
+ -------------
718
+ bpmn_graph
719
+ BPMN graph
720
+ """
721
+ if parameters is None:
722
+ parameters = {}
723
+
724
+ encoding = exec_utils.get_param_value(
725
+ Parameters.ENCODING, parameters, constants.DEFAULT_ENCODING
726
+ )
727
+
728
+ if type(bpmn_string) is str:
729
+ bpmn_string = bpmn_string.encode(encoding)
730
+
731
+ from lxml import etree, objectify
732
+
733
+ parser = etree.XMLParser(remove_comments=True)
734
+ root = objectify.fromstring(bpmn_string, parser=parser)
735
+
736
+ return import_xml_tree_from_root(root)
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from pm4py.objects.bpmn.layout import variants, layouter
source_data/pinned/pm4py-process/tag-2.7.23.11/pm4py/objects/bpmn/layout/layouter.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ PM4Py – A Process Mining Library for Python
3
+ Copyright (C) 2026 Process Intelligence Solutions GmbH
4
+
5
+ This program is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU Affero General Public License as
7
+ published by the Free Software Foundation, either version 3 of the
8
+ License, or any later version.
9
+
10
+ This program is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ GNU Affero General Public License for more details.
14
+
15
+ You should have received a copy of the GNU Affero General Public License
16
+ along with this program. If not, see this software project's root or
17
+ visit <https://www.gnu.org/licenses/>.
18
+
19
+ Website: https://processintelligence.solutions
20
+ Contact: info@processintelligence.solutions
21
+ '''
22
+ from enum import Enum
23
+
24
+ from pm4py.objects.bpmn.layout.variants import graphviz, graphviz_new
25
+ from pm4py.util import exec_utils
26
+
27
+
28
+ class Variants(Enum):
29
+ GRAPHVIZ = graphviz
30
+ GRAPHVIZ_NEW = graphviz_new
31
+
32
+
33
+ DEFAULT_VARIANT = Variants.GRAPHVIZ_NEW
34
+
35
+
36
+ def apply(bpmn_graph, variant=DEFAULT_VARIANT, parameters=None):
37
+ """
38
+ Layouts a BPMN graph (inserting the positions of the nodes and the layouting of the edges)
39
+
40
+ Parameters
41
+ -------------
42
+ bpmn_graph
43
+ BPMN graph
44
+ variant
45
+ Variant of the algorithm to use, possible values:
46
+ - Variants.GRAPHVIZ
47
+ parameters
48
+ Parameters of the algorithm
49
+
50
+ Returns
51
+ -------------
52
+ bpmn_graph
53
+ BPMN graph with layout information
54
+ """
55
+ return exec_utils.get_variant(variant).apply(
56
+ bpmn_graph, parameters=parameters
57
+ )